2016-07-01 4 views
2

Django RESTフレームワークでTokenAuthenticationにmemcachedを使用する方法はありますか?Django RESTフレームワーク - TokenAuthentication - キャッシュの使用

ユーザーのトークンは、長期間(例:月間)同じであるため、サーバーに送信されるリクエストごとにデータベースにヒットせず、キャッシュされたトークンを使用してユーザーオブジェクトを取得できます。

これを達成するためのきちんとした方法はありますか?

おかげ

答えて

2

あなたは代わりにあなたDBのmemcachedのヒットcustom authentication classを作成することができます。

class ExampleAuthentication(authentication.BaseAuthentication): 
    def authenticate(self, request): 
     token = request... # get your token here 
     if not token: 
      return None 

     try: 
      # user = User.objects.get(username=username) -> This is the original code from the link above 
      user = ... # get your user based in token here 
     except User.DoesNotExist: # some possible error 
      raise exceptions.AuthenticationFailed('No such user') 

     return (user, None) 

その後、すなわち、ビューごとに独自の認証クラスを使用することができます。

class ExampleApiView(APIView): 
    authentication_classes = (CustomTokenAuthentication,) 

    def get(self, request, *args, **kwargs): 

     ... 
関連する問題