Skip to content
Myr

Added support for generic HTTPException handlers on app and blueprints

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Error handlers are now returned in order of blueprint:code, app:code, blueprint:HTTPException, app:HTTPException, None Corresponding tests also added. Ref issue #941, pr #1383, #2082, #2144

authored by cerickson · committed by cerickson · parent 668061a · Browse files · 2 files+69 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+69 added−44 removed

  • tests:+56 added−24 removed
  • other:+13 added−20 removed

2 files+69 added−44 removed

modified:flask/app.py+13 added-20 removed
131 unmodified lines
132 of the `static_folder` folder.133 :param static_folder: the folder with static files that should be served134 at `static_url_path`. Defaults to the ``'static'``135 folder in the root path of the application.136 folder in the root path of the application. Defaults137 to None.138 :param host_matching: sets the app's ``url_map.host_matching`` to the given139 given value. Defaults to False.140 :param static_host: the host to use when adding the static route. Defaults141 to None. Required when using ``host_matching=True``
1319 unmodified lines
1461 self.url_default_functions.setdefault(None, []).append(f)1462 return f14631464 def _find_error_handler(self, e):1463 """Finds a registered error handler for the request’s blueprint.1464 Otherwise falls back to the app, returns None if not a suitable1465 handler is found.1465 """Find a registered error handler for a request in this order:1466 blueprint handler for a specific code, app handler for a specific code,1467 blueprint generic HTTPException handler, app generic HTTPException handler,1468 and returns None if a suitable handler is not found.1469 """1470 exc_class, code = self._get_exc_class_and_code(type(e))14711472 def find_handler(handler_map):1473 if not handler_map:1474 return14751476 for cls in exc_class.__mro__:1477 handler = handler_map.get(cls)1478 if handler is not None:1479 # cache for next time exc_class is raised1480 handler_map[exc_class] = handler1481 return handler14821479 # try blueprint handlers1480 handler = find_handler(self.error_handler_spec1481 .get(request.blueprint, {})1482 .get(code))1483 if handler is not None:1484 return handler1483 # check for any in blueprint or app1484 for name, c in ((request.blueprint, code), (None, code),1485 (request.blueprint, None), (None, None)):1486 handler = find_handler(self.error_handler_spec.get(name, {}).get(c))14871486 # fall back to app handlers1487 handler = find_handler(self.error_handler_spec[None].get(code))1488 if handler is not None:1489 return handler1488 if handler:1489 return handler14901491 try:1492 handler = find_handler(self.error_handler_spec[None][None])1493 except KeyError:1494 handler = None14951496 return handler14971491 def handle_http_exception(self, e):1492 """Handles an HTTP exception. By default this will invoke the1493 registered error handlers and fall back to returning the1494 exception as response.
588 unmodified lines
modified:tests/test_user_error_handler.py+56 added-24 removed
1# -*- coding: utf-8 -*-2from werkzeug.exceptions import Forbidden, InternalServerError, HTTPException, NotFound2from werkzeug.exceptions import (3 Forbidden,4 InternalServerError,5 HTTPException,6 NotFound7 )8import flask91011def test_error_handler_no_match():
24 unmodified lines
36 assert c.get('/custom').data == b'custom'37 assert c.get('/keyerror').data == b'KeyError'383935def test_default_error_handler():36 app = flask.Flask(__name__)3738 @app.errorhandler(HTTPException)39 def catchall_errorhandler(e):40 assert isinstance(e, HTTPException)41 assert isinstance(e, NotFound)42 return 'default'4344 @app.errorhandler(Forbidden)45 def catchall_errorhandler(e):46 assert isinstance(e, Forbidden)47 return 'forbidden'4849 @app.route('/forbidden')50 def forbidden():51 raise Forbidden()5253 c = app.test_client()54 assert c.get('/undefined').data == b'default'55 assert c.get('/forbidden').data == b'forbidden'565740def test_error_handler_subclass():41 app = flask.Flask(__name__)4243 class ParentException(Exception):
98 unmodified lines
142 c = app.test_client()143144 assert c.get('/error').data == b'app-error'145 assert c.get('/bp/error').data == b'bp-error'146147148def test_default_error_handler():149 bp = flask.Blueprint('bp', __name__)150151 @bp.errorhandler(HTTPException)152 def bp_exception_handler(e):153 assert isinstance(e, HTTPException)154 assert isinstance(e, NotFound)155 return 'bp-default'156157 @bp.errorhandler(Forbidden)158 def bp_exception_handler(e):159 assert isinstance(e, Forbidden)160 return 'bp-forbidden'161162 @bp.route('/undefined')163 def bp_registered_test():164 raise NotFound()165166 @bp.route('/forbidden')167 def bp_forbidden_test():168 raise Forbidden()169170 app = flask.Flask(__name__)171172 @app.errorhandler(HTTPException)173 def catchall_errorhandler(e):174 assert isinstance(e, HTTPException)175 assert isinstance(e, NotFound)176 return 'default'177178 @app.errorhandler(Forbidden)179 def catchall_errorhandler(e):180 assert isinstance(e, Forbidden)181 return 'forbidden'182183 @app.route('/forbidden')184 def forbidden():185 raise Forbidden()186187 app.register_blueprint(bp, url_prefix='/bp')188189 c = app.test_client()190 assert c.get('/bp/undefined').data == b'bp-default'191 assert c.get('/bp/forbidden').data == b'bp-forbidden'192 assert c.get('/undefined').data == b'default'193 assert c.get('/forbidden').data == b'forbidden'194195