django接入djangorestframework-simplejwt步骤

版本:django 4.2 python: 3.8

安装

python 复制代码
pip install djangorestframework-simplejwt

user子应用models.py文件

python 复制代码
from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
	mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号'  # unique 唯一索引,此处不能用IngeterField
	avatar = models.ImageField(upload_to='avatar', verbose_name='用户头像'
	WeChat= models.CharField(max_length=64, blank=True, null=True, verbose_name='微信号')

	class Meta:
		db_table='user' # 自己定义名称
		verbose_name = '用户信息'
		verbose_name_plural = verbose_name

配置settings

python 复制代码
REST_FRAMEWORK = {
	# 全局配置,若不需要可不配置,但在下面的views.py中,需要配置authentication_classes和permission_classes
	'AUTHENTICATION_CLASSES': (
		'rest_framework_simplejwt.authentication.JWTAuthentication', 
	),
	'PERMISSION_CLASSES': [
		'rest_framework.permissions.IsAuthenticated',
	]
}
from datetime import timedelta
SIMPLE_JWT= {
	'ACESS_TOKEN_LIFETIME': timedelta(hours=5),
	'REFRESH_TOKEN_LIFETIME': timedelta(day=1),
	'ROTATE_FEFRESH_TOKENS':False,
	'AUTH_HEADER_TYPES': ('Bearer',),
}
# 注册自定义的User表,格式为:应用名。表模型
AUTH_USER_MODEL = 'user.User'

配置urls

python 复制代码
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
	path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
	path('token/refresh/', TokenRefreshView.as_view(), name='token_obtain_pair'),
]

以上,djangorestframework-simplejwt即配置完成,注意,在子应用中的views.py文件写视图函数的时候,需要加上`authentication_classes`以及`permission_classes`。

python 复制代码
# views.py
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication

from .models import Banner
from .serializers import BannerModelSerializer

class BannerAPIView(ListAPIView):
	queryset = Banner.objects.filter(is_show=True, is_delete=False).order_by('-orders','-id)[: 3]  # 筛选前3个图片兵役orders和id倒叙排列
	serializer_class = BannerModelSerializer
	authentication_classes = [JWTAuthentication]  # 此处必须是列表或元组,若全局有配置,则可省略这一步
	permission_classes = [IsAuthenticated]  # 此处必须是列表或元组,若全局有配置,则可省略这一步

# serializers.py
from rest_framework import serializer
from .models import Banner

class BannerSerializer(serializers.ModelSerializer):
	class Meta:
		model = Banner
		fields = '__all__'
相关推荐
CodeDevMaster1 年前
Django之JWT库与SimpleJWT库的使用
后端·python·django·jwt·simplejwt