removed ExceptionHandlerDict
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Phil Schaf · committed by Phil Schaf · parent 0e44cca · Browse files · 2 files·+156 added−70 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+156 added−70 removed
- tests:+113 added−0 removed
- other:+43 added−70 removed
Provenance
- Commit
fd8e6b2- Tree
69e5c36- Author
Phil Schaf <flying-sheep@web.de>- Committer
Phil Schaf <flying-sheep@web.de>- Parent
0e44cca
2 files changed+156 added−70 removed
modified:flask/app.py+43 added-70 removed
63 unmodified lines64 return f(self, *args, **kwargs)65 return update_wrapper(wrapper_func, f)66 67 68-class ExceptionHandlerDict(Mapping):69- """A dict storing exception handlers or falling back to the default ones70- 71- Designed to be app.error_handler_spec[blueprint_or_none]72- And hold a Exception → handler function mapping.73- Converts error codes to default HTTPException subclasses.74- 75- Returns None if no handler is defined for blueprint or app76- """77- def __init__(self, app, blueprint):78- super(ExceptionHandlerDict, self).__init__()79- self.app = app80- self.data = {}81- if blueprint: # fall back to app mapping82- self.fallback = app.error_handler_spec[None]83- else:84- self.fallback = {}85- 86- @staticmethod87- def get_class(exc_class_or_code):88- if isinstance(exc_class_or_code, integer_types):89- # ensure that we register only exceptions as keys90- exc_class = default_exceptions[exc_class_or_code]91- else:92- assert issubclass(exc_class_or_code, Exception)93- exc_class = exc_class_or_code94- return exc_class95- 96- def __contains__(self, e_or_c):97- clazz = self.get_class(e_or_c)98- return clazz in self.data or clazz in self.fallback99- 100- def __getitem__(self, e_or_c):101- clazz = self.get_class(e_or_c)102- item = self.data.get(clazz)103- if item is not None:104- return item105- elif len(self.fallback):106- return self.fallback[clazz]107- else:108- raise KeyError(e_or_c)109- 110- def __setitem__(self, e_or_c, handler):111- assert callable(handler)112- self.data[self.get_class(e_or_c)] = handler113- 114- def __iter__(self):115- return iterkeys(self.data)116- 117- def __len__(self):118- return len(self.data)119- 120- def find_handler(self, ex_instance):121- assert isinstance(ex_instance, Exception)122- 123- for superclass in type(ex_instance).mro():124- if superclass is BaseException:125- return None126- handler = self.get(superclass)127- if handler is not None:128- return handler129- return None130-131-68 class Flask(_PackageBoundObject):69 """The flask object implements a WSGI application and acts as the central70 object. It is passed the name of the module or package of the71 application. Once it is created it will act as a central registry for292 unmodified lines364 self.view_functions = {}365 366 # support for the now deprecated `error_handlers` attribute. The367 # :attr:`error_handler_spec` shall be used now.432- self._error_handlers = ExceptionHandlerDict(self, None)368+ self._error_handlers = {}369 370 #: A dictionary of all registered error handlers. The key is ``None``371 #: for error handlers active on the application, otherwise the key is372 #: the name of the blueprint. Each key points to another dictionary704 unmodified lines1077 self.view_functions[endpoint] = f1078 return f1079 return decorator1080 1081+ @staticmethod1082+ def _ensure_exc_class(exc_class_or_code):1083+ """ensure that we register only exceptions as handler keys"""1084+ if isinstance(exc_class_or_code, integer_types):1085+ exc_class = default_exceptions[exc_class_or_code]1086+ elif isinstance(exc_class_or_code, type):1087+ exc_class = exc_class_or_code1088+ else:1089+ exc_class = type(exc_class_or_code)1090+ 1091+ assert issubclass(exc_class, Exception)1092+ 1093+ if issubclass(exc_class, HTTPException):1094+ return exc_class, exc_class.code1095+ else:1096+ return exc_class, None1097+ 1098 @setupmethod1099 def errorhandler(self, code_or_exception):1100 """A decorator that is used to register a function give a given1101 error code. Example::61 unmodified lines1163 'Tried to register a handler for an exception instance {0!r}. '1164 'Handlers can only be registered for exception classes or HTTP error codes.'1165 .format(code_or_exception))1166 1214- handlers = self.error_handler_spec.setdefault(key, ExceptionHandlerDict(self, key))1167+ exc_class, code = self._ensure_exc_class(code_or_exception)1168 1216- handlers[code_or_exception] = f1169+ handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1170+ handlers[exc_class] = f1171 1172 @setupmethod1173 def template_filter(self, name=None):1174 """A decorator that is used to register custom template filter.234 unmodified lines1409 return f1410 1411 def _find_error_handler(self, e):1412 """Finds a registered error handler for the request’s blueprint.1459- If nether blueprint nor App has a suitable handler registered, returns None1413+ If neither blueprint nor App has a suitable handler registered, returns None1414 """1461- handlers = self.error_handler_spec.get(request.blueprint, self.error_handler_spec[None])1462- return handlers.find_handler(e)1415+ exc_class, code = self._ensure_exc_class(e)1416+ 1417+ def find_superclass(d):1418+ if not d:1419+ return None1420+ for superclass in exc_class.mro():1421+ if superclass is BaseException:1422+ return None1423+ handler = d.get(superclass)1424+ if handler is not None:1425+ return handler1426+ return None1427+ 1428+ # try blueprint handlers1429+ handler = find_superclass(self.error_handler_spec.get(request.blueprint, {}).get(code))1430+ 1431+ if handler is not None:1432+ return handler1433+ 1434+ # fall back to app handlers1435+ return find_superclass(self.error_handler_spec[None].get(code))1436 1437 def handle_http_exception(self, e):1438 """Handles an HTTP exception. By default this will invoke the1439 registered error handlers and fall back to returning the527 unmodified linesadded:tests/test_user_error_handler.py+113 added
1+# -*- coding: utf-8 -*-2+from werkzeug.exceptions import Forbidden, InternalServerError3+import flask4+5+6+def test_error_handler_subclass():7+ app = flask.Flask(__name__)8+9+ class ParentException(Exception):10+ pass11+12+ class ChildExceptionUnregistered(ParentException):13+ pass14+15+ class ChildExceptionRegistered(ParentException):16+ pass17+18+ @app.errorhandler(ParentException)19+ def parent_exception_handler(e):20+ assert isinstance(e, ParentException)21+ return 'parent'22+23+ @app.errorhandler(ChildExceptionRegistered)24+ def child_exception_handler(e):25+ assert isinstance(e, ChildExceptionRegistered)26+ return 'child-registered'27+28+ @app.route('/parent')29+ def parent_test():30+ raise ParentException()31+32+ @app.route('/child-unregistered')33+ def unregistered_test():34+ raise ChildExceptionUnregistered()35+36+ @app.route('/child-registered')37+ def registered_test():38+ raise ChildExceptionRegistered()39+40+41+ c = app.test_client()42+43+ assert c.get('/parent').data == b'parent'44+ assert c.get('/child-unregistered').data == b'parent'45+ assert c.get('/child-registered').data == b'child-registered'46+47+48+def test_error_handler_http_subclass():49+ app = flask.Flask(__name__)50+51+ class ForbiddenSubclassRegistered(Forbidden):52+ pass53+54+ class ForbiddenSubclassUnregistered(Forbidden):55+ pass56+57+ @app.errorhandler(403)58+ def code_exception_handler(e):59+ assert isinstance(e, Forbidden)60+ return 'forbidden'61+62+ @app.errorhandler(ForbiddenSubclassRegistered)63+ def subclass_exception_handler(e):64+ assert isinstance(e, ForbiddenSubclassRegistered)65+ return 'forbidden-registered'66+67+ @app.route('/forbidden')68+ def forbidden_test():69+ raise Forbidden()70+71+ @app.route('/forbidden-registered')72+ def registered_test():73+ raise ForbiddenSubclassRegistered()74+75+ @app.route('/forbidden-unregistered')76+ def unregistered_test():77+ raise ForbiddenSubclassUnregistered()78+79+80+ c = app.test_client()81+82+ assert c.get('/forbidden').data == b'forbidden'83+ assert c.get('/forbidden-unregistered').data == b'forbidden'84+ assert c.get('/forbidden-registered').data == b'forbidden-registered'85+86+87+def test_error_handler_blueprint():88+ bp = flask.Blueprint('bp', __name__)89+ 90+ @bp.errorhandler(500)91+ def bp_exception_handler(e):92+ return 'bp-error'93+ 94+ @bp.route('/error')95+ def bp_test():96+ raise InternalServerError()97+ 98+ app = flask.Flask(__name__)99+ 100+ @app.errorhandler(500)101+ def app_exception_handler(e):102+ return 'app-error'103+ 104+ @app.route('/error')105+ def app_test():106+ raise InternalServerError()107+ 108+ app.register_blueprint(bp, url_prefix='/bp')109+ 110+ c = app.test_client()111+ 112+ assert c.get('/error').data == b'app-error'113+ assert c.get('/bp/error').data == b'bp-error'