Skip to content
Myr

extract common Flask/Blueprint API to Scaffold base class

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

authored by yk396 · committed by David Lord · parent 216d97c · Browse files · 5 files+473 added−495 removed
This commit

State

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

Trailers

  • Co-authored-by: Chris Nguyen <chrisngyn99@gmail.com>

Diff stats

5 files+473 added−495 removed

  • other:+473 added−495 removed

5 files+473 added−495 removed

modified:src/flask/app.py+14 added-353 removed
1import os2import sys3from datetime import timedelta4from functools import update_wrapper4from itertools import chain5from threading import Lock67from werkzeug.datastructures import Headers8from werkzeug.datastructures import ImmutableDict9from werkzeug.exceptions import BadRequest10from werkzeug.exceptions import BadRequestKeyError12from werkzeug.exceptions import default_exceptions11from werkzeug.exceptions import HTTPException12from werkzeug.exceptions import InternalServerError13from werkzeug.routing import BuildError14from werkzeug.routing import Map
12 unmodified lines
27from .globals import _request_ctx_stack28from .globals import g29from .globals import request30from .globals import session33from .helpers import _endpoint_from_view_func34from .helpers import _PackageBoundObject31from .helpers import find_package32from .helpers import get_debug_flag33from .helpers import get_env34from .helpers import get_flashed_messages
1 unmodified line
36from .helpers import locked_cached_property37from .helpers import url_for38from .json import jsonify39from .logging import create_logger40from .scaffold import _endpoint_from_view_func41from .scaffold import _sentinel42from .scaffold import Scaffold43from .scaffold import setupmethod44from .sessions import SecureCookieSessionInterface45from .signals import appcontext_tearing_down46from .signals import got_request_exception47from .signals import request_finished48from .signals import request_started49from .signals import request_tearing_down50from .templating import _default_template_ctx_processor50from .templating import DispatchingJinjaLoader51from .templating import Environment52from .wrappers import Request53from .wrappers import Response5456# a singleton sentinel value for parameter defaults57_sentinel = object()555956def _make_timedelta(value):57 if not isinstance(value, timedelta):58 return timedelta(seconds=value)59 return value606166def setupmethod(f):67 """Wraps a method so that it performs a check in debug mode if the68 first request was already handled.69 """7071 def wrapper_func(self, *args, **kwargs):72 if self.debug and self._got_first_request:73 raise AssertionError(74 "A setup function was called after the "75 "first request was handled. This usually indicates a bug "76 "in the application where a module was not imported "77 "and decorators or other functionality was called too late.\n"78 "To fix this make sure to import all your view modules, "79 "database models and everything related at a central place "80 "before the application starts serving requests."81 )82 return f(self, *args, **kwargs)8384 return update_wrapper(wrapper_func, f)858687class Flask(_PackageBoundObject):62class Flask(Scaffold):63 """The flask object implements a WSGI application and acts as the central64 object. It is passed the name of the module or package of the65 application. Once it is created it will act as a central registry for66 the view functions, the URL rules, template configuration and much more.
301 unmodified lines
368 instance_path=None,369 instance_relative_config=False,370 root_path=None,371 ):397 _PackageBoundObject.__init__(398 self, import_name, template_folder=template_folder, root_path=root_path372 super().__init__(373 import_name=import_name,374 static_folder=static_folder,375 static_url_path=static_url_path,376 template_folder=template_folder,377 root_path=root_path,378 )379401 self.static_url_path = static_url_path402 self.static_folder = static_folder403380 if instance_path is None:381 instance_path = self.auto_find_instance_path()382 elif not os.path.isabs(instance_path):383 raise ValueError(
10 unmodified lines
394 #: exactly like a regular dictionary but supports additional methods395 #: to load a config from files.396 self.config = self.make_config(instance_relative_config)397422 #: A dictionary of all view functions registered. The keys will423 #: be function names which are also used to generate URLs and424 #: the values are the function objects themselves.425 #: To register a view function, use the :meth:`route` decorator.426 self.view_functions = {}427428 #: A dictionary of all registered error handlers. The key is ``None``429 #: for error handlers active on the application, otherwise the key is430 #: the name of the blueprint. Each key points to another dictionary431 #: where the key is the status code of the http exception. The432 #: special key ``None`` points to a list of tuples where the first item433 #: is the class for the instance check and the second the error handler434 #: function.435 #:436 #: To register an error handler, use the :meth:`errorhandler`437 #: decorator.438 self.error_handler_spec = {}439398 #: A list of functions that are called when :meth:`url_for` raises a399 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here400 #: is called with `error`, `endpoint` and `values`. If a function401 #: returns ``None`` or raises a :exc:`BuildError` the next function is
1 unmodified line
403 #:404 #: .. versionadded:: 0.9405 self.url_build_error_handlers = []406449 #: A dictionary with lists of functions that will be called at the450 #: beginning of each request. The key of the dictionary is the name of451 #: the blueprint this function is active for, or ``None`` for all452 #: requests. To register a function, use the :meth:`before_request`453 #: decorator.454 self.before_request_funcs = {}455407 #: A list of functions that will be called at the beginning of the408 #: first request to this instance. To register a function, use the409 #: :meth:`before_first_request` decorator.410 #:411 #: .. versionadded:: 0.8412 self.before_first_request_funcs = []413463 #: A dictionary with lists of functions that should be called after464 #: each request. The key of the dictionary is the name of the blueprint465 #: this function is active for, ``None`` for all requests. This can for466 #: example be used to close database connections. To register a function467 #: here, use the :meth:`after_request` decorator.468 self.after_request_funcs = {}469470 #: A dictionary with lists of functions that are called after471 #: each request, even if an exception has occurred. The key of the472 #: dictionary is the name of the blueprint this function is active for,473 #: ``None`` for all requests. These functions are not allowed to modify474 #: the request, and their return values are ignored. If an exception475 #: occurred while processing the request, it gets passed to each476 #: teardown_request function. To register a function here, use the477 #: :meth:`teardown_request` decorator.478 #:479 #: .. versionadded:: 0.7480 self.teardown_request_funcs = {}481414 #: A list of functions that are called when the application context415 #: is destroyed. Since the application context is also torn down416 #: if the request ends this is the place to store code that disconnects417 #: from databases.418 #:419 #: .. versionadded:: 0.9420 self.teardown_appcontext_funcs = []421490 #: A dictionary with lists of functions that are called before the491 #: :attr:`before_request_funcs` functions. The key of the dictionary is492 #: the name of the blueprint this function is active for, or ``None``493 #: for all requests. To register a function, use494 #: :meth:`url_value_preprocessor`.495 #:496 #: .. versionadded:: 0.7497 self.url_value_preprocessors = {}498499 #: A dictionary with lists of functions that can be used as URL value500 #: preprocessors. The key ``None`` here is used for application wide501 #: callbacks, otherwise the key is the name of the blueprint.502 #: Each of these functions has the chance to modify the dictionary503 #: of URL values before they are used as the keyword arguments of the504 #: view function. For each function registered this one should also505 #: provide a :meth:`url_defaults` function that adds the parameters506 #: automatically again that were removed that way.507 #:508 #: .. versionadded:: 0.7509 self.url_default_functions = {}510511 #: A dictionary with list of functions that are called without argument512 #: to populate the template context. The key of the dictionary is the513 #: name of the blueprint this function is active for, ``None`` for all514 #: requests. Each returns a dictionary that the template context is515 #: updated with. To register a function here, use the516 #: :meth:`context_processor` decorator.517 self.template_context_processors = {None: [_default_template_ctx_processor]}518422 #: A list of shell context processor functions that should be run423 #: when a shell context is created.424 #:425 #: .. versionadded:: 0.11
62 unmodified lines
488 # Set the name of the Click group in case someone wants to add489 # the app's commands to another CLI tool.490 self.cli.name = self.name491492 def _is_setup_finished(self):493 return self.debug and self._got_first_request494495 @locked_cached_property496 def name(self):497 """The name of the application. This is usually the import name498 with the difference that it's guessed from the run file if the
612 unmodified lines
1111 f" endpoint function: {endpoint}"1112 )1113 self.view_functions[endpoint] = view_func11141209 def route(self, rule, **options):1210 """A decorator that is used to register a view function for a1211 given URL rule. This does the same thing as :meth:`add_url_rule`1212 but is intended for decorator usage::12131214 @app.route('/')1215 def index():1216 return 'Hello World'12171218 For more information refer to :ref:`url-route-registrations`.12191220 :param rule: the URL rule as string1221 :param endpoint: the endpoint for the registered URL rule. Flask1222 itself assumes the name of the view function as1223 endpoint1224 :param options: the options to be forwarded to the underlying1225 :class:`~werkzeug.routing.Rule` object. A change1226 to Werkzeug is handling of method options. methods1227 is a list of methods this rule should be limited1228 to (``GET``, ``POST`` etc.). By default a rule1229 just listens for ``GET`` (and implicitly ``HEAD``).1230 Starting with Flask 0.6, ``OPTIONS`` is implicitly1231 added and handled by the standard request handling.1232 """12331234 def decorator(f):1235 endpoint = options.pop("endpoint", None)1236 self.add_url_rule(rule, endpoint, f, **options)1237 return f12381239 return decorator12401115 @setupmethod1242 def endpoint(self, endpoint):1243 """A decorator to register a function as an endpoint.1244 Example::12451246 @app.endpoint('example.endpoint')1247 def example():1248 return "example"12491250 :param endpoint: the name of the endpoint1251 """12521253 def decorator(f):1254 self.view_functions[endpoint] = f1255 return f12561257 return decorator12581259 @staticmethod1260 def _get_exc_class_and_code(exc_class_or_code):1261 """Get the exception class being handled. For HTTP status codes1262 or ``HTTPException`` subclasses, return both the exception and1263 status code.12641265 :param exc_class_or_code: Any exception class, or an HTTP status1266 code as an integer.1267 """1268 if isinstance(exc_class_or_code, int):1269 exc_class = default_exceptions[exc_class_or_code]1270 else:1271 exc_class = exc_class_or_code12721273 assert issubclass(1274 exc_class, Exception1275 ), "Custom exceptions must be subclasses of Exception."12761277 if issubclass(exc_class, HTTPException):1278 return exc_class, exc_class.code1279 else:1280 return exc_class, None12811282 @setupmethod1283 def errorhandler(self, code_or_exception):1284 """Register a function to handle errors by code or exception class.12851286 A decorator that is used to register a function given an1287 error code. Example::12881289 @app.errorhandler(404)1290 def page_not_found(error):1291 return 'This page does not exist', 40412921293 You can also register handlers for arbitrary exceptions::12941295 @app.errorhandler(DatabaseError)1296 def special_exception_handler(error):1297 return 'Database connection failed', 50012981299 .. versionadded:: 0.71300 Use :meth:`register_error_handler` instead of modifying1301 :attr:`error_handler_spec` directly, for application wide error1302 handlers.13031304 .. versionadded:: 0.71305 One can now additionally also register custom exception types1306 that do not necessarily have to be a subclass of the1307 :class:`~werkzeug.exceptions.HTTPException` class.13081309 :param code_or_exception: the code as integer for the handler, or1310 an arbitrary exception1311 """13121313 def decorator(f):1314 self._register_error_handler(None, code_or_exception, f)1315 return f13161317 return decorator13181319 @setupmethod1320 def register_error_handler(self, code_or_exception, f):1321 """Alternative error attach function to the :meth:`errorhandler`1322 decorator that is more straightforward to use for non decorator1323 usage.13241325 .. versionadded:: 0.71326 """1327 self._register_error_handler(None, code_or_exception, f)13281329 @setupmethod1330 def _register_error_handler(self, key, code_or_exception, f):1331 """1332 :type key: None|str1333 :type code_or_exception: int|T<=Exception1334 :type f: callable1335 """1336 if isinstance(code_or_exception, HTTPException): # old broken behavior1337 raise ValueError(1338 "Tried to register a handler for an exception instance"1339 f" {code_or_exception!r}. Handlers can only be"1340 " registered for exception classes or HTTP error codes."1341 )13421343 try:1344 exc_class, code = self._get_exc_class_and_code(code_or_exception)1345 except KeyError:1346 raise KeyError(1347 f"'{code_or_exception}' is not a recognized HTTP error"1348 " code. Use a subclass of HTTPException with that code"1349 " instead."1350 )13511352 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1353 handlers[exc_class] = f13541355 @setupmethod1116 def template_filter(self, name=None):1117 """A decorator that is used to register custom template filter.1118 You can specify a name for the filter, otherwise the function1119 name will be used. Example::
95 unmodified lines
1215 """1216 self.jinja_env.globals[name or f.__name__] = f12171218 @setupmethod1459 def before_request(self, f):1460 """Registers a function to run before each request.14611462 For example, this can be used to open a database connection, or to load1463 the logged in user from the session.14641465 The function will be called without any arguments. If it returns a1466 non-None value, the value is handled as if it was the return value from1467 the view, and further request handling is stopped.1468 """1469 self.before_request_funcs.setdefault(None, []).append(f)1470 return f14711472 @setupmethod1219 def before_first_request(self, f):1220 """Registers a function to be run before the first request to this1221 instance of the application.1222
5 unmodified lines
1228 self.before_first_request_funcs.append(f)1229 return f12301231 @setupmethod1486 def after_request(self, f):1487 """Register a function to be run after each request.14881489 Your function must take one parameter, an instance of1490 :attr:`response_class` and return a new response object or the1491 same (see :meth:`process_response`).14921493 As of Flask 0.7 this function might not be executed at the end of the1494 request in case an unhandled exception occurred.1495 """1496 self.after_request_funcs.setdefault(None, []).append(f)1497 return f14981499 @setupmethod1500 def teardown_request(self, f):1501 """Register a function to be run at the end of each request,1502 regardless of whether there was an exception or not. These functions1503 are executed when the request context is popped, even if not an1504 actual request was performed.15051506 Example::15071508 ctx = app.test_request_context()1509 ctx.push()1510 ...1511 ctx.pop()15121513 When ``ctx.pop()`` is executed in the above example, the teardown1514 functions are called just before the request context moves from the1515 stack of active contexts. This becomes relevant if you are using1516 such constructs in tests.15171518 Generally teardown functions must take every necessary step to avoid1519 that they will fail. If they do execute code that might fail they1520 will have to surround the execution of these code by try/except1521 statements and log occurring errors.15221523 When a teardown function was called because of an exception it will1524 be passed an error object.15251526 The return values of teardown functions are ignored.15271528 .. admonition:: Debug Note15291530 In debug mode Flask will not tear down a request on an exception1531 immediately. Instead it will keep it alive so that the interactive1532 debugger can still access it. This behavior can be controlled1533 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.1534 """1535 self.teardown_request_funcs.setdefault(None, []).append(f)1536 return f15371538 @setupmethod1232 def teardown_appcontext(self, f):1233 """Registers a function to be called when the application context1234 ends. These functions are typically also called when the request1235 context is popped.
25 unmodified lines
1261 self.teardown_appcontext_funcs.append(f)1262 return f12631264 @setupmethod1572 def context_processor(self, f):1573 """Registers a template context processor function."""1574 self.template_context_processors[None].append(f)1575 return f15761577 @setupmethod1265 def shell_context_processor(self, f):1266 """Registers a shell context processor function.12671268 .. versionadded:: 0.111269 """1270 self.shell_context_processors.append(f)1271 return f12721586 @setupmethod1587 def url_value_preprocessor(self, f):1588 """Register a URL value preprocessor function for all view1589 functions in the application. These functions will be called before the1590 :meth:`before_request` functions.15911592 The function can modify the values captured from the matched url before1593 they are passed to the view. For example, this can be used to pop a1594 common language code value and place it in ``g`` rather than pass it to1595 every view.15961597 The function is passed the endpoint name and values dict. The return1598 value is ignored.1599 """1600 self.url_value_preprocessors.setdefault(None, []).append(f)1601 return f16021603 @setupmethod1604 def url_defaults(self, f):1605 """Callback function for URL defaults for all view functions of the1606 application. It's called with the endpoint and values and should1607 update the values passed in place.1608 """1609 self.url_default_functions.setdefault(None, []).append(f)1610 return f16111273 def _find_error_handler(self, e):1274 """Return a registered error handler for an exception in this order:1275 blueprint handler for a specific code, app handler for a specific code,1276 blueprint handler for an exception class, app handler for an exception
758 unmodified lines
modified:src/flask/blueprints.py+43 added-134 removed
1from functools import update_wrapper23from .helpers import _endpoint_from_view_func4from .helpers import _PackageBoundObject3from .scaffold import _endpoint_from_view_func4from .scaffold import _sentinel5from .scaffold import Scaffold66# a singleton sentinel value for parameter defaults7_sentinel = object()798class BlueprintSetupState:9 """Temporary holder object for registering a blueprint with the10 application. An instance of this class is created by the11 :meth:`~flask.Blueprint.make_setup_state` method and later passed
61 unmodified lines
73 **options,74 )757679class Blueprint(_PackageBoundObject):77class Blueprint(Scaffold):78 """Represents a blueprint, a collection of routes and other79 app-related functions that can be registered on a real application80 later.81
82 unmodified lines
164 url_defaults=None,165 root_path=None,166 cli_group=_sentinel,167 ):170 _PackageBoundObject.__init__(171 self, import_name, template_folder, root_path=root_path168 super().__init__(169 import_name=import_name,170 static_folder=static_folder,171 static_url_path=static_url_path,172 template_folder=template_folder,173 root_path=root_path,174 )175 self.name = name176 self.url_prefix = url_prefix177 self.subdomain = subdomain176 self.static_folder = static_folder177 self.static_url_path = static_url_path178 self.deferred_functions = []179 if url_defaults is None:180 url_defaults = {}181 self.url_values_defaults = url_defaults182 self.cli_group = cli_group183184 def _is_setup_finished(self):185 return self.warn_on_modifications and self._got_registered_once186187 def record(self, func):188 """Registers a function that is called when the blueprint is189 registered on the application. This function is called with the190 state as argument as returned by the :meth:`make_setup_state`
52 unmodified lines
243 view_func=self.send_static_file,244 endpoint="static",245 )246247 # Merge app and self dictionaries.248 def merge_dict_lists(self_dict, app_dict):249 """Merges self_dict into app_dict. Replaces None keys with self.name.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)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.259 """260 for key, value in self_dict.items():261 key = self.name if key is None else f"{self.name}.{key}"262 app_dict[key] = value263264 app.view_functions.update(self.view_functions)265266 merge_dict_lists(self.before_request_funcs, app.before_request_funcs)267 merge_dict_lists(self.after_request_funcs, app.after_request_funcs)268 merge_dict_lists(self.teardown_request_funcs, app.teardown_request_funcs)269 merge_dict_lists(self.url_default_functions, app.url_default_functions)270 merge_dict_lists(self.url_value_preprocessors, app.url_value_preprocessors)271 merge_dict_lists(272 self.template_context_processors, app.template_context_processors273 )274275 merge_dict_nested(self.error_handler_spec, app.error_handler_spec)276277 for deferred in self.deferred_functions:278 deferred(state)279280 cli_resolved_group = options.get("cli_group", self.cli_group)
9 unmodified lines
290 else:291 self.cli.name = cli_resolved_group292 app.cli.add_command(self.cli)293261 def route(self, rule, **options):262 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the263 :func:`url_for` function is prefixed with the name of the blueprint.264 """265266 def decorator(f):267 endpoint = options.pop("endpoint", f.__name__)268 self.add_url_rule(rule, endpoint, f, **options)269 return f270271 return decorator272294 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):295 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for296 the :func:`url_for` function is prefixed with the name of the blueprint.297 """
4 unmodified lines
302 "." not in view_func.__name__303 ), "Blueprint view function name should not contain dots"304 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))305285 def endpoint(self, endpoint):286 """Like :meth:`Flask.endpoint` but for a blueprint. This does not287 prefix the endpoint with the blueprint name, this has to be done288 explicitly by the user of this method. If the endpoint is prefixed289 with a `.` it will be registered to the current blueprint, otherwise290 it's an application independent endpoint.291 """292293 def decorator(f):294 def register_endpoint(state):295 state.app.view_functions[endpoint] = f296297 self.record_once(register_endpoint)298 return f299300 return decorator301306 def app_template_filter(self, name=None):307 """Register a custom template filter, available application wide. Like308 :meth:`Flask.template_filter` but for a blueprint.309
84 unmodified lines
394 state.app.jinja_env.globals[name or f.__name__] = f395396 self.record_once(register_template)397394 def before_request(self, f):395 """Like :meth:`Flask.before_request` but for a blueprint. This function396 is only executed before each request that is handled by a function of397 that blueprint.398 """399 self.record_once(400 lambda s: s.app.before_request_funcs.setdefault(self.name, []).append(f)401 )402 return f403398 def before_app_request(self, f):399 """Like :meth:`Flask.before_request`. Such a function is executed400 before each request, even if outside of a blueprint.401 """
8 unmodified lines
410 """411 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))412 return f413420 def after_request(self, f):421 """Like :meth:`Flask.after_request` but for a blueprint. This function422 is only executed after each request that is handled by a function of423 that blueprint.424 """425 self.record_once(426 lambda s: s.app.after_request_funcs.setdefault(self.name, []).append(f)427 )428 return f429414 def after_app_request(self, f):415 """Like :meth:`Flask.after_request` but for a blueprint. Such a function416 is executed after each request, even if outside of the blueprint.417 """
1 unmodified line
419 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)420 )421 return f422439 def teardown_request(self, f):440 """Like :meth:`Flask.teardown_request` but for a blueprint. This441 function is only executed when tearing down requests handled by a442 function of that blueprint. Teardown request functions are executed443 when the request context is popped, even when no actual request was444 performed.445 """446 self.record_once(447 lambda s: s.app.teardown_request_funcs.setdefault(self.name, []).append(f)448 )449 return f450423 def teardown_app_request(self, f):424 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a425 function is executed when tearing down each request, even if outside of426 the blueprint.
2 unmodified lines
429 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)430 )431 return f432461 def context_processor(self, f):462 """Like :meth:`Flask.context_processor` but for a blueprint. This463 function is only executed for requests handled by a blueprint.464 """465 self.record_once(466 lambda s: s.app.template_context_processors.setdefault(467 self.name, []468 ).append(f)469 )470 return f471433 def app_context_processor(self, f):434 """Like :meth:`Flask.context_processor` but for a blueprint. Such a435 function is executed each request, even if outside of the blueprint.436 """
12 unmodified lines
449 return f450451 return decorator452492 def url_value_preprocessor(self, f):493 """Registers a function as URL value preprocessor for this494 blueprint. It's called before the view functions are called and495 can modify the url values provided.496 """497 self.record_once(498 lambda s: s.app.url_value_preprocessors.setdefault(self.name, []).append(f)499 )500 return f501502 def url_defaults(self, f):503 """Callback function for URL defaults for this blueprint. It's called504 with the endpoint and values and should update the values passed505 in place.506 """507 self.record_once(508 lambda s: s.app.url_default_functions.setdefault(self.name, []).append(f)509 )510 return f511453 def app_url_value_preprocessor(self, f):454 """Same as :meth:`url_value_preprocessor` but application wide.455 """456 self.record_once(
7 unmodified lines
464 self.record_once(465 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)466 )467 return f527528 def errorhandler(self, code_or_exception):529 """Registers an error handler that becomes active for this blueprint530 only. Please be aware that routing does not happen local to a531 blueprint so an error handler for 404 usually is not handled by532 a blueprint unless it is caused inside a view function. Another533 special case is the 500 internal server error which is always looked534 up from the application.535536 Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator537 of the :class:`~flask.Flask` object.538 """539540 def decorator(f):541 self.record_once(542 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)543 )544 return f545546 return decorator547548 def register_error_handler(self, code_or_exception, f):549 """Non-decorator version of the :meth:`errorhandler` error attach550 function, akin to the :meth:`~flask.Flask.register_error_handler`551 application-wide function of the :class:`~flask.Flask` object but552 for error handlers limited to this blueprint.553554 .. versionadded:: 0.11555 """556 self.record_once(557 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)558 )
modified:src/flask/helpers.py-8 removed
74 unmodified lines
7576 return val.lower() in ("0", "false", "no")777879def _endpoint_from_view_func(view_func):80 """Internal helper that returns the default endpoint for a given81 function. This always is the function name.82 """83 assert view_func is not None, "expected view func if endpoint is not provided."84 return view_func.__name__858679def stream_with_context(generator_or_function):80 """Request contexts disappear when the response is started on the server.81 This is done for efficiency reasons and to make it less likely to encounter82 memory leaks with badly written WSGI middlewares. The downside is that if
1035 unmodified lines
added:src/flask/scaffold.py+411 added
1from functools import update_wrapper23from werkzeug.exceptions import default_exceptions4from werkzeug.exceptions import HTTPException56from .helpers import _PackageBoundObject7from .templating import _default_template_ctx_processor89# a singleton sentinel value for parameter defaults10_sentinel = object()111213def setupmethod(f):14 """Wraps a method so that it performs a check in debug mode if the15 first request was already handled.16 """1718 def wrapper_func(self, *args, **kwargs):19 if self._is_setup_finished():20 raise AssertionError(21 "A setup function was called after the "22 "first request was handled. This usually indicates a bug "23 "in the application where a module was not imported "24 "and decorators or other functionality was called too late.\n"25 "To fix this make sure to import all your view modules, "26 "database models and everything related at a central place "27 "before the application starts serving requests."28 )29 return f(self, *args, **kwargs)3031 return update_wrapper(wrapper_func, f)323334class Scaffold(_PackageBoundObject):35 """A common base for class Flask and class Blueprint.36 """3738 #: Skeleton local JSON decoder class to use.39 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.40 json_encoder = None4142 #: Skeleton local JSON decoder class to use.43 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.44 json_decoder = None4546 #: The name of the package or module that this app belongs to. Do not47 #: change this once it is set by the constructor.48 import_name = None4950 #: Location of the template files to be added to the template lookup.51 #: ``None`` if templates should not be added.52 template_folder = None5354 #: Absolute path to the package on the filesystem. Used to look up55 #: resources contained in the package.56 root_path = None5758 def __init__(59 self,60 import_name,61 static_folder="static",62 static_url_path=None,63 template_folder=None,64 root_path=None,65 ):66 super().__init__(67 import_name=import_name,68 template_folder=template_folder,69 root_path=root_path,70 )71 self.static_folder = static_folder72 self.static_url_path = static_url_path7374 #: A dictionary of all view functions registered. The keys will75 #: be function names which are also used to generate URLs and76 #: the values are the function objects themselves.77 #: To register a view function, use the :meth:`route` decorator.78 self.view_functions = {}7980 #: A dictionary of all registered error handlers. The key is ``None``81 #: for error handlers active on the application, otherwise the key is82 #: the name of the blueprint. Each key points to another dictionary83 #: where the key is the status code of the http exception. The84 #: special key ``None`` points to a list of tuples where the first item85 #: is the class for the instance check and the second the error handler86 #: function.87 #:88 #: To register an error handler, use the :meth:`errorhandler`89 #: decorator.90 self.error_handler_spec = {}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.97 self.before_request_funcs = {}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.104 self.after_request_funcs = {}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,109 #: ``None`` for all requests. These functions are not allowed to modify110 #: the request, and their return values are ignored. If an exception111 #: occurred while processing the request, it gets passed to each112 #: teardown_request function. To register a function here, use the113 #: :meth:`teardown_request` decorator.114 #:115 #: .. versionadded:: 0.7116 self.teardown_request_funcs = {}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.124 self.template_context_processors = {None: [_default_template_ctx_processor]}125126 #: A dictionary with lists of functions that are called before the127 #: :attr:`before_request_funcs` functions. The key of the dictionary is128 #: the name of the blueprint this function is active for, or ``None``129 #: for all requests. To register a function, use130 #: :meth:`url_value_preprocessor`.131 #:132 #: .. versionadded:: 0.7133 self.url_value_preprocessors = {}134135 #: A dictionary with lists of functions that can be used as URL value136 #: preprocessors. The key ``None`` here is used for application wide137 #: callbacks, otherwise the key is the name of the blueprint.138 #: Each of these functions has the chance to modify the dictionary139 #: of URL values before they are used as the keyword arguments of the140 #: view function. For each function registered this one should also141 #: provide a :meth:`url_defaults` function that adds the parameters142 #: automatically again that were removed that way.143 #:144 #: .. versionadded:: 0.7145 self.url_default_functions = {}146147 def _is_setup_finished(self):148 raise NotImplementedError149150 def route(self, rule, **options):151 """A decorator that is used to register a view function for a152 given URL rule. This does the same thing as :meth:`add_url_rule`153 but is intended for decorator usage::154155 @app.route('/')156 def index():157 return 'Hello World'158159 For more information refer to :ref:`url-route-registrations`.160161 :param rule: the URL rule as string162 :param endpoint: the endpoint for the registered URL rule. Flask163 itself assumes the name of the view function as164 endpoint165 :param options: the options to be forwarded to the underlying166 :class:`~werkzeug.routing.Rule` object. A change167 to Werkzeug is handling of method options. methods168 is a list of methods this rule should be limited169 to (``GET``, ``POST`` etc.). By default a rule170 just listens for ``GET`` (and implicitly ``HEAD``).171 Starting with Flask 0.6, ``OPTIONS`` is implicitly172 added and handled by the standard request handling.173 """174175 def decorator(f):176 endpoint = options.pop("endpoint", None)177 self.add_url_rule(rule, endpoint, f, **options)178 return f179180 return decorator181182 @setupmethod183 def add_url_rule(184 self,185 rule,186 endpoint=None,187 view_func=None,188 provide_automatic_options=None,189 **options,190 ):191 raise NotImplementedError192193 def endpoint(self, endpoint):194 """A decorator to register a function as an endpoint.195 Example::196197 @app.endpoint('example.endpoint')198 def example():199 return "example"200201 :param endpoint: the name of the endpoint202 """203204 def decorator(f):205 self.view_functions[endpoint] = f206 return f207208 return decorator209210 @setupmethod211 def before_request(self, f):212 """Registers a function to run before each request.213214 For example, this can be used to open a database connection, or to load215 the logged in user from the session.216217 The function will be called without any arguments. If it returns a218 non-None value, the value is handled as if it was the return value from219 the view, and further request handling is stopped.220 """221 self.before_request_funcs.setdefault(None, []).append(f)222 return f223224 @setupmethod225 def after_request(self, f):226 """Register a function to be run after each request.227228 Your function must take one parameter, an instance of229 :attr:`response_class` and return a new response object or the230 same (see :meth:`process_response`).231232 As of Flask 0.7 this function might not be executed at the end of the233 request in case an unhandled exception occurred.234 """235 self.after_request_funcs.setdefault(None, []).append(f)236 return f237238 @setupmethod239 def teardown_request(self, f):240 """Register a function to be run at the end of each request,241 regardless of whether there was an exception or not. These functions242 are executed when the request context is popped, even if not an243 actual request was performed.244245 Example::246247 ctx = app.test_request_context()248 ctx.push()249 ...250 ctx.pop()251252 When ``ctx.pop()`` is executed in the above example, the teardown253 functions are called just before the request context moves from the254 stack of active contexts. This becomes relevant if you are using255 such constructs in tests.256257 Generally teardown functions must take every necessary step to avoid258 that they will fail. If they do execute code that might fail they259 will have to surround the execution of these code by try/except260 statements and log occurring errors.261262 When a teardown function was called because of an exception it will263 be passed an error object.264265 The return values of teardown functions are ignored.266267 .. admonition:: Debug Note268269 In debug mode Flask will not tear down a request on an exception270 immediately. Instead it will keep it alive so that the interactive271 debugger can still access it. This behavior can be controlled272 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.273 """274 self.teardown_request_funcs.setdefault(None, []).append(f)275 return f276277 @setupmethod278 def context_processor(self, f):279 """Registers a template context processor function."""280 self.template_context_processors[None].append(f)281 return f282283 @setupmethod284 def url_value_preprocessor(self, f):285 """Register a URL value preprocessor function for all view286 functions in the application. These functions will be called before the287 :meth:`before_request` functions.288289 The function can modify the values captured from the matched url before290 they are passed to the view. For example, this can be used to pop a291 common language code value and place it in ``g`` rather than pass it to292 every view.293294 The function is passed the endpoint name and values dict. The return295 value is ignored.296 """297 self.url_value_preprocessors.setdefault(None, []).append(f)298 return f299300 @setupmethod301 def url_defaults(self, f):302 """Callback function for URL defaults for all view functions of the303 application. It's called with the endpoint and values and should304 update the values passed in place.305 """306 self.url_default_functions.setdefault(None, []).append(f)307 return f308309 @setupmethod310 def errorhandler(self, code_or_exception):311 """Register a function to handle errors by code or exception class.312313 A decorator that is used to register a function given an314 error code. Example::315316 @app.errorhandler(404)317 def page_not_found(error):318 return 'This page does not exist', 404319320 You can also register handlers for arbitrary exceptions::321322 @app.errorhandler(DatabaseError)323 def special_exception_handler(error):324 return 'Database connection failed', 500325326 .. versionadded:: 0.7327 Use :meth:`register_error_handler` instead of modifying328 :attr:`error_handler_spec` directly, for application wide error329 handlers.330331 .. versionadded:: 0.7332 One can now additionally also register custom exception types333 that do not necessarily have to be a subclass of the334 :class:`~werkzeug.exceptions.HTTPException` class.335336 :param code_or_exception: the code as integer for the handler, or337 an arbitrary exception338 """339340 def decorator(f):341 self._register_error_handler(None, code_or_exception, f)342 return f343344 return decorator345346 @setupmethod347 def register_error_handler(self, code_or_exception, f):348 """Alternative error attach function to the :meth:`errorhandler`349 decorator that is more straightforward to use for non decorator350 usage.351352 .. versionadded:: 0.7353 """354 self._register_error_handler(None, code_or_exception, f)355356 @setupmethod357 def _register_error_handler(self, key, code_or_exception, f):358 """359 :type key: None|str360 :type code_or_exception: int|T<=Exception361 :type f: callable362 """363 if isinstance(code_or_exception, HTTPException): # old broken behavior364 raise ValueError(365 "Tried to register a handler for an exception instance"366 f" {code_or_exception!r}. Handlers can only be"367 " registered for exception classes or HTTP error codes."368 )369370 try:371 exc_class, code = self._get_exc_class_and_code(code_or_exception)372 except KeyError:373 raise KeyError(374 f"'{code_or_exception}' is not a recognized HTTP error"375 " code. Use a subclass of HTTPException with that code"376 " instead."377 )378379 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})380 handlers[exc_class] = f381382 @staticmethod383 def _get_exc_class_and_code(exc_class_or_code):384 """Get the exception class being handled. For HTTP status codes385 or ``HTTPException`` subclasses, return both the exception and386 status code.387388 :param exc_class_or_code: Any exception class, or an HTTP status389 code as an integer.390 """391 if isinstance(exc_class_or_code, int):392 exc_class = default_exceptions[exc_class_or_code]393 else:394 exc_class = exc_class_or_code395396 assert issubclass(397 exc_class, Exception398 ), "Custom exceptions must be subclasses of Exception."399400 if issubclass(exc_class, HTTPException):401 return exc_class, exc_class.code402 else:403 return exc_class, None404405406def _endpoint_from_view_func(view_func):407 """Internal helper that returns the default endpoint for a given408 function. This always is the function name.409 """410 assert view_func is not None, "expected view func if endpoint is not provided."411 return view_func.__name__
modified:CHANGES.rst+5 added
35 unmodified lines
36 headers replace rather than extend existing headers on the response.37 For example, this allows setting the ``Content-Type`` for38 ``jsonify()``. Use ``response.headers.extend()`` if extending is39 desired. :issue:`3628`40- The ``Scaffold`` class provides a common API for the ``Flask`` and41 ``Blueprint`` classes. ``Blueprint`` information is stored in42 attributes just like ``Flask``, rather than opaque lambda functions.43 This is intended to improve consistency and maintainability.44 :issue:`3215`454647Version 1.1.x48-------------
1020 unmodified lines