Django rest framework实现token登陆、修改

释放双眼,带上耳机,听听看~!
class AccountUserCreate(generics.CreateAPIView):
    queryset = AccountUser.objects.all()
    serializer_class = AccountUserSerializer
    def perform_create(self, serializer):
        auuser = User.objects.get(username=self.request.user)
        serializer.save(user_id = auuser.id)

class AccountUserRetrieveUpdate(generics.RetrieveUpdateAPIView):
    queryset = AccountUser.objects.all()
    serializer_class = AccountUserSerializer
    lookup_field = 'user_id'
    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())
        auuser = User.objects.get(username=self.request.user)
        filter_kwargs = {self.lookup_field:auuser.id}
        obj = get_object_or_404(queryset,**filter_kwargs)
        self.check_object_permissions(self.request, obj)

        return obj

class UserCreate(generics.CreateAPIView):
    serializer_class = UserSerializer
    def create(self, request, *args, **kwargs):
        user = User.objects.create(username=self.request.data['openid'])
        token = Token.objects.create(user=user)
        return Response(token.key, status=status.HTTP_201_CREATED)

为了解决token没有过期时间这个问题,我准备采用随机删除的方式删除一部的份token,由于没有登陆成功,客户端就会带上openid来登陆,此时只需检查更新·token

class UserCreate(generics.CreateAPIView):
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
if User.objects.get_or_create(username=self.request.data['openid']):
user = User.objects.get(username=self.request.data['openid'])
else:
user = User.objects.create(username=self.request.data['openid'])
#user = User.objects.get_or_create(username=self.request.data['openid'])
#user = User.objects.create(username=self.request.data['openid'])
if Token.objects.get(user=user):
return Response({'未更新token':'你的token没有过期'}, status=status.HTTP_201_CREATED)
else:
token = Token.objects.create(user=user)
return Response(token.key, status=status.HTTP_201_CREATED)

【转自慕课】https://www.imooc.com

Python

用 pop()方法遍历列表演示 Python while 语句执行过程

2022-3-3 13:27:51

Python

Python课堂笔记 第7章 包、模块、函数与变量作用域

2022-3-3 13:33:16

搜索