Django 1.5.1的login_required装饰器无法捕获未认证用户问题

2024-10-02 20:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常典型的view/login-required decorator实现,据报告,有时QA团队每天会遇到两次这样的错误:

ERROR: AttributeError at /plan/reviewplan/1702/ 'WSGIRequest' object has no 
attribute 'user' Request Method: GET Request URL: 
http://<ip>/plan/reviewplan/1702/ Django Version: 1.5.1

Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 187. 
response = middleware_method(request, response) 
File "/usr/local/lib/python2.6/dist-packages/debug_toolbar/panels/template.py" in process_response 118. pformat(k(self.request))) for k in get_standard_processors() 
File "/opt/ion/iondb/rundb/context_processors.py" in base_context_processor 25. 
if request.user: Exception Type: AttributeError at /plan/reviewplan/1702/ 
Exception Value: 'WSGIRequest' object has no attribute 'user' 

我检查了一下,视图实际上有一个需要登录的decorator。也有报道说,其他视图也被装饰成登录名。在

这些观点的回报是:

^{pr2}$

仅供参考:ctx实例存储在会话中,并且经常在视图调用之间更新。我继承了这个设计,对此我无能为力。处理此问题的函数是:

def _create_context_from_session(request, next_step_name):
    ctxd = request.session['saved_plan']
    ctxd['helper'] = request.session['plan_step_helper']
    ctxd['step'] = None
    if next_step_name in ctxd['helper'].steps:
        ctxd['step'] = ctxd['helper'].steps[next_step_name]
    context = RequestContext(request, ctxd)
    return context

Tags: inpyhelper视图responserequestsessionstep
1条回答
网友
1楼 · 发布于 2024-10-02 20:38:54

可能存储在会话中的上下文变量存储了一个旧的请求实例(没有user属性)?可能修改返回的上下文以包含当前请求,如下所示:

def _create_context_from_session(request, next_step_name):
    ctxd = request.session['saved_plan']
    ctxd['request'] = request  # Add this line.
    ...

你的^{里有"django.contrib.auth.context_processors.auth"吗?在

似乎还启用了调试工具栏。禁用调试工具栏时是否存在问题?在

同时:

调试工具栏正在其中间件中执行模板上下文处理器,并且您的上下文处理器之一尝试访问request.user。在

您能否修改此回溯中提到的行:

^{pr2}$

而不是if request.user:/opt/ion/iondb/rundb/context_processors.py文件中if request.user:执行if hasattr(request, 'user'):。在

"/opt/ion/iondb/rundb/context_processors.py"上下文处理器是否在"django.contrib.auth.context_processors.auth"之后执行?上下文处理器的执行顺序由TEMPLATE_CONTEXT_PROCESSORS设置定义。在

相关问题 更多 >