繁体   English   中英

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

[英]Django decorator getting a WSGIRequest and not the expected function argument

我正在为Django视图创建装饰器,该装饰器将检查非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()一起调用的对象。 有人知道我的方法去了哪里以及如何找回它吗? 我没有办法链接到下一个装饰器或实际情况。

哦,CentOS和Django 1.1.1上的Python 2.4.3。

我想要我的功能! ;)

谢谢。

j

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

转换为:

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

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

因此,问题与装饰器的调用方式有关。 您会得到以下不同的行为:

@my_decorator

@my_decorator(someparam='someval')

在第一种情况下,您将可调用对象直接传递给my_decorator。 在第二种情况下,您不需要,但是从my_decorator返回的可调用项将可以。

我敢肯定有一些深奥的原因,但这是IMNSO的me脚。 这使得使用默认参数创建装饰器的过程比应该的要清晰得多。

暂无
暂无

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

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