2010-02-18 69 views
1

我正在为Django视图创建装饰器,它将检查非Django托管数据库中的权限。这里是装饰:Django装饰获取WSGIRequest而不是预期的函数参数

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。

我希望我的功能回来! ;)

谢谢。

TJ

回答

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

翻译成:

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

check_ownership不接受功能,但_check_ownership一样。这可能是你的问题所在。

0

所以这个问题与如何调用装饰器有关。你得到不同的行为与这些:

@my_decorator 

@my_decorator(someparam='someval') 

在第一种情况下,你可调用直接传递给my_decorator。在第二种情况下,您不会,但是您从my_decorator返回的可调用函数将会。

我敢肯定,这有一些深奥的原因,但它是,IMNSO,跛脚。它使得使用默认参数创建装饰器的能力远不如他们应该那样清晰。

相关问题