跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Django上下文处理器
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Django上下文处理器 = == 介绍 == '''Django上下文处理器'''(Context Processor)是一种向模板系统提供全局变量的机制,允许开发者在所有模板中自动访问特定数据,而无需在每个视图函数中重复传递这些数据。上下文处理器是Python可调用对象,接收<code>HttpRequest</code>对象作为参数,返回一个包含上下文变量的字典。 上下文处理器的主要应用场景包括: * 用户认证信息(如<code>request.user</code>) * 站点配置(如全局设置、品牌名称) * 国际化支持 * 购物车数据(电商场景) == 工作原理 == Django模板渲染流程中,上下文处理器在视图的<code>render()</code>调用时执行,其生成的字典会与视图传递的上下文合并: <mermaid> graph TD A[HttpRequest] --> B[上下文处理器] B --> C{合并上下文} D[视图上下文] --> C C --> E[模板渲染] </mermaid> 数学表示为:<math>最终上下文 = 视图上下文 \cup 处理器1上下文 \cup 处理器2上下文 \cup ...</math> == 内置上下文处理器 == Django默认提供以下常用处理器(位于<code>django.template.context_processors</code>): {| class="wikitable" |- ! 处理器名称 !! 提供变量 !! 说明 |- | <code>request</code> | <code>{{ request }}</code> | 当前请求对象 |- | <code>auth</code> | <code>{{ user }}</code> | 认证用户对象 |- | <code>debug</code> | <code>{{ debug }}</code> | 调试模式状态 |- | <code>i18n</code> | <code>{{ LANGUAGES }}</code> | 国际化支持 |} == 自定义上下文处理器 == === 基本示例 === 创建自定义处理器的步骤: 1. 在应用目录下新建<code>context_processors.py</code>文件 2. 编写处理器函数 3. 在<code>settings.py</code>中注册 <syntaxhighlight lang="python"> # myapp/context_processors.py def site_info(request): return { 'site_name': '我的学习网站', 'site_author': 'Python学习者', 'current_year': 2023 } </syntaxhighlight> 注册处理器: <syntaxhighlight lang="python"> # settings.py TEMPLATES = [ { 'OPTIONS': { 'context_processors': [ ... 'myapp.context_processors.site_info', ], }, }, ] </syntaxhighlight> === 高级示例 === 带数据库查询的处理器: <syntaxhighlight lang="python"> from django.contrib.sites.shortcuts import get_current_site from news.models import BreakingNews def global_news(request): try: current_site = get_current_site(request) return { 'breaking_news': BreakingNews.objects.filter( sites=current_site ).order_by('-publish_date')[:3] } except Exception: return {'breaking_news': []} </syntaxhighlight> == 实际应用案例 == === 场景1:用户主题偏好 === 存储用户选择的主题样式,在所有页面生效: <syntaxhighlight lang="python"> # accounts/context_processors.py from django.core.cache import cache def user_theme(request): if not request.user.is_authenticated: return {} cache_key = f"user_{request.user.id}_theme" theme = cache.get(cache_key) or 'light' return {'user_theme': theme} </syntaxhighlight> 模板中使用: <syntaxhighlight lang="django"> <link rel="stylesheet" href="/static/css/{{ user_theme }}.css"> </syntaxhighlight> === 场景2:电商平台全局数据 === 显示所有页面的购物车商品数量: <syntaxhighlight lang="python"> # cart/context_processors.py from .models import Cart def cart_items_count(request): if not request.user.is_authenticated: return {'cart_count': 0} count = Cart.objects.filter(user=request.user).count() return {'cart_count': count} </syntaxhighlight> 导航栏显示: <syntaxhighlight lang="django"> <a href="/cart/">购物车 ({{ cart_count }})</a> </syntaxhighlight> == 性能考虑 == 使用上下文处理器时需注意: 1. '''数据库查询''':避免在每个请求中执行昂贵查询 2. '''缓存策略''':对不常变化的数据使用缓存 3. '''处理器顺序''':后注册的处理器可能覆盖先前变量 优化方案示例: <syntaxhighlight lang="python"> from django.core.cache import cache def cached_site_config(request): config = cache.get('global_site_config') if not config: config = get_expensive_config() cache.set('global_site_config', config, 3600) return config </syntaxhighlight> == 测试上下文处理器 == 使用Django测试客户端验证处理器: <syntaxhighlight lang="python"> from django.test import RequestFactory, TestCase from myapp.context_processors import site_info class ContextProcessorTests(TestCase): def test_site_info_processor(self): request = RequestFactory().get('/') context = site_info(request) self.assertEqual(context['site_name'], '我的学习网站') self.assertEqual(context['current_year'], 2023) </syntaxhighlight> == 常见问题 == '''Q: 上下文处理器与中间件有何区别?''' A: 中间件处理请求/响应流程,而上下文处理器专门为模板提供数据。中间件可以修改请求对象,但无法直接向模板添加上下文。 '''Q: 如何禁用特定处理器的变量?''' A: 在<code>render()</code>中使用<code>context_instance</code>参数覆盖: <syntaxhighlight lang="python"> return render(request, 'template.html', context, context_instance=RequestContext(request, processors=[])) </syntaxhighlight> == 最佳实践 == 1. 保持处理器轻量级 2. 为处理器编写文档说明其用途 3. 避免业务逻辑耦合 4. 使用有意义的变量名防止冲突 5. 考虑使用<code>@functools.lru_cache</code>装饰器缓存结果 == 进阶主题 == 对于需要更复杂场景的开发者,可以探索: * 动态处理器注册 * 基于类的上下文处理器 * 与Django REST框架的集成 * 异步上下文处理器(Django 3.1+) [[Category:后端框架]] [[Category:Django]] [[Category:Django高级特性]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)
该页面使用的模板:
模板:Debug
(
编辑
)
模板:LANGUAGES
(
编辑
)
模板:Request
(
编辑
)
模板:User
(
编辑
)