Added blueprint specific error handling
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent aaa24fc · Browse files · 4 files·+182 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+182 added−12 removed
- tests:+60 added−0 removed
- other:+122 added−12 removed
Provenance
- Commit
f5ec995- Tree
cc334ce- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
aaa24fc
4 files changed+182 added−12 removed
modified:flask/app.py+94 added-11 removed
232 unmodified lines233 #: the values are the function objects themselves.234 #: To register a view function, use the :meth:`route` decorator.235 self.view_functions = {}236 237- #: A dictionary of all registered error handlers. The key is238- #: be the error code as integer, the value the function that239- #: should handle that error.237+ # support for the now deprecated `error_handlers` attribute. The238+ # :attr:`error_handler_spec` shall be used now.239+ self._error_handlers = {}240+241+ #: A dictionary of all registered error handlers. The key is `None`242+ #: for error handlers active on the application, otherwise the key is243+ #: the name of the blueprint. Each key points to another dictionary244+ #: where they key is the status code of the http exception. The245+ #: special key `None` points to a list of tuples where the first item246+ #: is the class for the instance check and the second the error handler247+ #: function.248+ #:249 #: To register a error handler, use the :meth:`errorhandler`250 #: decorator.242- self.error_handlers = {}251+ self.error_handler_spec = {None: self._error_handlers}252 253 #: A dictionary with lists of functions that should be called at the254 #: beginning of the request. The key of the dictionary is the name of255 #: the blueprint this function is active for, `None` for all requests.103 unmodified lines359 self.add_url_rule(self.static_url_path + '/<path:filename>',360 endpoint='static',361 view_func=self.send_static_file)362 363+ def _get_error_handlers(self):364+ from warnings import warn365+ warn(DeprecationWarning('error_handlers is deprecated, use the '366+ 'new error_handler_spec attribute instead.'), stacklevel=1)367+ return self._error_handlers368+ def _set_error_handlers(self, value):369+ self._error_handlers = value370+ self.error_handler_spec[None] = value371+ error_handlers = property(_get_error_handlers, _set_error_handlers)372+ del _get_error_handlers, _set_error_handlers373+374 @property375 def propagate_exceptions(self):376 """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration377 value in case it's set, otherwise a sensible default is returned.402 unmodified lines780 self.view_functions[endpoint] = f781 return f782 return decorator783 764- def errorhandler(self, code):784+ def errorhandler(self, code_or_exception):785 """A decorator that is used to register a function give a given786 error code. Example::787 788 @app.errorhandler(404)789 def page_not_found(error):790 return 'This page does not exist', 404791 792+ You can also register handlers for arbitrary exceptions::793+794+ @app.errorhandler(DatabaseError)795+ def special_exception_handler(error):796+ return 'Database connection failed', 500797+798 You can also register a function as error handler without using799 the :meth:`errorhandler` decorator. The following example is800 equivalent to the one above::801 802 def page_not_found(error):803 return 'This page does not exist', 404778- app.error_handlers[404] = page_not_found804+ app.error_handler_spec[None][404] = page_not_found805 806+ Setting error handlers via assignments to :attr:`error_handler_spec`807+ however is discouraged as it requires fidling with nested dictionaries808+ and the special case for arbitrary exception types.809+810+ The first `None` refers to the active blueprint. If the error811+ handler should be application wide `None` shall be used.812+813+ .. versionadded:: 0.7814+ One can now additionally also register custom exception types815+ that do not necessarily have to be a subclass of the816+ :class:~`werkzeug.exceptions.HTTPException` class.817+818 :param code: the code as integer for the handler819 """820 def decorator(f):783- self.error_handlers[code] = f821+ self._register_error_handler(None, code_or_exception, f)822 return f823 return decorator824 825+ def _register_error_handler(self, key, code_or_exception, f):826+ if isinstance(code_or_exception, HTTPException):827+ code_or_exception = code_or_exception.code828+ if isinstance(code_or_exception, (int, long)):829+ assert code_or_exception != 500 or key is None, \830+ 'It is currently not possible to register a 500 internal ' \831+ 'server error on a per-blueprint level.'832+ self.error_handler_spec.setdefault(key, {})[code_or_exception] = f833+ else:834+ self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \835+ .append((code_or_exception, f))836+837 def template_filter(self, name=None):838 """A decorator that is used to register custom template filter.839 You can specify a name for the filter, otherwise the function840 name will be used. Example::79 unmodified lines920 exception as response.921 922 .. versionadded: 0.3923 """924+ handlers = self.error_handler_spec.get(request.blueprint)925+ if handlers and e.code in handlers:926+ handler = handlers[e.code]927+ else:874- handler = self.error_handlers.get(e.code)928+ handler = self.error_handler_spec[None].get(e.code)929 if handler is None:930 return e931 return handler(e)932 933+ def handle_user_exception(self, e):934+ """This method is called whenever an exception occurs that should be935+ handled. A special case are936+ :class:`~werkzeug.exception.HTTPException`\s which are forwarded by937+ this function to the :meth:`handle_http_exception` method. This938+ function will either return a response value or reraise the939+ exception with the same traceback.940+941+ .. versionadded:: 0.7942+ """943+ # ensure not to trash sys.exc_info() at that point in case someone944+ # wants the traceback preserved in handle_http_exception.945+ if isinstance(e, HTTPException):946+ return self.handle_http_exception(e)947+948+ exc_type, exc_value, tb = sys.exc_info()949+ assert exc_value is e950+951+ blueprint_handlers = ()952+ handlers = self.error_handler_spec.get(request.blueprint)953+ if handlers is not None:954+ blueprint_handlers = handlers.get(None, ())955+ app_handlers = self.error_handler_spec[None].get(None, ())956+ for typecheck, handler in chain(blueprint_handlers, app_handlers):957+ if isinstance(e, typecheck):958+ return handler(e)959+960+ raise exc_type, exc_value, tb961+962 def handle_exception(self, e):963 """Default exception handling that kicks in when an exception964 occours that is not caught. In debug mode the exception will965 be re-raised immediately, otherwise it is logged and the handler4 unmodified lines970 """971 exc_type, exc_value, tb = sys.exc_info()972 973 got_request_exception.send(self, exception=e)891- handler = self.error_handlers.get(500)974+ handler = self.error_handler_spec[None].get(500)975 976 if self.propagate_exceptions:977 # if we want to repropagate the exception, we can attempt to978 # raise it with the whole traceback in case we can do that45 unmodified lines1024 request_started.send(self)1025 rv = self.preprocess_request()1026 if rv is None:1027 rv = self.dispatch_request()945- except HTTPException, e:946- rv = self.handle_http_exception(e)1028+ except Exception, e:1029+ rv = self.handle_user_exception(e)1030 response = self.make_response(rv)1031 response = self.process_response(response)1032 request_finished.send(self, response=response)1033 return response240 unmodified linesmodified:flask/blueprints.py+23 added-1 removed
60 unmodified lines61 self.subdomain = subdomain62 self.static_folder = static_folder63 self.static_url_path = static_url_path64 self.deferred_functions = []65+ self.view_functions = {}66 67 def _record(self, func):68 self.deferred_functions.append(func)69 40 unmodified lines110 111 def endpoint(self, endpoint):112 """Like :meth:`Flask.endpoint` but for a module. This does not113 prefix the endpoint with the module name, this has to be done113- explicitly by the user of this method.114+ explicitly by the user of this method. If the endpoint is prefixed115+ with a `.` it will be registered to the current blueprint, otherwise116+ it's an application independent endpoint.117 """118 def decorator(f):119 def register_endpoint(state):120 state.app.view_functions[endpoint] = f90 unmodified lines211 """212 self._record_once(lambda s: s.app.url_default_functions213 .setdefault(None, []).append(f))214 return f215+216+ def errorhandler(self, code_or_exception):217+ """Registers an error handler that becomes active for this blueprint218+ only. Please be aware that routing does not happen local to a219+ blueprint so an error handler for 404 usually is not handled by220+ a blueprint unless it is caused inside a view function. Another221+ special case is the 500 internal server error which is always looked222+ up from the application.223+224+ Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator225+ of the :class:`~flask.Flask` object.226+227+ .. versionadded:: 0.7228+ """229+ def decorator(f):230+ self._record_once(lambda s: s.app._register_error_handler(231+ self.name, code_or_exception, f))232+ return f233+ return decoratormodified:tests/flask_tests.py+60 added
529 unmodified lines530 rv = c.get('/error')531 assert rv.status_code == 500532 assert 'internal server error' == rv.data533 534+ def test_user_error_handling(self):535+ class MyException(Exception):536+ pass537+538+ app = flask.Flask(__name__)539+ @app.errorhandler(MyException)540+ def handle_my_exception(e):541+ assert isinstance(e, MyException)542+ return '42'543+ @app.route('/')544+ def index():545+ raise MyException()546+547+ c = app.test_client()548+ assert c.get('/').data == '42'549+550 def test_teardown_on_pop(self):551 buffer = []552 app = flask.Flask(__name__)553 @app.teardown_request675 unmodified lines1229 assert c.get('/foo/').data == 'index'1230 assert c.get('/foo/bar').data == 'bar'1231 1232 1233+class BlueprintTestCase(unittest.TestCase):1234+1235+ def test_blueprint_specific_error_handling(self):1236+ frontend = flask.Blueprint('frontend', __name__)1237+ backend = flask.Blueprint('backend', __name__)1238+ sideend = flask.Blueprint('sideend', __name__)1239+1240+ @frontend.errorhandler(403)1241+ def frontend_forbidden(e):1242+ return 'frontend says no', 4031243+1244+ @frontend.route('/frontend-no')1245+ def frontend_no():1246+ flask.abort(403)1247+1248+ @backend.errorhandler(403)1249+ def backend_forbidden(e):1250+ return 'backend says no', 4031251+1252+ @backend.route('/backend-no')1253+ def backend_no():1254+ flask.abort(403)1255+1256+ @sideend.route('/what-is-a-sideend')1257+ def sideend_no():1258+ flask.abort(403)1259+1260+ app = flask.Flask(__name__)1261+ app.register_blueprint(frontend)1262+ app.register_blueprint(backend)1263+ app.register_blueprint(sideend)1264+1265+ @app.errorhandler(403)1266+ def app_forbidden(e):1267+ return 'application itself says no', 4031268+1269+ c = app.test_client()1270+1271+ assert c.get('/frontend-no').data == 'frontend says no'1272+ assert c.get('/backend-no').data == 'backend says no'1273+ assert c.get('/what-is-a-sideend').data == 'application itself says no'1274+1275+1276 class SendfileTestCase(unittest.TestCase):1277 1278 def test_send_file_regular(self):1279 app = flask.Flask(__name__)409 unmodified lines1689 suite.addTest(unittest.makeSuite(ContextTestCase))1690 suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1691 suite.addTest(unittest.makeSuite(TemplatingTestCase))1692 suite.addTest(unittest.makeSuite(ModuleTestCase))1693+ suite.addTest(unittest.makeSuite(BlueprintTestCase))1694 suite.addTest(unittest.makeSuite(SendfileTestCase))1695 suite.addTest(unittest.makeSuite(LoggingTestCase))1696 suite.addTest(unittest.makeSuite(ConfigTestCase))1697 suite.addTest(unittest.makeSuite(SubdomainTestCase))12 unmodified linesmodified:CHANGES+5 added
49 unmodified lines50 mimetype parameter.51 - Don't modify the session on :func:`flask.get_flashed_messages` if there52 are no messages in the session.53 - `before_request` handlers are now able to abort requests with errors.54+- it is not possible to define user exception handlers. That way you can55+ provide custom error messages from a central hub for certain errors that56+ might occur during request processing (for instance database connection57+ errors, timeouts from remote resources etc.).58+- Blueprints can provide blueprint specific error handlers.59 60 Version 0.6.161 -------------62 159 unmodified lines