做这件事,需要两张表,一张存token值,一张存用户信息,详细看表

from django.db import models

# Create your models here.

class UserAuth(object):
    def authenticate_header(self, request):
        pass
    def authenticate(self, request):
        user_post_token = request.query_params.get('token')
        token_object = UserToken.objects.filter(token=user_post_token).first()
        if token_object:
            return token_object.user.user_name, token_object.token
        else:
            raise APIException("认证失败")


class User(models.Model):
    """
    存储用户信息
    """
    authentication_classes = [UserAuth]
  # 一定要写上这句话才生效,括号内是认证类名,其余的固定模式,别问为什么 user_name
= models.CharField(max_length=32) password = models.EmailField(max_length=32) user_type_entry = ( (1, 'Delux'), (2, 'SVIP'), (3, "VVIP") ) user_type = models.IntegerField(choices=user_type_entry) def __str__(self): return self.user_name class UserToken(models.Model): """ 存储用户登录的token值 """ user = models.OneToOneField("User", on_delete=models.CASCADE) token = models.CharField(max_length=128)

有了表之后,我们开始写视图函数,代码有点多,但是关键的就几句,着重看下

from django.http import JsonResponse
from rest_framework.views import APIView
from .models import User, UserToken
from app01 import get_token



class UserView(APIView):
    def post(self, request):
        response = dict()
        try:
            user_name = request.data['username']
            password = request.data['password']
            user_obj = User.objects.filter(user_name=user_name, password=password).first()
            if user_obj:
                access_token = get_token.generate_token()
                UserToken.objects.update_or_create(user=user_obj, defaults={"token": access_token})
                response["status_code"] = 200
                response["status_message"] = "登录成功"
                response["access_token"] = access_token
                response["user_role"] = user_obj.get_user_type_display()
            else:
                response["status_code"] = 201
                response["status_message"] = "登录失败,用户名或密码错误"
        except Exception as e:
            response["status_code"] = 202
            response["status_message"] = str(e)

        return JsonResponse(response)

最后设置下访问url

from django.contrib import admin
from django.urls import path, re_path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path('user', views.UserView.as_view())

]




文章结尾我说下,我这里用的是网页访问工具,POSTMAN,比较省事,如果有想通过网页的,可以自己搭建一个页面.
成功和失败分别给2张图