Skip to main content
 首页 » 编程设计

python之无法从 JWT 导入 TokenObtainPairView、TokenRefreshView

2024年11月01日15oomusou

我想使用 Json Web token 身份验证。

但是当我导入时,它给我的错误是没有引用 TokenObtainPairView, TokenRefreshView,找到了,不过我安装了jwt。

urls.py:

   from django.contrib import admin 
   from django.urls import path 
   from rest_framework_jwt.views import ( 
     TokenObtainPairView, 
     TokenRefreshView, 
   ) 
    from django.conf.urls import url,include 
 
   urlpatterns = [ 
       path('admin/', admin.site.urls), 
       path('api/token/', TokenObtainPairView.as_view(),  
       name='token_obtain_pair'), 
       path('api/token/refresh/', TokenRefreshView.as_view(),  
       name='token_refresh'), 
       url(r'^auth/', include('authsystem.urls')) 

设置.py:

        REST_FRAMEWORK = { 
'DEFAULT_PERMISSION_CLASSES': ( 
    'rest_framework.permissions.IsAuthenticated', 
), 
'DEFAULT_AUTHENTICATION_CLASSES': ( 
    'rest_framework_simplejwt.authentication.JWTAuthentication', 
    'rest_framework.authentication.SessionAuthentication', 
), 

当我执行 pip freeze 时,我有包:

           Django==2.2.4 
           django-cors-headers==3.1.0 
           djangorestframework==3.10.2 
           djangorestframework-jwt==1.11.0 
           djangorestframework-simplejwt==4.3.0 
           Pillow==6.1.0 
           PyJWT==1.7.1 
           pytz==2019.2 
           sqlparse==0.3.0 

我尝试从不同的方式导入,但仍然找不到引用。

请您参考如下方法:

您从错误的框架导入它,您需要从 rest_framework_simplejwt.views 模块导入它,而不是 rest_framework_jwt.views 模块:

from <b>rest_framework_simplejwt</b>.views import ( 
    TokenObtainPairView, 
    TokenRefreshView, 
)

安装 djangorestframework-jwt 和 djangorestframework-simplejwt 是否有特定原因?