Merge pull request #3709 from MLH-Fellowship/3215-flask-blueprint
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Common API Between Flask + Blueprint
authored by David Lord · committed by GitHub · parents 216d97c, b146a13 · 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.
Diff stats
5 files+473 added−495 removed
- other:+473 added−495 removed
Provenance
- Commit
632f85b- Tree
90d8639- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
216d97c- Parent 2
b146a13
5 files changed+473 added−495 removed
modified:src/flask/app.py+14 added-353 removed
1 import os2 import sys3 from datetime import timedelta4-from functools import update_wrapper4 from itertools import chain5 from threading import Lock6 7 from werkzeug.datastructures import Headers8 from werkzeug.datastructures import ImmutableDict9 from werkzeug.exceptions import BadRequest10 from werkzeug.exceptions import BadRequestKeyError12-from werkzeug.exceptions import default_exceptions11 from werkzeug.exceptions import HTTPException12 from werkzeug.exceptions import InternalServerError13 from werkzeug.routing import BuildError14 from werkzeug.routing import Map12 unmodified lines27 from .globals import _request_ctx_stack28 from .globals import g29 from .globals import request30 from .globals import session33-from .helpers import _endpoint_from_view_func34-from .helpers import _PackageBoundObject31 from .helpers import find_package32 from .helpers import get_debug_flag33 from .helpers import get_env34 from .helpers import get_flashed_messages1 unmodified line36 from .helpers import locked_cached_property37 from .helpers import url_for38 from .json import jsonify39 from .logging import create_logger40+from .scaffold import _endpoint_from_view_func41+from .scaffold import _sentinel42+from .scaffold import Scaffold43+from .scaffold import setupmethod44 from .sessions import SecureCookieSessionInterface45 from .signals import appcontext_tearing_down46 from .signals import got_request_exception47 from .signals import request_finished48 from .signals import request_started49 from .signals import request_tearing_down50-from .templating import _default_template_ctx_processor50 from .templating import DispatchingJinjaLoader51 from .templating import Environment52 from .wrappers import Request53 from .wrappers import Response54 56-# a singleton sentinel value for parameter defaults57-_sentinel = object()55 59-56 def _make_timedelta(value):57 if not isinstance(value, timedelta):58 return timedelta(seconds=value)59 return value60 61 66-def setupmethod(f):67- """Wraps a method so that it performs a check in debug mode if the68- first request was already handled.69- """70-71- 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)83-84- return update_wrapper(wrapper_func, f)85-86-87-class Flask(_PackageBoundObject):62+class 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 lines368 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 )379 401- self.static_url_path = static_url_path402- self.static_folder = static_folder403-380 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 lines394 #: exactly like a regular dictionary but supports additional methods395 #: to load a config from files.396 self.config = self.make_config(instance_relative_config)397 422- #: 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 = {}427-428- #: 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 = {}439-398 #: 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 is1 unmodified line403 #:404 #: .. versionadded:: 0.9405 self.url_build_error_handlers = []406 449- #: 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 = {}455-407 #: 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 = []413 463- #: 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 = {}469-470- #: 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 = {}481-414 #: 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 = []421 490- #: 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 = {}498-499- #: 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 = {}510-511- #: 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]}518-422 #: A list of shell context processor functions that should be run423 #: when a shell context is created.424 #:425 #: .. versionadded:: 0.1162 unmodified lines488 # 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.name491 492+ def _is_setup_finished(self):493+ return self.debug and self._got_first_request494+495 @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 the612 unmodified lines1111 f" endpoint function: {endpoint}"1112 )1113 self.view_functions[endpoint] = view_func1114 1209- 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::1213-1214- @app.route('/')1215- def index():1216- return 'Hello World'1217-1218- For more information refer to :ref:`url-route-registrations`.1219-1220- :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- """1233-1234- def decorator(f):1235- endpoint = options.pop("endpoint", None)1236- self.add_url_rule(rule, endpoint, f, **options)1237- return f1238-1239- return decorator1240-1115 @setupmethod1242- def endpoint(self, endpoint):1243- """A decorator to register a function as an endpoint.1244- Example::1245-1246- @app.endpoint('example.endpoint')1247- def example():1248- return "example"1249-1250- :param endpoint: the name of the endpoint1251- """1252-1253- def decorator(f):1254- self.view_functions[endpoint] = f1255- return f1256-1257- return decorator1258-1259- @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.1264-1265- :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_code1272-1273- assert issubclass(1274- exc_class, Exception1275- ), "Custom exceptions must be subclasses of Exception."1276-1277- if issubclass(exc_class, HTTPException):1278- return exc_class, exc_class.code1279- else:1280- return exc_class, None1281-1282- @setupmethod1283- def errorhandler(self, code_or_exception):1284- """Register a function to handle errors by code or exception class.1285-1286- A decorator that is used to register a function given an1287- error code. Example::1288-1289- @app.errorhandler(404)1290- def page_not_found(error):1291- return 'This page does not exist', 4041292-1293- You can also register handlers for arbitrary exceptions::1294-1295- @app.errorhandler(DatabaseError)1296- def special_exception_handler(error):1297- return 'Database connection failed', 5001298-1299- .. versionadded:: 0.71300- Use :meth:`register_error_handler` instead of modifying1301- :attr:`error_handler_spec` directly, for application wide error1302- handlers.1303-1304- .. 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.1308-1309- :param code_or_exception: the code as integer for the handler, or1310- an arbitrary exception1311- """1312-1313- def decorator(f):1314- self._register_error_handler(None, code_or_exception, f)1315- return f1316-1317- return decorator1318-1319- @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.1324-1325- .. versionadded:: 0.71326- """1327- self._register_error_handler(None, code_or_exception, f)1328-1329- @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- )1342-1343- 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- )1351-1352- handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1353- handlers[exc_class] = f1354-1355- @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 lines1215 """1216 self.jinja_env.globals[name or f.__name__] = f1217 1218 @setupmethod1459- def before_request(self, f):1460- """Registers a function to run before each request.1461-1462- For example, this can be used to open a database connection, or to load1463- the logged in user from the session.1464-1465- 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 f1471-1472- @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 lines1228 self.before_first_request_funcs.append(f)1229 return f1230 1231 @setupmethod1486- def after_request(self, f):1487- """Register a function to be run after each request.1488-1489- 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`).1492-1493- 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 f1498-1499- @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.1505-1506- Example::1507-1508- ctx = app.test_request_context()1509- ctx.push()1510- ...1511- ctx.pop()1512-1513- 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.1517-1518- 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.1522-1523- When a teardown function was called because of an exception it will1524- be passed an error object.1525-1526- The return values of teardown functions are ignored.1527-1528- .. admonition:: Debug Note1529-1530- 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 f1537-1538- @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 lines1261 self.teardown_appcontext_funcs.append(f)1262 return f1263 1264 @setupmethod1572- def context_processor(self, f):1573- """Registers a template context processor function."""1574- self.template_context_processors[None].append(f)1575- return f1576-1577- @setupmethod1265 def shell_context_processor(self, f):1266 """Registers a shell context processor function.1267 1268 .. versionadded:: 0.111269 """1270 self.shell_context_processors.append(f)1271 return f1272 1586- @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.1591-1592- 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.1596-1597- 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 f1602-1603- @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 f1611-1273 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 exception758 unmodified linesmodified:src/flask/blueprints.py+43 added-134 removed
1 from functools import update_wrapper2 3-from .helpers import _endpoint_from_view_func4-from .helpers import _PackageBoundObject3+from .scaffold import _endpoint_from_view_func4+from .scaffold import _sentinel5+from .scaffold import Scaffold6 6-# a singleton sentinel value for parameter defaults7-_sentinel = object()7 9-8 class 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 passed61 unmodified lines73 **options,74 )75 76 79-class Blueprint(_PackageBoundObject):77+class 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 lines164 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_group183 184+ def _is_setup_finished(self):185+ return self.warn_on_modifications and self._got_registered_once186+187 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 lines243 view_func=self.send_static_file,244 endpoint="static",245 )246 247+ # 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)255+256+ 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] = value263+264+ app.view_functions.update(self.view_functions)265+266+ 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+ )274+275+ merge_dict_nested(self.error_handler_spec, app.error_handler_spec)276+277 for deferred in self.deferred_functions:278 deferred(state)279 280 cli_resolved_group = options.get("cli_group", self.cli_group)9 unmodified lines290 else:291 self.cli.name = cli_resolved_group292 app.cli.add_command(self.cli)293 261- 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- """265-266- def decorator(f):267- endpoint = options.pop("endpoint", f.__name__)268- self.add_url_rule(rule, endpoint, f, **options)269- return f270-271- return decorator272-294 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 lines302 "." 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))305 285- 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- """292-293- def decorator(f):294- def register_endpoint(state):295- state.app.view_functions[endpoint] = f296-297- self.record_once(register_endpoint)298- return f299-300- return decorator301-306 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 lines394 state.app.jinja_env.globals[name or f.__name__] = f395 396 self.record_once(register_template)397 394- 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 f403-398 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 lines410 """411 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))412 return f413 420- 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 f429-414 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 line419 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)420 )421 return f422 439- 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 f450-423 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 lines429 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)430 )431 return f432 461- 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 f471-433 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 lines449 return f450 451 return decorator452 492- 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 f501-502- 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 f511-453 def app_url_value_preprocessor(self, f):454 """Same as :meth:`url_value_preprocessor` but application wide.455 """456 self.record_once(7 unmodified lines464 self.record_once(465 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)466 )467 return f527-528- 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.535-536- Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator537- of the :class:`~flask.Flask` object.538- """539-540- def decorator(f):541- self.record_once(542- lambda s: s.app._register_error_handler(self.name, code_or_exception, f)543- )544- return f545-546- return decorator547-548- 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.553-554- .. 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 lines75 76 return val.lower() in ("0", "false", "no")77 78 79-def _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__85-86-79 def 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 if1035 unmodified linesadded:src/flask/scaffold.py+411 added
1+from functools import update_wrapper2+3+from werkzeug.exceptions import default_exceptions4+from werkzeug.exceptions import HTTPException5+6+from .helpers import _PackageBoundObject7+from .templating import _default_template_ctx_processor8+9+# a singleton sentinel value for parameter defaults10+_sentinel = object()11+12+13+def setupmethod(f):14+ """Wraps a method so that it performs a check in debug mode if the15+ first request was already handled.16+ """17+18+ 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)30+31+ return update_wrapper(wrapper_func, f)32+33+34+class Scaffold(_PackageBoundObject):35+ """A common base for class Flask and class Blueprint.36+ """37+38+ #: 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 = None41+42+ #: 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 = None45+46+ #: 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 = None49+50+ #: Location of the template files to be added to the template lookup.51+ #: ``None`` if templates should not be added.52+ template_folder = None53+54+ #: Absolute path to the package on the filesystem. Used to look up55+ #: resources contained in the package.56+ root_path = None57+58+ 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_path73+74+ #: 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 = {}79+80+ #: 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 = {}91+92+ #: 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 = {}98+99+ #: 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 = {}105+106+ #: 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 = {}117+118+ #: 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]}125+126+ #: 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 = {}134+135+ #: 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 = {}146+147+ def _is_setup_finished(self):148+ raise NotImplementedError149+150+ 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::154+155+ @app.route('/')156+ def index():157+ return 'Hello World'158+159+ For more information refer to :ref:`url-route-registrations`.160+161+ :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+ """174+175+ def decorator(f):176+ endpoint = options.pop("endpoint", None)177+ self.add_url_rule(rule, endpoint, f, **options)178+ return f179+180+ return decorator181+182+ @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 NotImplementedError192+193+ def endpoint(self, endpoint):194+ """A decorator to register a function as an endpoint.195+ Example::196+197+ @app.endpoint('example.endpoint')198+ def example():199+ return "example"200+201+ :param endpoint: the name of the endpoint202+ """203+204+ def decorator(f):205+ self.view_functions[endpoint] = f206+ return f207+208+ return decorator209+210+ @setupmethod211+ def before_request(self, f):212+ """Registers a function to run before each request.213+214+ For example, this can be used to open a database connection, or to load215+ the logged in user from the session.216+217+ 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 f223+224+ @setupmethod225+ def after_request(self, f):226+ """Register a function to be run after each request.227+228+ 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`).231+232+ 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 f237+238+ @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.244+245+ Example::246+247+ ctx = app.test_request_context()248+ ctx.push()249+ ...250+ ctx.pop()251+252+ 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.256+257+ 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.261+262+ When a teardown function was called because of an exception it will263+ be passed an error object.264+265+ The return values of teardown functions are ignored.266+267+ .. admonition:: Debug Note268+269+ 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 f276+277+ @setupmethod278+ def context_processor(self, f):279+ """Registers a template context processor function."""280+ self.template_context_processors[None].append(f)281+ return f282+283+ @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.288+289+ 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.293+294+ 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 f299+300+ @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 f308+309+ @setupmethod310+ def errorhandler(self, code_or_exception):311+ """Register a function to handle errors by code or exception class.312+313+ A decorator that is used to register a function given an314+ error code. Example::315+316+ @app.errorhandler(404)317+ def page_not_found(error):318+ return 'This page does not exist', 404319+320+ You can also register handlers for arbitrary exceptions::321+322+ @app.errorhandler(DatabaseError)323+ def special_exception_handler(error):324+ return 'Database connection failed', 500325+326+ .. versionadded:: 0.7327+ Use :meth:`register_error_handler` instead of modifying328+ :attr:`error_handler_spec` directly, for application wide error329+ handlers.330+331+ .. 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.335+336+ :param code_or_exception: the code as integer for the handler, or337+ an arbitrary exception338+ """339+340+ def decorator(f):341+ self._register_error_handler(None, code_or_exception, f)342+ return f343+344+ return decorator345+346+ @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.351+352+ .. versionadded:: 0.7353+ """354+ self._register_error_handler(None, code_or_exception, f)355+356+ @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+ )369+370+ 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+ )378+379+ handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})380+ handlers[exc_class] = f381+382+ @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.387+388+ :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_code395+396+ assert issubclass(397+ exc_class, Exception398+ ), "Custom exceptions must be subclasses of Exception."399+400+ if issubclass(exc_class, HTTPException):401+ return exc_class, exc_class.code402+ else:403+ return exc_class, None404+405+406+def _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 lines36 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`45 46 47 Version 1.1.x48 -------------1020 unmodified lines