Skip to content
Myr

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

2 files+156 added−70 removed

modified:flask/app.py+43 added-70 removed
63 unmodified lines
64 return f(self, *args, **kwargs)65 return update_wrapper(wrapper_func, f)666768class 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 None13013168class 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 for
292 unmodified lines
364 self.view_functions = {}365366 # 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 = {}369370 #: 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 dictionary
704 unmodified lines
1077 self.view_functions[endpoint] = f1078 return f1079 return decorator10801081 @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 lines
1163 '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] = f11711172 @setupmethod1173 def template_filter(self, name=None):1174 """A decorator that is used to register custom template filter.
234 unmodified lines
1409 return f14101411 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))14361437 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 the
527 unmodified lines
added:tests/test_user_error_handler.py+113 added
1# -*- coding: utf-8 -*-2from werkzeug.exceptions import Forbidden, InternalServerError3import flask456def test_error_handler_subclass():7 app = flask.Flask(__name__)89 class ParentException(Exception):10 pass1112 class ChildExceptionUnregistered(ParentException):13 pass1415 class ChildExceptionRegistered(ParentException):16 pass1718 @app.errorhandler(ParentException)19 def parent_exception_handler(e):20 assert isinstance(e, ParentException)21 return 'parent'2223 @app.errorhandler(ChildExceptionRegistered)24 def child_exception_handler(e):25 assert isinstance(e, ChildExceptionRegistered)26 return 'child-registered'2728 @app.route('/parent')29 def parent_test():30 raise ParentException()3132 @app.route('/child-unregistered')33 def unregistered_test():34 raise ChildExceptionUnregistered()3536 @app.route('/child-registered')37 def registered_test():38 raise ChildExceptionRegistered()394041 c = app.test_client()4243 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'464748def test_error_handler_http_subclass():49 app = flask.Flask(__name__)5051 class ForbiddenSubclassRegistered(Forbidden):52 pass5354 class ForbiddenSubclassUnregistered(Forbidden):55 pass5657 @app.errorhandler(403)58 def code_exception_handler(e):59 assert isinstance(e, Forbidden)60 return 'forbidden'6162 @app.errorhandler(ForbiddenSubclassRegistered)63 def subclass_exception_handler(e):64 assert isinstance(e, ForbiddenSubclassRegistered)65 return 'forbidden-registered'6667 @app.route('/forbidden')68 def forbidden_test():69 raise Forbidden()7071 @app.route('/forbidden-registered')72 def registered_test():73 raise ForbiddenSubclassRegistered()7475 @app.route('/forbidden-unregistered')76 def unregistered_test():77 raise ForbiddenSubclassUnregistered()787980 c = app.test_client()8182 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'858687def 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'