drf-jwt的简单使用
路由:
from django.contrib import admin
from django.urls import path
from app01 import views
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
path('reg/', views.reg.as_view()),
path('login/',obtain_jwt_token ),
path('index/',views.index.as_view()),
]
视图:
from app01.models import User
from rest_framework.authentication import authenticate
from rest_framework.views import APIView
from app01.userSerializers import UserSerializers
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
# Create your views here.
class reg(APIView):
def post(self, request, *args, **kwargs):
ser = UserSerializers(data=request.data)
if not ser.is_valid():
return Response("失败")
user = User.objects.create_user(**ser.data)
return Response("成功")
from rest_framework.permissions import BasePermission
from rest_framework.throttling import BaseThrottle, SimpleRateThrottle, AnonRateThrottle, UserRateThrottle
class index(APIView):
# 认证失败返回的是一个None 进入了self._not_authenticated() 返回了一个匿名用户,所以这里需要对权限和频率的一个验证
authentication_classes = [JSONWebTokenAuthentication, ]
# 任何用户都可以访问
parser_classes = [BasePermission, ]
# 注册用户与匿名用户访问的频率次数
throttle_classes = [AnonRateThrottle, UserRateThrottle, ]
def get(self, request, *args, **kwargs):
return Response('111111')
模型:
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser
#继承AbstractUser
class User(AbstractUser):
phone = models.CharField(max_length=11)
icon = models.ImageField(upload_to='icon')
序列化器:
from rest_framework import serializers
from app01.models import User
class UserSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password')
只是简单的使用,等会儿写一个基于JWT的自定义认证
浙公网安备 33010602011771号