Python 访问request.user时django rest框架中的身份验证循环
我在django rest framework 3.0.3中定义了一个自定义身份验证方案,如下所示: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):
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
的后代,我不认为这是问题所在。ReturningAnonymousUser
在过去对我有效,例如:对,但是line request.user在设置AnonymousUser对象之前出现,因此它会不断递归调用函数,不会到达return语句。感谢您的澄清。这是有道理的。我想通过查看DRF的SessionAuthentication
:我需要查看请求。\u request
。