继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Django rest framework实现token登陆、修改

无无法师
关注TA
已关注
手记 44
粉丝 54
获赞 130
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)
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP

热门评论

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

查看全部评论