在用戶未登錄時如何最好地訪問內容。例如,我有一個處理串列和發布博客文章的視圖,盡管我希望有人即使沒有登錄也能訪問內容,盡管該人不應該創建博客文章,除非已登錄。
以下是我目前的實作:
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
queryset = Post.objects.all()
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data, context=request)
if serializer.is_valid():
serializer.save()
return response.Response(serializer.data,
status=status.HTTP_201_CREATED, )
return response.Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
那么我如何最好地使用這些線條:
authentication_classes = (JWTAuthentication,)
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
編輯 :
因為當我洗掉這一行時:
authentication_classes = (JWTAuthentication,)
我無法訪問博客串列,我收到以下回復:
{
"detail": "You do not have permission to perform this action."
}
雖然我需要一個創建博客文章的端點來受到保護,但如何最好地實作這一點
uj5u.com熱心網友回復:
通過繼承permissions.BasePermission類創建自定義權限并has_permission根據您的要求覆寫方法。
class PostsProtectOrReadOnly(permissions.BasePermission):
def has_permission(self, request, view):
if request.method not in permissions.SAFE_METHODS\
and not request.user.is_authenticated:
return False
return True
的permissions.SAFE_METHODS是含有一個元組GET,HEAD及OPTIONS它們基本上方法只讀方法。因此,如果用戶請求創建新條目,則使用的方法將POST是不被視為安全方法的方法。并檢查用戶是否已登錄,請使用request.user.is_authenticated.
現在為您的 api 視圖使用自定義權限。
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = (PostsProtectOrReadOnly,)
queryset = Post.objects.all()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334387.html
