博客五部曲之三 - 博客RESTful


1523 浏览 5 years, 2 months

31 Django Rest Framework Settings

版权声明: 转载请注明出处 http://www.codingsoho.com/

Django Rest Framework Settings

在Serializer里,我们有很多重复的设置,有些可以直接通过在settings里统一设置完成。

http://www.django-rest-framework.org/api-guide/settings/

JSONRenderer和 BrowsableAPIRenderer支持json和html两种浏览格式

IsAuthenticatedOrReadOnly被广泛使用,可以把它设为默认权限类

src/blog/settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    # 'DEFAULT_PARSER_CLASSES': (
    #     'rest_framework.parsers.JSONParser',
    # )
    "DEFAULT_AUTHENTICATION_CLASSES": (
         'rest_framework.authentication.SessionAuthentication',
        #'rest_framework.authentication.BasicAuthentication'
    ), 
    "DEFAULT_PERMISSION_CLASSES": (
         'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    )
}

对应的IsAuthenticated和IsAuthenticatedOrReadOnly都可以被注销,保留与默认权限类不一样的。
记得给ListView添加权限类AllowAny,否则他们会使用默认权限类

src/comments/api/views.py

class CommentCreateAPIView(CreateAPIView):
    # permission_classes = [IsAuthenticated]

class CommentDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView):
    # permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    permission_classes = [IsOwnerOrReadOnly]

class CommentListAPIView(ListAPIView):
    permission_classes = [AllowAny]

src/posts/api/views.py

class PostCreateAPIView(CreateAPIView):
    #permission_classes = [IsAuthenticated]

class PostDetailAPIView(RetrieveAPIView):
    permission_classes = [AllowAny]

class PostUpdateAPIView(RetrieveUpdateAPIView):
    # permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    permission_classes = [IsOwnerOrReadOnly]

class PostDeleteAPIView(DestroyAPIView):
    # permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    permission_classes = [IsOwnerOrReadOnly]

class PostListAPIView(ListAPIView):
    permission_classes = [AllowAny]

src/accounts/api/views.py

class UserCreateAPIView(CreateAPIView):
    permission_classes = [AllowAny]