2010-02-18 2 views
1

장고가 관리하지 않는 데이터베이스에서 사용 권한을 확인할 장고 뷰의 데코레이터를 만들고 있습니다. 여기에 장식입니다 :예상되는 함수 인수가 아닌 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()이 호출되면 _wrapper()가 호출 될 것으로 기대했던 WSGIRequest 객체로 호출됩니다. 아무도 내 방법이 어디로 갔는지 어떻게 알 수 있습니까? 나는 다음 데코레이터 또는 실제보기에 사물이서는 방식으로 연결할 수있는 방법이 없습니다.

아, 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, 절름발이입니다. 그것이해야하는 것보다 훨씬 덜 명확한 디폴트 인자를 가진 데코레이터를 생성합니다.

관련 문제