如何仅在特定方法上添加django rest框架权限? [英] How to add django rest framework permissions on specific method only ?
问题描述
我在用于用户模型的rest API中具有以下功能.我只想对POST请求设置AllowAny权限.有人可以帮我吗?
I have following functions in rest API for User model. I want to set AllowAny permission on only POST request. Can someone help me out.
class UserList(APIView):
"""Get and post users data."""
def get(self, request, format=None):
"""Get users."""
users = User.objects.all()
serialized_users = UserSerializer(users, many=True)
return Response(serialized_users.data)
def post(self, request, format=None):
"""Post users."""
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
推荐答案
You can write a custom Permission class IsPostOrIsAuthenticated
which will allow unrestricted access to POST
requests but will allow only authenticated GET
requests.
要实现自定义权限IsPostOrIsAuthenticated
,请覆盖BasePermission
类并实现.has_permission(self, request, view)
方法.如果应授予请求访问权限,该方法应返回True
,否则返回False
.
To implement the custom permission IsPostOrIsAuthenticated
, override the BasePermission
class and implement .has_permission(self, request, view)
method. The method should return True
if the request should be granted access, and False
otherwise.
from rest_framework import permissions
class IsPostOrIsAuthenticated(permissions.BasePermission):
def has_permission(self, request, view):
# allow all POST requests
if request.method == 'POST':
return True
# Otherwise, only allow authenticated requests
# Post Django 1.10, 'is_authenticated' is a read-only attribute
return request.user and request.user.is_authenticated
因此,所有POST
请求将被授予不受限制的访问权限.对于其他请求,将需要身份验证.
So, all POST
requests will be granted unrestricted access. For other requests, authentication will be required.
现在,您需要在全局设置中包括此自定义权限类.
Now, you need to include this custom permission class in your global settings.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'my_app.permissions.IsPostOrIsAuthenticated',
)
}
这篇关于如何仅在特定方法上添加django rest框架权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!