2015-06-15 152 views
1

我正在嘗試驗證通過Web API接口傳遞到url中的GUID。不過,我並沒有設法通過GUID到我的驗證類。Python Django Rest Framework身份驗證

注:通過驗證我的意思是確保它是一個有效的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 

和請求如下:

enter image description here

問題: 我喜歡在clas中檢索GUID驗證並確保其有效。此刻,我不斷收到你在屏幕截圖中看到的錯誤,並且我的日誌中顯示:'沒有guid!

如何將GUID從請求傳遞到Authenticate類?

感謝

+1

檢查你是否可以自己訪問'kwargs'。 ''guid = self.kwargs.get('guid',None)' –

+0

我檢查過,''authenticate()'中沒有DRF視圖的'kwargs'。我已經更新了我的答案。另一種解決方案是在調用時將視圖的'kwargs'傳遞給'authenticate()'。 –

回答

1

你可以這樣做:

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 

這是一個有點哈克,因爲我試圖通過拆分request.path'/'訪問​​和訪問後得到的列表的第三最後一個索引分裂。

我查過,self有權訪問我們通常在DRF視圖中獲得的kwargs,因此我們無法在此處訪問kwargs

當重寫DRF的認證過程調用authenticate()時,另一種解決方案是在DRF視圖中明確傳遞kwargs