为了账号安全,请及时绑定邮箱和手机立即绑定

Django rest framework实现token登陆、修改

标签:
Python
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人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消