2
votes

Is there a way to use memcached for TokenAuthentication with Django REST Framework.

My tokens for users stay same for long periods of time (months e.g.), and hence it makes sense not to hit the database for each request that comes in to my server, and get the user object using the cached token.

Is there a neat way of achieving this?

Thanks

1

1 Answers

2
votes

You can create a custom authentication class that hits memcached instead of you DB:

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)

Then you can use your own authentication class per view, ie:

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

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

        ...