所以,我想制作Anon或非管理员只能POST的端点。 端点是:
我已经获得了自定义权限并将其应用到基于类的视图中。
#permissions.py
from rest_framework import permissions
class AnonWriteOnly(permissions.BasePermission):
"""
Anon can only post
"""
def has_object_permission(self, request, view, obj):
# Only allow post request
allowed_methods = ('POST')
if request.method in allowed_methods:
print (True) #debugging purpose
return True
print(False) #debugging purpose
return permissions.IsAuthenticated.has_permission(self, request, view)
这是我的观点:
# Anon can post.
#Corresponds to the first endpoint
class KeywordList(generics.ListCreateAPIView):
"""
List all keywords, or create a new keyword
"""
permission_classes = [AnonWriteOnly]
queryset = Keyword.objects.all()
serializer_class = KeywordSerializer
#Corresponds to the second endpoint
class KeywordDetail(generics.RetrieveDestroyAPIView):
"""
Retrieve, update, delete keyword
"""
permission_classes = [AnonWriteOnly]
queryset = Keyword.objects.all()
serializer_class = KeywordSerializer
当我没有登录并尝试打开第二个端点时,它可以正常工作。它有403响应,输出也被打印。
False
[27/May/2018 18:14:33] "GET /api/v1/keyword/1 HTTP/1.1" 403 10621
但是,当我尝试打开第一个端点时,它没有打印任何东西,它只是在未经许可的情况下正常运行。
[27/May/2018 18:28:02] "GET /api/v1/keywords/ HTTP/1.1" 200 13256
我试图更改权限.IsAuthenticated为permissions.IsAdminUser但仍然没有运气。
但是,通过覆盖has_permission
可以正常工作from rest_framework import permissions
class AnonWriteOnly(permissions.BasePermission):
"""
Anon can only post
"""
def has_permission(self, request, view):
# Only allow post request
allowed_methods = ('POST')
if request.method in allowed_methods:
print (True)
return True
print(False)
return request.user.is_staff
为什么不使用has_object_permission?
答案 0 :(得分:2)
有两件事:
allowed_methods = ('POST',)
你忘了逗号(如果没有逗号它只是字符串,但如果有逗号则是元组)
has_object_permissions - DRF在您想要获取对象时调用它,而不是创建对象。