ImportError: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'smart_text' from 'django.utils.encoding'
# settings.py 部分代码
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'web.apps.WebConfig',
'RestFramework.apps.RestframeworkConfig',
'rest_framework',
'rest_framework_simplejwt'
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
# 'rest_framework.authentication.TokenAuthentication',
)
}
SIMPLE_JWT = {
# token有效时长(返回的 access 有效时长)
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=30),
# token刷新的有效时间(返回的 refresh 有效时长)
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(seconds=20),
}
# urls.py部分代码
from web.views import Login, task, hello_request, world_request
from web.views import DemoView
from RestFramework.views import DefectList
from RestFramework.views import DefectDetail
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView
from rest_framework import routers, serializers, viewsets
from django.contrib.auth.models import User
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = [
path("admin/", admin.site.urls),
path('', include(router.urls)),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
path('defects/', DefectList.as_view()), # 此接口的作用是返回缺陷表中的全部记录
path('defect//', DefectDetail.as_view()), # 此接口的作用是对某条缺陷记录进行修改和删除
]
# views.py 部分代码
from RestFramework.models import Defect
from RestFramework.serializers import DefectSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class DefectList(APIView): # APIView 是RESTFramework提供的所有视图的基类,继承自Django的View父类。
def get(self, request):
defects = Defect.objects.all()
serializer = DefectSerializer(defects, many=True)
return Response(serializer.data)
def post(self, request):
serializer = DefectSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# 用于完成单条记录的请求处理
class DefectDetail(APIView):
def get_object(self, request, bug_code):
"""
由于后续代码需要反复获取一条缺陷记录,因此将该操作定义为一个公共的函数,bug_code 参数代表需要提取的缺陷编号
"""
try:
return Defect.objects.get(bug_code=bug_code) # 如果找到了传入缺陷编号所对应的数据记录,将其返回
except Defect.DoesNotExist:
raise Http404
def get(self, request, bug_code):
defect = self.get_object(self, bug_code) # 返回缺陷编号对应的一条缺陷记录对象
serializer = DefectSerializer(defect) # 对缺陷记录对象进行序列化
return Response(serializer.data) # 装饰序列化的JSON数据作为HTTP的响应内容返回
def put(self, request, bug_code):
defect = self.get_object(self, bug_code) # 返回缺陷编号对应的一条缺陷记录对象
serializer = DefectSerializer(defect, data=request.data) # 对缺陷数据进行序列化处理
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, bug_code):
defect = self.get_object(self, bug_code) # 返回缺陷编号对应的一条缺陷记录对象
defect.delete()
return Response(status=status.HTTP_204_NO_CONTENT) # 代表无内容(因为已经被删除了)
JWT授权为啥要在 Authorization标头里加个Bearer 呢_authorization bearer_小白de成长之路的博客-CSDN博客