Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.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
Django 有条件地向DRF视图验证用户_Django_Rest_Authentication_Django Rest Framework_Api Design - Fatal编程技术网

Django 有条件地向DRF视图验证用户

Django 有条件地向DRF视图验证用户,django,rest,authentication,django-rest-framework,api-design,Django,Rest,Authentication,Django Rest Framework,Api Design,我的DRF观点如下: class DocumentsView(generics.ListCreateAPIView): permission_classes = () authentication_classes = () # I typically enforce authentication with # authentication_classes = (JWTCookieAuthentication,) def list(self, reque

我的DRF观点如下:

class DocumentsView(generics.ListCreateAPIView):
    permission_classes = ()
    authentication_classes = ()
    # I typically enforce authentication with 
    # authentication_classes = (JWTCookieAuthentication,)

    def list(self, request):
        pagination_class = None
        
        if request.user.is_authenticated: 
           ... return protected data ...
        else:
           ... return generic data ...
我希望允许发送有效令牌的用户和未发送有效令牌的用户都从该端点获得响应。但是,
request.user.is_authenticated
返回
False
,即使发送了有效令牌(我理解原因)。如何尝试对用户进行身份验证,但即使不提供令牌,仍允许他们继续


或者更好的做法是不对未经身份验证的用户使用相同的视图?

您想要的是拥有无权限,但仍然执行身份验证

验证验证令牌、从数据库获取用户等。如果禁用它,则不会执行令牌/etc检查。这意味着
请求。用户
将始终等于
匿名用户

class MyView(ListCreateApiView):
    permissions_classes = [AllowAny]
    

值得考虑使用
AllowAny
作为您的许可。这与使用空白列表相同,但清楚地表明您的意图是公开视图,而不是错误。

但是,request.user.is\u authenticated返回False,即使发送了有效令牌(我理解原因)。我不。身份验证后端是否没有让用户登录,或者身份验证中间件是否没有运行?@Melvyn,因为视图中的身份验证类=()覆盖了我的默认身份验证类