简体   繁体   English

Django 中的自定义权限

[英]Custom permissions in Django

In Django Rest framework, we can verify permissions such as (isAuthenticated, isAdminUser...) but how can we add our custom permissions and decide what django can do with those permissions?在 Django Rest 框架中,我们可以验证诸如 (isAuthenticated, isAdminUser...) 之类的权限,但是我们如何添加自定义权限并确定 django 可以使用哪些权限?

I really want to understand what happens behind (I didn't find a documentation that explaint this):我真的很想了解背后发生了什么(我没有找到解释这一点的文档):

@permission_classes([IsAdminUser])

Thank you谢谢

If you are using VSCode , hover over @permission_classes([IsAdminUser]) , click on Command (on your keyboard).如果您使用VSCode , hover 而不是@permission_classes([IsAdminUser]) ,请单击命令(在您的键盘上)。

在此处输入图像描述

You can see what happens behind the scenes, play and create your custom Django version (not recommended) or you can overwrite the function.您可以查看幕后发生的事情,播放并创建您的自定义 Django 版本(不推荐),或者您可以覆盖 function。

Write your own permissions, like this:编写您自己的权限,如下所示:

def permission_valid_token(func):
    # first arg is the viewset, second is the request
    def wrapper(*args, **kwargs):
        valid_token, user_token = test_token_authorization(args[1].headers)
        if not valid_token:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        return func(*args, **kwargs)
    return wrapper

This a permission that i'm using in app, probably you will have the valid_token part这是我在应用程序中使用的权限,可能您将拥有 valid_token 部分

And them you import in your views你在视图中导入它们

from file_that_you_use.permissions import permission_valid_token

And you use as a decorator而你用作装饰者

class WeatherViewSet(viewsets.ViewSet):
    @permission_valid_token
    def list(self, request):

This is just a viewset for example, you can use generic viewsets or whatever you want.例如,这只是一个视图集,您可以使用通用视图集或任何您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM