我已经在我的 django react 项目中添加了 JWT 身份验证。 我想要实现的是,我想在没有身份验证的情况下公开一些 API。 这是一个电子商务项目,我想公开类别列表API,以便任何人都可以在没有身份验证的情况下访问。
settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':[
#'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
#'rest_framework.authentication.SessionAuthentication',
# 'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.IsAuthenticated',
#'rest_framework.permissions.AllowAny',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE':10,
}
views.py:
@permission_classes((IsAuthenticated,))
class UserViewSet(viewsets.ModelViewSet):
queryset = CustomUser.objects.all()
serializer_class = serializers.UserSerializer
#User Registration View
class CreateUserView(generics.CreateAPIView):
model = get_user_model()
permission_classes = [
permissions.AllowAny
]
serializer_class = serializers.RegisterSerializer
#Category Listing View
@permission_classes((IsAuthenticated,))
class CategoryView(generics.ListCreateAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializers
class CategoryDetailView(generics.RetrieveUpdateAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializers
还想从类别列表中删除分页
您可以使用decorators
将authentication_class
和permission_class
设置为无:
from rest_framework.decorators import authentication_classes, permission_classes
class CategoryView(generics.ListCreateAPIView):
authentication_classes = []
permission_classes = []
pagination_class = None
queryset = Category.objects.all()
serializer_class = CategorySerializers
由于ListCreateAPIView是genericViewSet的扩展,因此您可以设置pagination_class