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

2021/5/18 20:55:39

本文主要是介绍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)


这篇关于djangorestframework_simplejwt4.6.0与django3.2.3+python3.9.4+djangorestframework3.12.4配置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程