django restful框架request.user有两种不同的类型和不同的值?

时间:2014-10-23 15:52:53

标签: django django-rest-framework

我是django-rest-framework的新手,我尝试了一个非常简单的网络应用

一个程序

url.py

urlpatterns = [
    url(r'^admin/$', "app.views.admin_index"),
]

views.py

def admin_index(request):
    print request
    print type(request.user)    
    return render(request, "admin/index.html")

输出

AnonymousUser
<class 'django.utils.functional.SimpleLazyObject'>

anthoner programe

url.py

urlpatterns = [
    url(r'^admin/$', AdminViewSet.as_view({'get':'list'})),
]

views.py

class AdminViewSet(viewsets.ViewSet):
    permission_classes = (permissions.IsAdminUser,)
    renderer_classes = (renderers.TemplateHTMLRenderer,)    
    def list(self, request):
        print request
        print type(request.user)
        return Response(template_name='admin/index.html')

输出

admin
<class 'django.contrib.auth.models.User'>

所以,request.user有两个不同的输出,最重要的是一个是AnonymousUser,另一个是admin,为什么?有什么不对吗?

======溶液========================

settings.py

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny'
    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )    
}

它有&#39; rest_framework.authentication.BasicAuthentication&#39;,因此它在http标头中创建request.user存储,但不在会话中,因此django.contrib.auth的注销失败。

解决方案仅使用&#39; rest_framework.authentication.SessionAuthentication&#39;

1 个答案:

答案 0 :(得分:1)

class 'django.utils.functional.SimpleLazyObject'是一种承诺。评估时,它将充当延迟对象的代理。这里没有错; django在很多地方使用这种类型来实现懒惰。