Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 访问request.user时django rest框架中的身份验证循环_Python_Django_Django Rest Framework_Django 1.7 - Fatal编程技术网

Python 访问request.user时django rest框架中的身份验证循环

Python 访问request.user时django rest框架中的身份验证循环,python,django,django-rest-framework,django-1.7,Python,Django,Django Rest Framework,Django 1.7,我在django rest framework 3.0.3中定义了一个自定义身份验证方案,如下所示: from django.contrib.auth.models import AnonymousUser from rest_framework import authentication class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request):

我在django rest framework 3.0.3中定义了一个自定义身份验证方案,如下所示:

from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication


class CustomAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        print 'authenticate!', request.user
        return (AnonymousUser(), None)
当我使用
CustomAuthentication
时,我得到一个“超过最大递归深度”错误,并将其打印在我的日志中:

authenticate! authenticate! authenticate! authenticate! authenticate! etc.
从我的打印语句中删除
request.user
,可以修复这个无限循环。在定义自定义身份验证方案时,我不应该使用
request.user

这表明:

request.user通常返回 django.contrib.auth.models.User,尽管行为取决于 正在使用的身份验证策略

如果请求未经身份验证,则默认值request.user为 django.contrib.auth.models.AnonymousUser的实例


我认为,当使用request.user时,它会检查请求是否有用户对象,并递归地继续调用自定义身份验证方法。您需要在函数中返回用户对象。

您应该使用
request.META.get('field')
从请求的标题中检索字段。@cziemba谢谢。当我做
user=request.META.get('user')
时,
user
None
匿名用户
user
的后代,我不认为这是问题所在。Returning
AnonymousUser
在过去对我有效,例如:对,但是line request.user在设置AnonymousUser对象之前出现,因此它会不断递归调用函数,不会到达return语句。感谢您的澄清。这是有道理的。我想通过查看DRF的
SessionAuthentication
:我需要查看
请求。\u request