我正在尝试验证通过 Web API 接口(interface)在 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',
)
}
我的客户应用程序中的身份验证类如下所示:
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!”
如何将 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
这有点 hacky,因为我试图通过拆分关于 '/'
的 request.path
来访问 guid
并访问第三个 -分割后获得的列表的最后一个索引。
我已经检查过,self
无法访问我们通常在 DRF View 中获取的 kwargs
,因此我们无法访问 kwargs
这里。
另一种解决方案是在调用 authenticate()
时通过覆盖 DRF 的身份验证过程在 DRF View 中显式传递 kwargs
。
关于Python Django Rest 框架身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30841580/