Django REST Framework - TokenAuthentication - 缓存的使用

标签 django django-rest-framework

有没有办法通过 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/

相关文章:

django - Django Rest Framework View 集的 HTTP 方法

python - Django 中有没有办法直接从模型获取当前经过身份验证的用户?

digital ocean 上的 Django

python - Django "No Module Named URLs"错误

python - 在 get_queryset 中返回一个 Http 响应

python - 如何在 Django 中按日期范围过滤记录?

python - Django Celery AbortableTask 使用

python - 如何考虑 Django 的普通基于类的 View 与使用 REST API

Django REST 框架 : Unique_together validation on Serializers

django - 更新期间如何在 Django REST Framework 序列化程序中获取 changed_fields?