Django-restframework登陆认证 token

【urls】

urlpatterns = [
    re_path('^api/v1/auth/$', AuthView.as_view()),
]

【models】

############  用户登陆与认证  #########################################################
class UserInfo(models.Model):
    user_type_choices=(
        (1,'普通用户'),
        (2,'VIP'),
        (3,'SVIP'),
    )
    usertype=models.IntegerField(choices=user_type_choices)
    username=models.CharField(max_length=20)
    password=models.CharField(max_length=32)

    class Meta:
        managed=True


class UserToken(models.Model):
    token = models.CharField(max_length=300)
    user = models.OneToOneField(to='UserInfo', on_delete=models.CASCADE)

    class Meta:
        managed=True

建完数据库模型后,执行以下命令生成数据库:
【django的manage.py同级目录下执行命令,生成迁移文件】python3 manage.py makemigrations --empty appname
【django的manage.py同级目录下执行命令,生成数据库】python3 manage.py migrate appname

【views】


############  用户登陆与认证  #########################################################
from django.http import JsonResponse
from .models import UserInfo, UserToken
from rest_framework.views import APIView

# 创建md5摘要
def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf8'))
    m.update(bytes(ctime, encoding='utf8'))
    return m.hexdigest()

# APIView继承自rest_framework.views,APIView继承自Django的View
class AuthView(APIView):
    def post(self, request, *args, **kwargs):
        ret = {'code':1000, 'msg':None}
        try:
            user = request._request.POST.get('username')
            pwd = request._request.POST.get('password')
            obj = UserInfo.objects.filter(username=user, password=pwd).first()
            if not obj:
                ret['code'] = 1001
                ret['msg'] = '用户名或密码错误'

            token = md5(user=user)

            # token表中更新或创建用户对应的token
            UserToken.objects.update_or_create(user=obj, defaults={'token':token})
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = '异常错误'
            pass
        return JsonResponse(ret)
    
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读