有没有办法在Django REST Framework中使用memcached进行TokenAuthentication。
我的用户令牌在很长一段时间内保持相同(例如几个月),因此有意义的是不要为进入我的服务器的每个请求点击数据库,并使用缓存的令牌获取用户对象。
有没有一种巧妙的方法来实现这一目标?
由于
答案 0 :(得分:2)
您可以创建一个custom authentication class来命中memcached而不是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)
然后,您可以在每个视图中使用自己的身份验证类,即:
class ExampleApiView(APIView):
authentication_classes = (CustomTokenAuthentication, )
def get(self, request, *args, **kwargs):
...