2012-11-17 3 views
1

나는 전화를 인증하기 위해 데코레이터를 작성했다. 하나의 인수만으로도 제대로 작동하지만 더 많은 인수를 사용하면 inner() takes exactly 1 argument (2 given)을 트리거합니다. 나는 토네이도를 사용하고 있기 때문에 약간의 콜백 스파게티가 있지만, 이것을하기에 가장 좋은 방법은 무엇인지 모르겠습니다.여러 args (토네이도)와 파이썬 장식 기능

#this works 
class FirstHandler(BaseHandler): 

    @asynchronous 
    @oauth_machine.auth 
    def post(self): 
     print self.user 
     self.finish() 

#this now also does 
class SecondHandler(BaseHandler): 

    @asynchronous 
    @oauth_machine.auth 
    def get(self, args): 
     self.write("ok") 
     self.finish() 

데코레이터 기능 (들)

def auth(fn): 
    def inner(self, *args): 
     res = get_user_by_credentials(self, fn, args, callback=done_auth) 
    return inner 

def get_user_by_credentials(self, fn, callback): 

    def onFetchUserCredentials(result, error): 
     self.user = result 
     callback(self, fn, args) 

    email = self.get_argument("email") 
    password = self.get_argument("password") 
    settings.DB.users.find_one({'email': email, 'password': password }, callback=onFetchUserCredentials) 

def done_auth(result, fn, args): 
    return fn(result, args) 

편집 : 버전을 작업하는

업데이트 코드입니다.

감사합니다.

+0

'def inner (* args) :'와'print args'를'def inner (self) :'로 변경하면 전달되는 인자를 확인할 수 있습니다. – Blender

+0

함수에서 전달 된 두 개의 인수를 얻습니다. 'self '를'args [0]'으로 변경함으로써,'get()은 정확히 2 개의 인수 (주어진 1 개)'를 얻습니다. 두 번째 논의를 어디에서 지나치지 않습니까? –

+0

'get '을 호출하는 코드가 없습니다. 관련 코드를 모두 게시했다고 가정하면, 이는 토네이도 내부에서 부적절하게'get '이라고 부르는 것입니다. 이는 아마도 토네이도에서 부적절하게 호출하는 것을 의미합니다. 우리가 볼 수 있도록 스택 추적을 게시하십시오. – abarnert

답변

1

처음에는 문제가 아주 간단하다고 생각했지만 원래 오류 메시지와 모순되는 추적 코드를 게시했습니다. 그러나, 나는 문제가 여전히 매우 간단하다고 생각합니다. 추적 코드 오류가 올바른 것으로 가정합니다.

@decorator 
def foo(x): 
    return x + 1 

이를 위해 단순히 문법적인가 :이 것을 기억 당신이 get@oauth_machine.auth를 사용할 때,이 fninner에 폐쇄를 통해 전달 된 것

def foo(x): 
    return x + 1 
foo = oauth_machine.auth(foo) 

합니다.

def auth(fn): 
    def inner(self): 
     res = get_user_by_credentials(self, fn, callback=done_auth) 
    return inner 

그런 다음 다시 callbackfn를 전달하는 다른 폐쇄, 생산 fn로 다시 get_user_by_credentials에 전달합니다.

def get_user_by_credentials(self, fn, callback): 

    def onFetchUserCredentials(result, error): 
     self.user = result 
     callback(self, fn) 

callback가 다시 innerdone_auth로 정의 하였다 그래서 menas 그 fn (즉, 원래 get)이 result 거기에 통과 한 후 호출됩니다

def done_auth(result, fn): 
    return fn(result) 

그러나 fn (예 : get를) 두 개의 인수를 취합니다. 하나만 전달하면 오류가 발생합니다.

+1

헤이, 해부 덕분에! 그 동안 (코드를 업데이트 한) 코드가 제대로 작동 했으므로 getter()는 데코레이터를 거친 후 해고 당하고 done_auth()는 param이 누락되었습니다. 나는 그것을 종결에서 종결해야만했다. 건배! –