我正在尝试验证通过Web API接口在URL中传递的GUID。但是,我没有设法将GUID传递给我的Authenticate类。

注意:通过身份验证是指确保它是有效的GUID

我的urls.py:

 url(r'^customer_address/(?P<guid>[a-z0-9-]+)/(?P<address_id>[a-z0-9-]+)/$',
    views.CustomerAddressView.as_view()),


我的views.py:

class CustomerAddressView(generics.RetrieveAPIView):
    lookup_field = "address_id"
    queryset = CustomerAddress.objects.all()
    serializer_class = CustomerAddressSerializer


我的settings.py:

REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'customer.authenticate.Authenticate',
        ),
         'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
         )
}


我的客户应用程序中的Authenticate类如下所示:

class Authenticate(authentication.BaseAuthentication) :
    def authenticate(self, request):

        request = request._request
        guid = getattr(request, 'guid', None)


        my_logger.debug(guid)


        if not guid:
            my_logger.debug('There is no guid!')
            return None


        try:
            user = Customer.objects.get(guid=guid,brand=1)
        except Customer.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

        return None


请求看起来像这样:



问题:
我喜欢在Authenticate类中检索GUID,并确保其有效。目前,我不断收到您在屏幕截图中看到的错误,我的日志显示为:“没有向导!”

如何将guid从请求传递到Authenticate类?

谢谢

最佳答案

你可以这样做:

class Authenticate(authentication.BaseAuthentication) :
    def authenticate(self, request):

        request = request._request

        # This is a bit hacky way to get value of guid
        guid = request.path.split('/')[-3]

        my_logger.debug(guid)

        if not guid:
            my_logger.debug('There is no guid!')
        return None

        try:
            user = Customer.objects.get(guid=guid,brand=1)
        except Customer.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

    return None


因为我试图通过将guid拆分为request.path来访问'/',并访问拆分后获得的列表的倒数第三索引,所以这有点hacky。

我已经检查过,self无法访问通常在DRF视图中获得的kwargs,所以我们在这里不能访问kwargs

另一种解决方案是,通过覆盖DRF的身份验证过程,在调用kwargs时在DRF视图中显式传递authenticate()

关于python - Python Django Rest Framework身份验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30841580/

10-16 03:12