Recursively traverse MRO of exception
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Markus Unterwaditzer · committed by Markus Unterwaditzer · parent aed464b · Browse files · 1 file·+25 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+25 added−15 removed
- other:+25 added−15 removed
Provenance
- Commit
7d506f2- Tree
a043a4a- Author
Markus Unterwaditzer <markus@unterwaditzer.net>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent
aed464b
1 file changed+25 added−15 removed
modified:flask/app.py+25 added-15 removed
12 unmodified lines13 from threading import Lock14 from datetime import timedelta15 from itertools import chain16 from functools import update_wrapper17-from collections import Mapping17+from collections import Mapping, deque18 19 from werkzeug.datastructures import ImmutableDict20 from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21 from werkzeug.exceptions import HTTPException, InternalServerError, \1388 unmodified lines1410 """Finds a registered error handler for the request’s blueprint.1411 If neither blueprint nor App has a suitable handler registered, returns None1412 """1413 exc_class, code = self._get_exc_class_and_code(type(e))1414- 1415- def find_superclass(handler_map):1414+1415+ def find_handler(handler_map):1416 if not handler_map:1417- return None1418- for superclass in exc_class.__mro__:1419- if superclass is BaseException:1420- return None1421- handler = handler_map.get(superclass)1417+ return1418+ queue = deque(exc_class.__mro__)1419+ # Protect from geniuses who might create circular references in1420+ # __mro__1421+ done = set()1422+1423+ while True:1424+ cls = queue.popleft()1425+ if cls in done:1426+ continue1427+ done.add(cls)1428+ handler = handler_map.get(cls)1429 if handler is not None:1423- handler_map[exc_class] = handler # cache for next time exc_class is raised1430+ # cache for next time exc_class is raised1431+ handler_map[exc_class] = handler1432 return handler1425- return None1426- 1433+1434+ queue.extend(cls.__mro__)1435+1436 # try blueprint handlers1428- handler = find_superclass(self.error_handler_spec.get(request.blueprint, {}).get(code))1429- 1437+ handler = find_handler(self.error_handler_spec1438+ .get(request.blueprint, {})1439+ .get(code))1440 if handler is not None:1441 return handler1432- 1442+1443 # fall back to app handlers1434- return find_superclass(self.error_handler_spec[None].get(code))1444+ return find_handler(self.error_handler_spec[None].get(code))1445 1446 def handle_http_exception(self, e):1447 """Handles an HTTP exception. By default this will invoke the1448 registered error handlers and fall back to returning the527 unmodified lines