python - Django 装饰器获取 WSGIRequest 而不是预期的函数参数

标签 python django decorator

我正在为 Django View 创建一个装饰器,它将检查非 Django 管理的数据库中的权限。这是装饰器:

def check_ownership(failure_redirect_url='/', *args, **kwargs):
    def _check_ownership(view):
        def _wrapper(request, csi=None):
            try:
                opb_id=request.user.get_profile().opb_id
                if opb_id and csi and model.is_users_server(opb_id, csi):
                    return view(*args, **kwargs)
            except Exception, e:
                logger.debug("Exception checking ownership: %s", str(e))
            return HttpResponseRedirect(failure_redirect_url)
        _wrapper.__dict__=view.__dict__
        _wrapper.__doc__=view.__doc__
        return _wrapper
    return _check_ownership

这就是它的使用方式:

@check_ownership
def my_view(request, csi=None):
    """Process my request"""

正在调用 check_ownership() 并返回 _check_ownership()。当调用 _check_ownership() 时,它是通过 WSGIRequest 对象调用的,这正是我期望调用 _wrapper() 的对象。有人知道我的方法去了哪里以及如何找回它吗?我没有办法链接到下一个装饰器或实际 View 。

哦,CentOS 上的 Python 2.4.3 和 Django 1.1.1。

我想要恢复我的功能! ;)

谢谢。

tj

最佳答案

@check_ownership
def my_view(request, csi=None):
    ...

翻译成:

def my_view(request, csi=None):
    ...
my_view = check_ownership(my_view)

but check_ownership 不接受函数,但 _check_ownership 接受。这可能就是您的问题所在。

关于python - Django 装饰器获取 WSGIRequest 而不是预期的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2291616/

相关文章:

python - 具有动态选项的 Django Rest Framework MultipleChoiceField

javascript - 装饰器功能不起作用(意外标记)

java - 验证 Java 中装饰器模式的实现

python - Pytest/Allure - 如何生成测试用例描述?

python - 如何增加 Sentry 中捕获的 Python 参数的最大长度?

python - Django 向数据库表中的所有用户发送电子邮件

Java EE 7 - @Decorator、@Stateless 和@PersistenceContext = nullpointerException

python - 使用 Python 3 打印不带括号的不同错误消息

python - 如何在不使用 json 库或没有任何其他库的情况下读取 json 文件到字典或列表中?

python - 机器人框架骑行 : text in Edit panel is not markable