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
Provenance
- Commit
4f81501- Tree
d2c0709- Author
cerickson <basicsafty@gmail.com>- Committer
cerickson <basicsafty@gmail.com>- Parent
668061a
2 files changed+69 added−44 removed
modified:flask/app.py+13 added-20 removed
131 unmodified lines132 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 lines1461 self.url_default_functions.setdefault(None, []).append(f)1462 return f1463 1464 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))1471 1472 def find_handler(handler_map):1473 if not handler_map:1474 return1475+1476 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 handler1482 1479- # 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))1487 1486- # 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 handler1490 1491- try:1492- handler = find_handler(self.error_handler_spec[None][None])1493- except KeyError:1494- handler = None1495-1496- return handler1497-1491 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 linesmodified:tests/test_user_error_handler.py+56 added-24 removed
1 # -*- coding: utf-8 -*-2-from werkzeug.exceptions import Forbidden, InternalServerError, HTTPException, NotFound2+from werkzeug.exceptions import (3+ Forbidden,4+ InternalServerError,5+ HTTPException,6+ NotFound7+ )8 import flask9 10 11 def test_error_handler_no_match():24 unmodified lines36 assert c.get('/custom').data == b'custom'37 assert c.get('/keyerror').data == b'KeyError'38 39 35-def test_default_error_handler():36- app = flask.Flask(__name__)37-38- @app.errorhandler(HTTPException)39- def catchall_errorhandler(e):40- assert isinstance(e, HTTPException)41- assert isinstance(e, NotFound)42- return 'default'43-44- @app.errorhandler(Forbidden)45- def catchall_errorhandler(e):46- assert isinstance(e, Forbidden)47- return 'forbidden'48-49- @app.route('/forbidden')50- def forbidden():51- raise Forbidden()52-53- c = app.test_client()54- assert c.get('/undefined').data == b'default'55- assert c.get('/forbidden').data == b'forbidden'56-57-40 def test_error_handler_subclass():41 app = flask.Flask(__name__)42 43 class ParentException(Exception):98 unmodified lines142 c = app.test_client()143 144 assert c.get('/error').data == b'app-error'145 assert c.get('/bp/error').data == b'bp-error'146+147+148+def test_default_error_handler():149+ bp = flask.Blueprint('bp', __name__)150+151+ @bp.errorhandler(HTTPException)152+ def bp_exception_handler(e):153+ assert isinstance(e, HTTPException)154+ assert isinstance(e, NotFound)155+ return 'bp-default'156+157+ @bp.errorhandler(Forbidden)158+ def bp_exception_handler(e):159+ assert isinstance(e, Forbidden)160+ return 'bp-forbidden'161+162+ @bp.route('/undefined')163+ def bp_registered_test():164+ raise NotFound()165+166+ @bp.route('/forbidden')167+ def bp_forbidden_test():168+ raise Forbidden()169+170+ app = flask.Flask(__name__)171+172+ @app.errorhandler(HTTPException)173+ def catchall_errorhandler(e):174+ assert isinstance(e, HTTPException)175+ assert isinstance(e, NotFound)176+ return 'default'177+178+ @app.errorhandler(Forbidden)179+ def catchall_errorhandler(e):180+ assert isinstance(e, Forbidden)181+ return 'forbidden'182+183+ @app.route('/forbidden')184+ def forbidden():185+ raise Forbidden()186+187+ app.register_blueprint(bp, url_prefix='/bp')188+189+ 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'194+195+