2013-06-10 3 views
0

필자는 도우미 데코레이터를 제공하는 flask-auth를 사용하고 있습니다. 아래에 다양한 방법을 모두 추가했지만, 궁금한 점은 authorized_handler 데코레이터에서 발생하는 문제를 잡는 방법입니다. 데코레이터에 대한 일반적인 질문이지만 실제 예제가 도움이 될 것으로 생각했습니다.데코레이터에서 발생한 오류를 어떻게 catch합니까?

데코레이터가 터지면 어떻게 잡을 수 있습니까?

import os 
import flask 
import flask_oauth 

CONSUMER_KEY = os.environ['CONSUMER_KEY'] 
CONSUMER_SECRET = os.environ['CONSUMER_SECRET'] 

oauth = flask_oauth.OAuth() 
twitter = oauth.remote_app(
    'twitter', 
    base_url='https://api.twitter.com/1/', 
    request_token_url='https://api.twitter.com/oauth/request_token', 
    access_token_url='https://api.twitter.com/oauth/access_token', 
    authorize_url='https://api.twitter.com/oauth/authenticate', 
    consumer_key=CONSUMER_KEY, 
    consumer_secret=CONSUMER_SECRET 
) 

app = flask.Flask(__name__) 

@app.route('/login') 
def login(): 
    return twitter.authorize(
     callback=url_for(
      'oauth_authorized', 
      next=request.args.get('next') or request.referrer or None) 
    ) 

@app.route('/oauth-authorized') 
# what happens if this raises an error? 
@twitter.authorized_handler 
def oauth_authorized(resp): 
    print 'foo-bar' 

답변

2

함수 정의가 실행됩니다. 따라서, 제기 된 예외를 가정하는 것은 그 장식에 고유 한, 당신은 try/except에, 장식을 포함한 함수 정의를 포장 할 수 있습니다 : 예외가 발생하면 물론

try: 
    @app.route('/oauth-authorized') 
    @twitter.authorized_handler 
    def oauth_authorized(resp): 
     print 'foo-bar' 
except WhateverError as e: 
    print "twitter.authorized_handler raised an error", e 

, 이것은 oauth_authorized이 정의되지 않은 떠날 것이다. 이것은 아마도 어쨌든 라우팅 될 수 있기를 원하지 않기 때문에 아마도 귀하의 경우에는 괜찮습니다. 그러나 이것이 원하는 것이 아니면, except 블록에 더미 정의를 추가 할 수 있습니다.

장식 그냥 기능입니다 (물론, 모든 호출)와 @ 표기는 함수 호출을 위해 단지 문법 설탕 때문에 또는, 당신은 단지 authorized_handler 장식 try/except에 포장 할 수 있습니다

def oauth_authorized(resp): 
    print 'foo-bar' 
try: # apply decorator 
    oauth_authorized = twitter.authorized_handler(oauth_authorized) 
except Exception as e: 
    print "twitter.authorized_handler raised an error", e 
else: # no error decorating with authorized_handler, apply app.route 
    oauth_authorized = app.route('/oauth-authorized')(oauth_authorized) 

이 떠나 authorized_handler 데코 레이팅이 실패해도 꾸미지 않은 버전의 기능을 사용하면 라우팅되지만 라우팅되지는 않습니다. 위의 것을 자신의 함수에 넣고 데코레이터로 사용할 수도 있습니다!

+0

감사합니다. 위대하고 포괄적 인 대답입니다. –

관련 문제