【发布时间】:2016-11-04 02:23:10
【问题描述】:
有没有办法在 Django REST Framework 中使用 memcached 进行 TokenAuthentication。
我的用户令牌长时间(例如几个月)保持不变,因此不要为进入我的服务器的每个请求访问数据库并使用缓存的令牌获取用户对象是有意义的。
有没有一种巧妙的方法来实现这一点?
谢谢
【问题讨论】:
标签: django django-rest-framework
有没有办法在 Django REST Framework 中使用 memcached 进行 TokenAuthentication。
我的用户令牌长时间(例如几个月)保持不变,因此不要为进入我的服务器的每个请求访问数据库并使用缓存的令牌获取用户对象是有意义的。
有没有一种巧妙的方法来实现这一点?
谢谢
【问题讨论】:
标签: django django-rest-framework
您可以创建一个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):
...
【讨论】: