如何仅在特定方法上添加django rest框架权限?

编程入门 行业动态 更新时间:2024-10-26 21:33:51
本文介绍了如何仅在特定方法上添加django rest框架权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在用于用户模型的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)

推荐答案

您可以编写自定义权限类 IsPostOrIsAuthenticated ,它将允许不受限制地访问POST请求,但仅允许通过身份验证的GET请求.

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框架权限?

本文发布于:2023-07-15 02:00:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1108368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框架   权限   方法   在特定   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!