在Django上使用装饰器会阻止请求

时间:2018-08-13 08:35:48

标签: python django django-rest-framework python-decorators

我正在尝试创建自己的装饰器,以验证与Django的REST调用(使用Django Rest Framework)。

装饰器看起来像这样:

def allowed_states(allowed=[]):
    def decorator(func):
        def wrapper(self, request, *args, **kwargs):
            print(func)
            result = func(self, request, *args, **kwargs)
            return result
        return wrapper
    return decorator

请求API看起来像这样:

@swagger_auto_schema(
    operation_id="my_api",
    responses={
        status.HTTP_204_NO_CONTENT: "",
    }
)
@action(detail=True, methods=["DELETE"])
@allowed_states(allowed=["state1", "state2"])
def my_api(self, request, *args, **kwargs):
    # do some stuff here

移除我的@allowed_states装饰器后,该调用将正常运行。当我重新添加它时,我从Django框架收到404错误,说它找不到要为此调用执行的网址格式。

我尝试从self(也从wrapper调用)中删除func。 我也尝试更改函数调用上方的装饰器顺序。 两者都不起作用。

堆栈跟踪说明不多,只是django找不到url模式:

 Using the URLconf defined in 
                <code>my_project.urls</code>,
      Django tried these URL patterns, in this order:

(然后是URL模式在my_project.urls中出现的顺序)

1 个答案:

答案 0 :(得分:0)

我在functools.wraps的注释中提出了建议,并解决了问题:

from functools import wraps

def allowed_states(allowed=[]):
    def decorator(func):
        @wraps(func)
        def wrapper(self, request, *args, **kwargs):
            print(func)
            result = func(self, request, *args, **kwargs)
            return result
        return wrapper
    return decorator
相关问题