python - 使用 Django 对象权限时,如何使用 django-rest 框架添加非模型/查询集返回 View ?

标签 python django api permissions django-rest-framework

我有一个想要添加到我的 django-restframework api 中的 View ,该 View 与任何模型都不相关。虽然我在 DEFAULT_PERMISSION_CLASSES 中使用“rest_framework.permissions.DjangoObjectPermissions”。

class EnumChoices(views.APIView):       
    def get(self, request):
        enums = {}
        return Response(enums)

现在 Django 提示我的观点:

AssertionError at /api/enums/
Cannot apply DjangoModelPermissions on a view that does not have `.queryset` property or overrides the `.get_queryset()` method.

我需要几乎所有其他 View 的权限类,并且不想删除它。如何绕过单一 View 的强制属性?

最佳答案

您可以添加特定于 View 的权限逻辑来覆盖模型权限检查。创建一个 BasePermission 类对象并将其添加到您的 View permission_classes 属性中。不要忘记 IsAuthenticated,除非您也想允许匿名用户。

class EnumChoices(views.APIView):
    class EnumPermission(permissions.BasePermission):
        def has_permission(self, request, view):
            # whatever permission logic you need, e.g.
            return request.user.has_perm("planning.view_enums")
    permission_classes = (permissions.IsAuthenticated, EnumPermission)

    def get(self, request):
        enums = {}
        return Response(enums)

现在 View 将确保用户经过身份验证并具有 view_enums 权限。

更多信息请点击:http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

关于python - 使用 Django 对象权限时,如何使用 django-rest 框架添加非模型/查询集返回 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040069/

相关文章:

python - 检测窗口的起始大小是多少?

python脚本总是失败

python - 更改 Python 直方图 bin 中的计数

javascript - Django Rest框架和React前端: How to prevent unauthorized users from viewing private images if they get a hold of the image URL?

django south - unique=True,但是 "give default value for existing rows"?

python - Form.media 没有被注入(inject)到模板中

azure - 如何将 Azure 身份验证添加到我当前也使用 API 的 Web 应用程序?

python - 尽管存在所需的库,但我无法安装 python 包

PHP 无需爬行 Google 即可获取网站的 Google 排名

获取文件系统信息的 Linux API