手记

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)
1人推荐
随时随地看视频
慕课网APP

热门评论

老师,我就是不知道怎么做小程序登陆,可否具体指导,我给报酬

查看全部评论