DRF - 用户登录加 token
实现:用户登录成功后,对应的 token 表创建一条对应登录用户的 token 数据
models.py:
from django.db import models class UserInfo(models.Model): user_type_choices = ( (1, "普通用户"), (2, "管理员"), (3, "超级用户"), ) user_type = models.IntegerField(choices=user_type_choices) username = models.CharField(max_length=32, unique=True) password = models.CharField(max_length=64) class UserToken(models.Model): user = models.OneToOneField(to="UserInfo", on_delete=models.DO_NOTHING) token = models.CharField(max_length=64)
在 UserInfo 表中添加三条数据
views.py:
from rest_framework.views import APIView from django.http import JsonResponse from drf import models import hashlib, time # 给 token 进行加密处理 def token_md5(user): ctime = str(time.time()) # 当前时间 m = hashlib.md5(bytes(user, encoding="utf-8")) m.update(bytes(ctime, encoding="utf-8")) # 加上时间戳 return m.hexdigest() class AuthView(APIView): def post(self, request, *args, **kwargs): response = {"code": 1000, "msg": None} try: username = request._request.POST.get("username") password = request._request.POST.get("password") user_obj = models.UserInfo.objects.filter(username=username, password=password).first() if not user_obj: response["code"] = 10001 response["msg"] = "用户名或密码错误" token = token_md5(username) # 给登录用户创建 token # 不存在就创建,存在就更新 models.UserToken.objects.update_or_create(user=user_obj, defaults={"token": token}) response["token"] = token except Exception as e: response["code"] = 1002 response["msg"] = "出现未知错误" return JsonResponse(response)
urls.py:
from django.urls import path from drf import views urlpatterns = [ path('api/auth/', views.AuthView.as_view()), ]
访问 http://127.0.0.1/api/auth/ :
发送 post 请求:
token 表生成了一条数据: