有没有办法通过 Django REST Framework 使用 memcached 进行 TokenAuthentication。
我的用户 token 在很长一段时间内(例如几个月)保持不变,因此对于进入我的服务器的每个请求不访问数据库并使用缓存的 token 获取用户对象是有意义的。
有没有一种巧妙的方法来实现这一目标?
谢谢
最佳答案
您可以创建 custom authentication class命中 memcached 而不是你的数据库:
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)
然后您可以在每个 View 中使用自己的身份验证类,即:
class ExampleApiView(APIView):
authentication_classes = (CustomTokenAuthentication, )
def get(self, request, *args, **kwargs):
...
关于Django REST Framework - TokenAuthentication - 缓存的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38149369/