django-rest-framework用户认证(jwt)

drf框架下的jwt用户认证

  • jwt

jwt

json web token ,一般用于用户认证(前后端分离,微信小程序,app开发)

首先,从项目的urls.py中分发路由至app中,再创建两个url。
urls.py

from django.urls import path,re_path

from . import views

urlpatterns = [

    re_path(r'login/$',views.LoginView.as_view()),
    re_path(r'order/$', views.OrderView.as_view())

]

接着,在models.py中创建用户表User
models.py

from django.db import models

class User(models.Model):
    SEX_CHOICES = [
        [0,'男'],
        [1,'女'],
    ]

    name = models.CharField(max_length=64)
    pwd = models.CharField(max_length=32)
    phone = models.CharField(max_length=11, null=True, default=None)
    sex = models.IntegerField(choices=SEX_CHOICES,default=0)
    icon = models.ImageField(upload_to='icon',default='icon/default.jpg')
    token = models.CharField(max_length=64,null=True,blank=True)

    class Meta:
        db_table = 'user'
        verbose_name='用户'
        verbose_name_plural = verbose_name #复数形式

    def __str__(self):
        return  '%s' % self.name

接着进行数据库迁移:

python manage.py makemigrations
python manage.py migrate 

API/views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from . import models
import uuid


class LoginView(APIView):
    '''用户登录'''
    def post(self, request, *args, **kwargs):
        name = request.data.get("username")
        pwd = request.data.get("password")

        user_object = models.User.objects.filter(name = name,pwd = pwd).first()
        if not user_object:
            return Response({ 'code':1000,'error':'用户名或密码错误' })

        random_string = str(uuid.uuid4())
        #token认证
        user_object.token = random_string
        user_object.save()
        return Response({ 'code':1001,'data':random_string })

class   OrderView(APIView):
    def get(self,request,*args,**kwargs):
        token = request.query_params.get("token")
        if not token:
            return Response({ 'code':2000,'error':'登录成功才能访问' })
        user_object = models.User.objects.filter(token=token).first()
        if not user_object:
            return Response({'code':2000,'error':'token无效'})
        return Response('订单列表')

最后运行服务器:

python manage.py runserver

可使用postman对注册的个url进行收发数据。。。

你可能感兴趣的:(django)