编程语言
首页 > 编程语言> > djangorestframework_simplejwt4.6.0与django3.2.3+python3.9.4+djangorestframework3.12.4配置

djangorestframework_simplejwt4.6.0与django3.2.3+python3.9.4+djangorestframework3.12.4配置

作者:互联网

djangorestframework_simplejwt4.6.0与django3.2.3+python3.9.4+djangorestframework3.12.4配置(部分代码省略只展示重点部分)

虚拟环境中安装 pip3 install djangorestframework_simplejwt(这里其它配置不做详细说明只配置djangorestframework_simplejwt)

1.settings.py配置文件设置

REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',  
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework_simplejwt.authentication.JWTAuthentication',  
        'rest_framework.authentication.BasicAuthentication',  
        'rest_framework.authentication.SessionAuthentication',  
   ]
}
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=7),  # 配置ACCESS过期时间7天
    'REFRESH_TOKEN_LIFETIME': timedelta(days=15),  # 配置REFRESH过期时间15天
    'ROTATE_REFRESH_TOKENS': True,  # 循环刷新令牌
}
2.views.py中配置

from rest_framework_simplejwt.authentication import JWTAuthentication  # 用户token验证,放入当前view中就不会全局验证
from rest_framework.authentication import SessionAuthentication  

class UserFavViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
                     mixins.DestroyModelMixin, viewsets.GenericViewSet):
   authentication_classes = (JWTAuthentication, SessionAuthentication)  # 配置登录认证    
   def get_queryset(self):  # 获取当前用户列表(queryset)
      return UserFav.objects.filter(user=self.request.user)

 

3.urls.py中配置

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView
)
urlpatterns = [
    path('login/', TokenObtainPairView.as_view(), name='token_obtain_pair'),  
]

4.uni-app前端中使用

// 请求用户信息

getUsetInfo(token) {
            uni.request({
                url: 'https://www.xxx.com' + '/user/', //仅为示例,并非真实接口地址。
                data: {},
                header: {
                    'Authorization': 'Bearer ' + token  
                }, //注意:JWT后面必需有个空格
                success: (res) => {

              }

}

5.生成token

from rest_framework_simplejwt.tokens import RefreshToken  # 生成token
class UserViewset(CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
 def create(self, request, *args, **kwargs):  # 注册后生成token自动登录
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = self.perform_create(serializer)
    re_dict = serializer.data

    refresh = RefreshToken.for_user(user)  # 生成token
    re_dict["refresh"] = str(refresh)
    re_dict["access"] = str(refresh.access_token)
    re_dict["name"] = user.name if user.name else user.id  # 如果有名字就返回没有就显示用户Id

    headers = self.get_success_headers(serializer.data)
    return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

标签:djangorestframework3.12,simplejwt4.6,mixins,token,rest,framework,djangorestframe
来源: https://blog.csdn.net/qq_16800845/article/details/116999051