Skip to content
Myr

Utilise defaultdicts

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

This code originates from the Python 2.4 supporting version of Flask, with defaultdicts being added in 2.5. Using defaultdict makes the intentional usage clearer, and slightly simplifies the code.

authored by pgjones · committed by David Lord · parent 5fea7ca · Browse files · 3 files+23 added−21 removed
This commit

State

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

Diff stats

3 files+23 added−21 removed

  • other:+23 added−21 removed

3 files+23 added−21 removed

modified:src/flask/app.py+6 added-6 removed
1290 unmodified lines
1291 (None, code),1292 (request.blueprint, None),1293 (None, None),1294 ):1295 handler_map = self.error_handler_spec.setdefault(name, {}).get(c)1295 handler_map = self.error_handler_spec[name][c]12961297 if not handler_map:1298 continue1299
452 unmodified lines
1752 automatically called on URL building.17531754 .. versionadded:: 0.71755 """1756 funcs = self.url_default_functions.get(None, ())1756 funcs = self.url_default_functions[None]1757 if "." in endpoint:1758 bp = endpoint.rsplit(".", 1)[0]1759 funcs = chain(funcs, self.url_default_functions.get(bp, ()))1759 funcs = chain(funcs, self.url_default_functions[bp])1760 for func in funcs:1761 func(endpoint, values)17621763 def handle_url_build_error(self, error, endpoint, values):
29 unmodified lines
1793 """17941795 bp = _request_ctx_stack.top.request.blueprint17961797 funcs = self.url_value_preprocessors.get(None, ())1797 funcs = self.url_value_preprocessors[None]1798 if bp is not None and bp in self.url_value_preprocessors:1799 funcs = chain(funcs, self.url_value_preprocessors[bp])1800 for func in funcs:1801 func(request.endpoint, request.view_args)18021803 funcs = self.before_request_funcs.get(None, ())1803 funcs = self.before_request_funcs[None]1804 if bp is not None and bp in self.before_request_funcs:1805 funcs = chain(funcs, self.before_request_funcs[bp])1806 for func in funcs:1807 rv = func()
48 unmodified lines
1856 Added the ``exc`` argument.1857 """1858 if exc is _sentinel:1859 exc = sys.exc_info()[1]1860 funcs = reversed(self.teardown_request_funcs.get(None, ()))1860 funcs = reversed(self.teardown_request_funcs[None])1861 bp = _request_ctx_stack.top.request.blueprint1862 if bp is not None and bp in self.teardown_request_funcs:1863 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1864 for func in funcs:
168 unmodified lines
modified:src/flask/blueprints.py+1 added-1 removed
249 unmodified lines
250 Values of dict must be lists.251 """252 for key, values in self_dict.items():253 key = self.name if key is None else f"{self.name}.{key}"254 app_dict.setdefault(key, []).extend(values)254 app_dict[key].extend(values)255256 def merge_dict_nested(self_dict, app_dict):257 """Merges self_dict into app_dict. Replaces None keys with self.name.258 Values of dict must be dict.
207 unmodified lines
modified:src/flask/scaffold.py+16 added-14 removed
1from collections import defaultdict2from functools import update_wrapper34from werkzeug.exceptions import default_exceptions5from werkzeug.exceptions import HTTPException
80 unmodified lines
86 #: function.87 #:88 #: To register an error handler, use the :meth:`errorhandler`89 #: decorator.89 self.error_handler_spec = {}90 self.error_handler_spec = defaultdict(lambda: defaultdict(dict))9192 #: A dictionary with lists of functions that will be called at the93 #: beginning of each request. The key of the dictionary is the name of94 #: the blueprint this function is active for, or ``None`` for all95 #: requests. To register a function, use the :meth:`before_request`96 #: decorator.96 self.before_request_funcs = {}97 self.before_request_funcs = defaultdict(list)9899 #: A dictionary with lists of functions that should be called after100 #: each request. The key of the dictionary is the name of the blueprint101 #: this function is active for, ``None`` for all requests. This can for102 #: example be used to close database connections. To register a function103 #: here, use the :meth:`after_request` decorator.103 self.after_request_funcs = {}104 self.after_request_funcs = defaultdict(list)105106 #: A dictionary with lists of functions that are called after107 #: each request, even if an exception has occurred. The key of the108 #: dictionary is the name of the blueprint this function is active for,
3 unmodified lines
112 #: teardown_request function. To register a function here, use the113 #: :meth:`teardown_request` decorator.114 #:115 #: .. versionadded:: 0.7115 self.teardown_request_funcs = {}116 self.teardown_request_funcs = defaultdict(list)117118 #: A dictionary with list of functions that are called without argument119 #: to populate the template context. The key of the dictionary is the120 #: name of the blueprint this function is active for, ``None`` for all121 #: requests. Each returns a dictionary that the template context is122 #: updated with. To register a function here, use the123 #: :meth:`context_processor` decorator.123 self.template_context_processors = {None: [_default_template_ctx_processor]}124 self.template_context_processors = defaultdict(125 list, {None: [_default_template_ctx_processor]}126 )127128 #: A dictionary with lists of functions that are called before the129 #: :attr:`before_request_funcs` functions. The key of the dictionary is130 #: the name of the blueprint this function is active for, or ``None``131 #: for all requests. To register a function, use132 #: :meth:`url_value_preprocessor`.133 #:134 #: .. versionadded:: 0.7132 self.url_value_preprocessors = {}135 self.url_value_preprocessors = defaultdict(list)136137 #: A dictionary with lists of functions that can be used as URL value138 #: preprocessors. The key ``None`` here is used for application wide139 #: callbacks, otherwise the key is the name of the blueprint.
3 unmodified lines
143 #: provide a :meth:`url_defaults` function that adds the parameters144 #: automatically again that were removed that way.145 #:146 #: .. versionadded:: 0.7144 self.url_default_functions = {}147 self.url_default_functions = defaultdict(list)148149 def _is_setup_finished(self):150 raise NotImplementedError151
108 unmodified lines
260 The function will be called without any arguments. If it returns a261 non-None value, the value is handled as if it was the return value from262 the view, and further request handling is stopped.263 """261 self.before_request_funcs.setdefault(None, []).append(f)264 self.before_request_funcs[None].append(f)265 return f266267 @setupmethod268 def after_request(self, f):
5 unmodified lines
274275 As of Flask 0.7 this function might not be executed at the end of the276 request in case an unhandled exception occurred.277 """275 self.after_request_funcs.setdefault(None, []).append(f)278 self.after_request_funcs[None].append(f)279 return f280281 @setupmethod282 def teardown_request(self, f):
30 unmodified lines
313 immediately. Instead it will keep it alive so that the interactive314 debugger can still access it. This behavior can be controlled315 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.316 """314 self.teardown_request_funcs.setdefault(None, []).append(f)317 self.teardown_request_funcs[None].append(f)318 return f319320 @setupmethod321 def context_processor(self, f):
14 unmodified lines
336337 The function is passed the endpoint name and values dict. The return338 value is ignored.339 """337 self.url_value_preprocessors.setdefault(None, []).append(f)340 self.url_value_preprocessors[None].append(f)341 return f342343 @setupmethod344 def url_defaults(self, f):345 """Callback function for URL defaults for all view functions of the346 application. It's called with the endpoint and values and should347 update the values passed in place.348 """346 self.url_default_functions.setdefault(None, []).append(f)349 self.url_default_functions[None].append(f)350 return f351352 @setupmethod353 def errorhandler(self, code_or_exception):
64 unmodified lines
418 " code. Use a subclass of HTTPException with that code"419 " instead."420 )421419 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})420 handlers[exc_class] = f422 self.error_handler_spec[key][code][exc_class] = f423424 @staticmethod425 def _get_exc_class_and_code(exc_class_or_code):426 """Get the exception class being handled. For HTTP status codes
27 unmodified lines