问题
I am using flask-auth, which provides some helper decorators. I've added all the various methods below, but the question I want to ask is how to catch any issues thrown by the authorized_handler
decorator. It's a general question about decorators, but I thought a real example might help.
If the decorator blows up, how could I catch it?
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'
回答1:
Function definitions are executed. Therefore, assuming the exception raised is specific to that decorator, you can wrap the function definition, including decorators, in a 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
Of course, this will leave oauth_authorized
undefined if the exception is raised. This is probably OK in your case since you probably don't want it to be be routed anyway. But if this isn't what you want, you could add a dummy definition to your except
block.
Or, since decorators are just functions (well, any callable) and the @
notation is merely syntactic sugar for a function call, you can wrap just the authorized_handler
decoration in 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)
This will leave you with the undecorated version of the function if the authorized_handler
decoration fails, but it will not be routed. You could even put the above in its own function and use it as a decorator!
来源:https://stackoverflow.com/questions/17033094/how-do-i-catch-an-error-raised-in-a-decorator