Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/flask/app.py: 41%
575 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:03 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:03 +0000
1import functools
2import inspect
3import logging
4import os
5import sys
6import typing as t
7import weakref
8from datetime import timedelta
9from itertools import chain
10from threading import Lock
11from types import TracebackType
13from werkzeug.datastructures import Headers
14from werkzeug.datastructures import ImmutableDict
15from werkzeug.exceptions import BadRequest
16from werkzeug.exceptions import BadRequestKeyError
17from werkzeug.exceptions import HTTPException
18from werkzeug.exceptions import InternalServerError
19from werkzeug.routing import BuildError
20from werkzeug.routing import Map
21from werkzeug.routing import MapAdapter
22from werkzeug.routing import RequestRedirect
23from werkzeug.routing import RoutingException
24from werkzeug.routing import Rule
25from werkzeug.wrappers import Response as BaseResponse
27from . import cli
28from . import json
29from . import typing as ft
30from .config import Config
31from .config import ConfigAttribute
32from .ctx import _AppCtxGlobals
33from .ctx import AppContext
34from .ctx import RequestContext
35from .globals import _request_ctx_stack
36from .globals import g
37from .globals import request
38from .globals import session
39from .helpers import _split_blueprint_path
40from .helpers import get_debug_flag
41from .helpers import get_env
42from .helpers import get_flashed_messages
43from .helpers import get_load_dotenv
44from .helpers import locked_cached_property
45from .helpers import url_for
46from .json import jsonify
47from .logging import create_logger
48from .scaffold import _endpoint_from_view_func
49from .scaffold import _sentinel
50from .scaffold import find_package
51from .scaffold import Scaffold
52from .scaffold import setupmethod
53from .sessions import SecureCookieSessionInterface
54from .sessions import SessionInterface
55from .signals import appcontext_tearing_down
56from .signals import got_request_exception
57from .signals import request_finished
58from .signals import request_started
59from .signals import request_tearing_down
60from .templating import DispatchingJinjaLoader
61from .templating import Environment
62from .wrappers import Request
63from .wrappers import Response
65if t.TYPE_CHECKING:
66 import typing_extensions as te
67 from .blueprints import Blueprint
68 from .testing import FlaskClient
69 from .testing import FlaskCliRunner
71if sys.version_info >= (3, 8):
72 iscoroutinefunction = inspect.iscoroutinefunction
73else:
75 def iscoroutinefunction(func: t.Any) -> bool:
76 while inspect.ismethod(func):
77 func = func.__func__
79 while isinstance(func, functools.partial):
80 func = func.func
82 return inspect.iscoroutinefunction(func)
85def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:
86 if value is None or isinstance(value, timedelta):
87 return value
89 return timedelta(seconds=value)
92class Flask(Scaffold):
93 """The flask object implements a WSGI application and acts as the central
94 object. It is passed the name of the module or package of the
95 application. Once it is created it will act as a central registry for
96 the view functions, the URL rules, template configuration and much more.
98 The name of the package is used to resolve resources from inside the
99 package or the folder the module is contained in depending on if the
100 package parameter resolves to an actual python package (a folder with
101 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
103 For more information about resource loading, see :func:`open_resource`.
105 Usually you create a :class:`Flask` instance in your main module or
106 in the :file:`__init__.py` file of your package like this::
108 from flask import Flask
109 app = Flask(__name__)
111 .. admonition:: About the First Parameter
113 The idea of the first parameter is to give Flask an idea of what
114 belongs to your application. This name is used to find resources
115 on the filesystem, can be used by extensions to improve debugging
116 information and a lot more.
118 So it's important what you provide there. If you are using a single
119 module, `__name__` is always the correct value. If you however are
120 using a package, it's usually recommended to hardcode the name of
121 your package there.
123 For example if your application is defined in :file:`yourapplication/app.py`
124 you should create it with one of the two versions below::
126 app = Flask('yourapplication')
127 app = Flask(__name__.split('.')[0])
129 Why is that? The application will work even with `__name__`, thanks
130 to how resources are looked up. However it will make debugging more
131 painful. Certain extensions can make assumptions based on the
132 import name of your application. For example the Flask-SQLAlchemy
133 extension will look for the code in your application that triggered
134 an SQL query in debug mode. If the import name is not properly set
135 up, that debugging information is lost. (For example it would only
136 pick up SQL queries in `yourapplication.app` and not
137 `yourapplication.views.frontend`)
139 .. versionadded:: 0.7
140 The `static_url_path`, `static_folder`, and `template_folder`
141 parameters were added.
143 .. versionadded:: 0.8
144 The `instance_path` and `instance_relative_config` parameters were
145 added.
147 .. versionadded:: 0.11
148 The `root_path` parameter was added.
150 .. versionadded:: 1.0
151 The ``host_matching`` and ``static_host`` parameters were added.
153 .. versionadded:: 1.0
154 The ``subdomain_matching`` parameter was added. Subdomain
155 matching needs to be enabled manually now. Setting
156 :data:`SERVER_NAME` does not implicitly enable it.
158 :param import_name: the name of the application package
159 :param static_url_path: can be used to specify a different path for the
160 static files on the web. Defaults to the name
161 of the `static_folder` folder.
162 :param static_folder: The folder with static files that is served at
163 ``static_url_path``. Relative to the application ``root_path``
164 or an absolute path. Defaults to ``'static'``.
165 :param static_host: the host to use when adding the static route.
166 Defaults to None. Required when using ``host_matching=True``
167 with a ``static_folder`` configured.
168 :param host_matching: set ``url_map.host_matching`` attribute.
169 Defaults to False.
170 :param subdomain_matching: consider the subdomain relative to
171 :data:`SERVER_NAME` when matching routes. Defaults to False.
172 :param template_folder: the folder that contains the templates that should
173 be used by the application. Defaults to
174 ``'templates'`` folder in the root path of the
175 application.
176 :param instance_path: An alternative instance path for the application.
177 By default the folder ``'instance'`` next to the
178 package or module is assumed to be the instance
179 path.
180 :param instance_relative_config: if set to ``True`` relative filenames
181 for loading the config are assumed to
182 be relative to the instance path instead
183 of the application root.
184 :param root_path: The path to the root of the application files.
185 This should only be set manually when it can't be detected
186 automatically, such as for namespace packages.
187 """
189 #: The class that is used for request objects. See :class:`~flask.Request`
190 #: for more information.
191 request_class = Request
193 #: The class that is used for response objects. See
194 #: :class:`~flask.Response` for more information.
195 response_class = Response
197 #: The class that is used for the Jinja environment.
198 #:
199 #: .. versionadded:: 0.11
200 jinja_environment = Environment
202 #: The class that is used for the :data:`~flask.g` instance.
203 #:
204 #: Example use cases for a custom class:
205 #:
206 #: 1. Store arbitrary attributes on flask.g.
207 #: 2. Add a property for lazy per-request database connectors.
208 #: 3. Return None instead of AttributeError on unexpected attributes.
209 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
210 #:
211 #: In Flask 0.9 this property was called `request_globals_class` but it
212 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
213 #: flask.g object is now application context scoped.
214 #:
215 #: .. versionadded:: 0.10
216 app_ctx_globals_class = _AppCtxGlobals
218 #: The class that is used for the ``config`` attribute of this app.
219 #: Defaults to :class:`~flask.Config`.
220 #:
221 #: Example use cases for a custom class:
222 #:
223 #: 1. Default values for certain config options.
224 #: 2. Access to config values through attributes in addition to keys.
225 #:
226 #: .. versionadded:: 0.11
227 config_class = Config
229 #: The testing flag. Set this to ``True`` to enable the test mode of
230 #: Flask extensions (and in the future probably also Flask itself).
231 #: For example this might activate test helpers that have an
232 #: additional runtime cost which should not be enabled by default.
233 #:
234 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
235 #: default it's implicitly enabled.
236 #:
237 #: This attribute can also be configured from the config with the
238 #: ``TESTING`` configuration key. Defaults to ``False``.
239 testing = ConfigAttribute("TESTING")
241 #: If a secret key is set, cryptographic components can use this to
242 #: sign cookies and other things. Set this to a complex random value
243 #: when you want to use the secure cookie for instance.
244 #:
245 #: This attribute can also be configured from the config with the
246 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.
247 secret_key = ConfigAttribute("SECRET_KEY")
249 #: The secure cookie uses this for the name of the session cookie.
250 #:
251 #: This attribute can also be configured from the config with the
252 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``
253 session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")
255 #: A :class:`~datetime.timedelta` which is used to set the expiration
256 #: date of a permanent session. The default is 31 days which makes a
257 #: permanent session survive for roughly one month.
258 #:
259 #: This attribute can also be configured from the config with the
260 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
261 #: ``timedelta(days=31)``
262 permanent_session_lifetime = ConfigAttribute(
263 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
264 )
266 #: A :class:`~datetime.timedelta` or number of seconds which is used
267 #: as the default ``max_age`` for :func:`send_file`. The default is
268 #: ``None``, which tells the browser to use conditional requests
269 #: instead of a timed cache.
270 #:
271 #: Configured with the :data:`SEND_FILE_MAX_AGE_DEFAULT`
272 #: configuration key.
273 #:
274 #: .. versionchanged:: 2.0
275 #: Defaults to ``None`` instead of 12 hours.
276 send_file_max_age_default = ConfigAttribute(
277 "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta
278 )
280 #: Enable this if you want to use the X-Sendfile feature. Keep in
281 #: mind that the server has to support this. This only affects files
282 #: sent with the :func:`send_file` method.
283 #:
284 #: .. versionadded:: 0.2
285 #:
286 #: This attribute can also be configured from the config with the
287 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.
288 use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")
290 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.
291 #:
292 #: .. versionadded:: 0.10
293 json_encoder = json.JSONEncoder
295 #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.
296 #:
297 #: .. versionadded:: 0.10
298 json_decoder = json.JSONDecoder
300 #: Options that are passed to the Jinja environment in
301 #: :meth:`create_jinja_environment`. Changing these options after
302 #: the environment is created (accessing :attr:`jinja_env`) will
303 #: have no effect.
304 #:
305 #: .. versionchanged:: 1.1.0
306 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
307 #: easier configuration.
308 #:
309 jinja_options: dict = {}
311 #: Default configuration parameters.
312 default_config = ImmutableDict(
313 {
314 "ENV": None,
315 "DEBUG": None,
316 "TESTING": False,
317 "PROPAGATE_EXCEPTIONS": None,
318 "PRESERVE_CONTEXT_ON_EXCEPTION": None,
319 "SECRET_KEY": None,
320 "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
321 "USE_X_SENDFILE": False,
322 "SERVER_NAME": None,
323 "APPLICATION_ROOT": "/",
324 "SESSION_COOKIE_NAME": "session",
325 "SESSION_COOKIE_DOMAIN": None,
326 "SESSION_COOKIE_PATH": None,
327 "SESSION_COOKIE_HTTPONLY": True,
328 "SESSION_COOKIE_SECURE": False,
329 "SESSION_COOKIE_SAMESITE": None,
330 "SESSION_REFRESH_EACH_REQUEST": True,
331 "MAX_CONTENT_LENGTH": None,
332 "SEND_FILE_MAX_AGE_DEFAULT": None,
333 "TRAP_BAD_REQUEST_ERRORS": None,
334 "TRAP_HTTP_EXCEPTIONS": False,
335 "EXPLAIN_TEMPLATE_LOADING": False,
336 "PREFERRED_URL_SCHEME": "http",
337 "JSON_AS_ASCII": True,
338 "JSON_SORT_KEYS": True,
339 "JSONIFY_PRETTYPRINT_REGULAR": False,
340 "JSONIFY_MIMETYPE": "application/json",
341 "TEMPLATES_AUTO_RELOAD": None,
342 "MAX_COOKIE_SIZE": 4093,
343 }
344 )
346 #: The rule object to use for URL rules created. This is used by
347 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
348 #:
349 #: .. versionadded:: 0.7
350 url_rule_class = Rule
352 #: The map object to use for storing the URL rules and routing
353 #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
354 #:
355 #: .. versionadded:: 1.1.0
356 url_map_class = Map
358 #: The :meth:`test_client` method creates an instance of this test
359 #: client class. Defaults to :class:`~flask.testing.FlaskClient`.
360 #:
361 #: .. versionadded:: 0.7
362 test_client_class: t.Optional[t.Type["FlaskClient"]] = None
364 #: The :class:`~click.testing.CliRunner` subclass, by default
365 #: :class:`~flask.testing.FlaskCliRunner` that is used by
366 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
367 #: Flask app object as the first argument.
368 #:
369 #: .. versionadded:: 1.0
370 test_cli_runner_class: t.Optional[t.Type["FlaskCliRunner"]] = None
372 #: the session interface to use. By default an instance of
373 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
374 #:
375 #: .. versionadded:: 0.8
376 session_interface: SessionInterface = SecureCookieSessionInterface()
378 def __init__(
379 self,
380 import_name: str,
381 static_url_path: t.Optional[str] = None,
382 static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",
383 static_host: t.Optional[str] = None,
384 host_matching: bool = False,
385 subdomain_matching: bool = False,
386 template_folder: t.Optional[str] = "templates",
387 instance_path: t.Optional[str] = None,
388 instance_relative_config: bool = False,
389 root_path: t.Optional[str] = None,
390 ):
391 super().__init__(
392 import_name=import_name,
393 static_folder=static_folder,
394 static_url_path=static_url_path,
395 template_folder=template_folder,
396 root_path=root_path,
397 )
399 if instance_path is None:
400 instance_path = self.auto_find_instance_path()
401 elif not os.path.isabs(instance_path):
402 raise ValueError(
403 "If an instance path is provided it must be absolute."
404 " A relative path was given instead."
405 )
407 #: Holds the path to the instance folder.
408 #:
409 #: .. versionadded:: 0.8
410 self.instance_path = instance_path
412 #: The configuration dictionary as :class:`Config`. This behaves
413 #: exactly like a regular dictionary but supports additional methods
414 #: to load a config from files.
415 self.config = self.make_config(instance_relative_config)
417 #: A list of functions that are called when :meth:`url_for` raises a
418 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here
419 #: is called with `error`, `endpoint` and `values`. If a function
420 #: returns ``None`` or raises a :exc:`BuildError` the next function is
421 #: tried.
422 #:
423 #: .. versionadded:: 0.9
424 self.url_build_error_handlers: t.List[
425 t.Callable[[Exception, str, dict], str]
426 ] = []
428 #: A list of functions that will be called at the beginning of the
429 #: first request to this instance. To register a function, use the
430 #: :meth:`before_first_request` decorator.
431 #:
432 #: .. versionadded:: 0.8
433 self.before_first_request_funcs: t.List[ft.BeforeFirstRequestCallable] = []
435 #: A list of functions that are called when the application context
436 #: is destroyed. Since the application context is also torn down
437 #: if the request ends this is the place to store code that disconnects
438 #: from databases.
439 #:
440 #: .. versionadded:: 0.9
441 self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = []
443 #: A list of shell context processor functions that should be run
444 #: when a shell context is created.
445 #:
446 #: .. versionadded:: 0.11
447 self.shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] = []
449 #: Maps registered blueprint names to blueprint objects. The
450 #: dict retains the order the blueprints were registered in.
451 #: Blueprints can be registered multiple times, this dict does
452 #: not track how often they were attached.
453 #:
454 #: .. versionadded:: 0.7
455 self.blueprints: t.Dict[str, "Blueprint"] = {}
457 #: a place where extensions can store application specific state. For
458 #: example this is where an extension could store database engines and
459 #: similar things.
460 #:
461 #: The key must match the name of the extension module. For example in
462 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
463 #: ``'foo'``.
464 #:
465 #: .. versionadded:: 0.7
466 self.extensions: dict = {}
468 #: The :class:`~werkzeug.routing.Map` for this instance. You can use
469 #: this to change the routing converters after the class was created
470 #: but before any routes are connected. Example::
471 #:
472 #: from werkzeug.routing import BaseConverter
473 #:
474 #: class ListConverter(BaseConverter):
475 #: def to_python(self, value):
476 #: return value.split(',')
477 #: def to_url(self, values):
478 #: return ','.join(super(ListConverter, self).to_url(value)
479 #: for value in values)
480 #:
481 #: app = Flask(__name__)
482 #: app.url_map.converters['list'] = ListConverter
483 self.url_map = self.url_map_class()
485 self.url_map.host_matching = host_matching
486 self.subdomain_matching = subdomain_matching
488 # tracks internally if the application already handled at least one
489 # request.
490 self._got_first_request = False
491 self._before_request_lock = Lock()
493 # Add a static route using the provided static_url_path, static_host,
494 # and static_folder if there is a configured static_folder.
495 # Note we do this without checking if static_folder exists.
496 # For one, it might be created while the server is running (e.g. during
497 # development). Also, Google App Engine stores static files somewhere
498 if self.has_static_folder:
499 assert (
500 bool(static_host) == host_matching
501 ), "Invalid static_host/host_matching combination"
502 # Use a weakref to avoid creating a reference cycle between the app
503 # and the view function (see #3761).
504 self_ref = weakref.ref(self)
505 self.add_url_rule(
506 f"{self.static_url_path}/<path:filename>",
507 endpoint="static",
508 host=static_host,
509 view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950
510 )
512 # Set the name of the Click group in case someone wants to add
513 # the app's commands to another CLI tool.
514 self.cli.name = self.name
516 def _is_setup_finished(self) -> bool:
517 return self.debug and self._got_first_request
519 @locked_cached_property
520 def name(self) -> str: # type: ignore
521 """The name of the application. This is usually the import name
522 with the difference that it's guessed from the run file if the
523 import name is main. This name is used as a display name when
524 Flask needs the name of the application. It can be set and overridden
525 to change the value.
527 .. versionadded:: 0.8
528 """
529 if self.import_name == "__main__":
530 fn = getattr(sys.modules["__main__"], "__file__", None)
531 if fn is None:
532 return "__main__"
533 return os.path.splitext(os.path.basename(fn))[0]
534 return self.import_name
536 @property
537 def propagate_exceptions(self) -> bool:
538 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
539 value in case it's set, otherwise a sensible default is returned.
541 .. versionadded:: 0.7
542 """
543 rv = self.config["PROPAGATE_EXCEPTIONS"]
544 if rv is not None:
545 return rv
546 return self.testing or self.debug
548 @property
549 def preserve_context_on_exception(self) -> bool:
550 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
551 configuration value in case it's set, otherwise a sensible default
552 is returned.
554 .. versionadded:: 0.7
555 """
556 rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]
557 if rv is not None:
558 return rv
559 return self.debug
561 @locked_cached_property
562 def logger(self) -> logging.Logger:
563 """A standard Python :class:`~logging.Logger` for the app, with
564 the same name as :attr:`name`.
566 In debug mode, the logger's :attr:`~logging.Logger.level` will
567 be set to :data:`~logging.DEBUG`.
569 If there are no handlers configured, a default handler will be
570 added. See :doc:`/logging` for more information.
572 .. versionchanged:: 1.1.0
573 The logger takes the same name as :attr:`name` rather than
574 hard-coding ``"flask.app"``.
576 .. versionchanged:: 1.0.0
577 Behavior was simplified. The logger is always named
578 ``"flask.app"``. The level is only set during configuration,
579 it doesn't check ``app.debug`` each time. Only one format is
580 used, not different ones depending on ``app.debug``. No
581 handlers are removed, and a handler is only added if no
582 handlers are already configured.
584 .. versionadded:: 0.3
585 """
586 return create_logger(self)
588 @locked_cached_property
589 def jinja_env(self) -> Environment:
590 """The Jinja environment used to load templates.
592 The environment is created the first time this property is
593 accessed. Changing :attr:`jinja_options` after that will have no
594 effect.
595 """
596 return self.create_jinja_environment()
598 @property
599 def got_first_request(self) -> bool:
600 """This attribute is set to ``True`` if the application started
601 handling the first request.
603 .. versionadded:: 0.8
604 """
605 return self._got_first_request
607 def make_config(self, instance_relative: bool = False) -> Config:
608 """Used to create the config attribute by the Flask constructor.
609 The `instance_relative` parameter is passed in from the constructor
610 of Flask (there named `instance_relative_config`) and indicates if
611 the config should be relative to the instance path or the root path
612 of the application.
614 .. versionadded:: 0.8
615 """
616 root_path = self.root_path
617 if instance_relative:
618 root_path = self.instance_path
619 defaults = dict(self.default_config)
620 defaults["ENV"] = get_env()
621 defaults["DEBUG"] = get_debug_flag()
622 return self.config_class(root_path, defaults)
624 def auto_find_instance_path(self) -> str:
625 """Tries to locate the instance path if it was not provided to the
626 constructor of the application class. It will basically calculate
627 the path to a folder named ``instance`` next to your main file or
628 the package.
630 .. versionadded:: 0.8
631 """
632 prefix, package_path = find_package(self.import_name)
633 if prefix is None:
634 return os.path.join(package_path, "instance")
635 return os.path.join(prefix, "var", f"{self.name}-instance")
637 def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
638 """Opens a resource from the application's instance folder
639 (:attr:`instance_path`). Otherwise works like
640 :meth:`open_resource`. Instance resources can also be opened for
641 writing.
643 :param resource: the name of the resource. To access resources within
644 subfolders use forward slashes as separator.
645 :param mode: resource file opening mode, default is 'rb'.
646 """
647 return open(os.path.join(self.instance_path, resource), mode)
649 @property
650 def templates_auto_reload(self) -> bool:
651 """Reload templates when they are changed. Used by
652 :meth:`create_jinja_environment`.
654 This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If
655 not set, it will be enabled in debug mode.
657 .. versionadded:: 1.0
658 This property was added but the underlying config and behavior
659 already existed.
660 """
661 rv = self.config["TEMPLATES_AUTO_RELOAD"]
662 return rv if rv is not None else self.debug
664 @templates_auto_reload.setter
665 def templates_auto_reload(self, value: bool) -> None:
666 self.config["TEMPLATES_AUTO_RELOAD"] = value
668 def create_jinja_environment(self) -> Environment:
669 """Create the Jinja environment based on :attr:`jinja_options`
670 and the various Jinja-related methods of the app. Changing
671 :attr:`jinja_options` after this will have no effect. Also adds
672 Flask-related globals and filters to the environment.
674 .. versionchanged:: 0.11
675 ``Environment.auto_reload`` set in accordance with
676 ``TEMPLATES_AUTO_RELOAD`` configuration option.
678 .. versionadded:: 0.5
679 """
680 options = dict(self.jinja_options)
682 if "autoescape" not in options:
683 options["autoescape"] = self.select_jinja_autoescape
685 if "auto_reload" not in options:
686 options["auto_reload"] = self.templates_auto_reload
688 rv = self.jinja_environment(self, **options)
689 rv.globals.update(
690 url_for=url_for,
691 get_flashed_messages=get_flashed_messages,
692 config=self.config,
693 # request, session and g are normally added with the
694 # context processor for efficiency reasons but for imported
695 # templates we also want the proxies in there.
696 request=request,
697 session=session,
698 g=g,
699 )
700 rv.policies["json.dumps_function"] = json.dumps
701 return rv
703 def create_global_jinja_loader(self) -> DispatchingJinjaLoader:
704 """Creates the loader for the Jinja2 environment. Can be used to
705 override just the loader and keeping the rest unchanged. It's
706 discouraged to override this function. Instead one should override
707 the :meth:`jinja_loader` function instead.
709 The global loader dispatches between the loaders of the application
710 and the individual blueprints.
712 .. versionadded:: 0.7
713 """
714 return DispatchingJinjaLoader(self)
716 def select_jinja_autoescape(self, filename: str) -> bool:
717 """Returns ``True`` if autoescaping should be active for the given
718 template name. If no template name is given, returns `True`.
720 .. versionadded:: 0.5
721 """
722 if filename is None:
723 return True
724 return filename.endswith((".html", ".htm", ".xml", ".xhtml"))
726 def update_template_context(self, context: dict) -> None:
727 """Update the template context with some commonly used variables.
728 This injects request, session, config and g into the template
729 context as well as everything template context processors want
730 to inject. Note that the as of Flask 0.6, the original values
731 in the context will not be overridden if a context processor
732 decides to return a value with the same key.
734 :param context: the context as a dictionary that is updated in place
735 to add extra variables.
736 """
737 names: t.Iterable[t.Optional[str]] = (None,)
739 # A template may be rendered outside a request context.
740 if request:
741 names = chain(names, reversed(request.blueprints))
743 # The values passed to render_template take precedence. Keep a
744 # copy to re-apply after all context functions.
745 orig_ctx = context.copy()
747 for name in names:
748 if name in self.template_context_processors:
749 for func in self.template_context_processors[name]:
750 context.update(func())
752 context.update(orig_ctx)
754 def make_shell_context(self) -> dict:
755 """Returns the shell context for an interactive shell for this
756 application. This runs all the registered shell context
757 processors.
759 .. versionadded:: 0.11
760 """
761 rv = {"app": self, "g": g}
762 for processor in self.shell_context_processors:
763 rv.update(processor())
764 return rv
766 #: What environment the app is running in. Flask and extensions may
767 #: enable behaviors based on the environment, such as enabling debug
768 #: mode. This maps to the :data:`ENV` config key. This is set by the
769 #: :envvar:`FLASK_ENV` environment variable and may not behave as
770 #: expected if set in code.
771 #:
772 #: **Do not enable development when deploying in production.**
773 #:
774 #: Default: ``'production'``
775 env = ConfigAttribute("ENV")
777 @property
778 def debug(self) -> bool:
779 """Whether debug mode is enabled. When using ``flask run`` to start
780 the development server, an interactive debugger will be shown for
781 unhandled exceptions, and the server will be reloaded when code
782 changes. This maps to the :data:`DEBUG` config key. This is
783 enabled when :attr:`env` is ``'development'`` and is overridden
784 by the ``FLASK_DEBUG`` environment variable. It may not behave as
785 expected if set in code.
787 **Do not enable debug mode when deploying in production.**
789 Default: ``True`` if :attr:`env` is ``'development'``, or
790 ``False`` otherwise.
791 """
792 return self.config["DEBUG"]
794 @debug.setter
795 def debug(self, value: bool) -> None:
796 self.config["DEBUG"] = value
797 self.jinja_env.auto_reload = self.templates_auto_reload
799 def run(
800 self,
801 host: t.Optional[str] = None,
802 port: t.Optional[int] = None,
803 debug: t.Optional[bool] = None,
804 load_dotenv: bool = True,
805 **options: t.Any,
806 ) -> None:
807 """Runs the application on a local development server.
809 Do not use ``run()`` in a production setting. It is not intended to
810 meet security and performance requirements for a production server.
811 Instead, see :doc:`/deploying/index` for WSGI server recommendations.
813 If the :attr:`debug` flag is set the server will automatically reload
814 for code changes and show a debugger in case an exception happened.
816 If you want to run the application in debug mode, but disable the
817 code execution on the interactive debugger, you can pass
818 ``use_evalex=False`` as parameter. This will keep the debugger's
819 traceback screen active, but disable code execution.
821 It is not recommended to use this function for development with
822 automatic reloading as this is badly supported. Instead you should
823 be using the :command:`flask` command line script's ``run`` support.
825 .. admonition:: Keep in Mind
827 Flask will suppress any server error with a generic error page
828 unless it is in debug mode. As such to enable just the
829 interactive debugger without the code reloading, you have to
830 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
831 Setting ``use_debugger`` to ``True`` without being in debug mode
832 won't catch any exceptions because there won't be any to
833 catch.
835 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
836 have the server available externally as well. Defaults to
837 ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
838 if present.
839 :param port: the port of the webserver. Defaults to ``5000`` or the
840 port defined in the ``SERVER_NAME`` config variable if present.
841 :param debug: if given, enable or disable debug mode. See
842 :attr:`debug`.
843 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
844 files to set environment variables. Will also change the working
845 directory to the directory containing the first file found.
846 :param options: the options to be forwarded to the underlying Werkzeug
847 server. See :func:`werkzeug.serving.run_simple` for more
848 information.
850 .. versionchanged:: 1.0
851 If installed, python-dotenv will be used to load environment
852 variables from :file:`.env` and :file:`.flaskenv` files.
854 If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`
855 environment variables will override :attr:`env` and
856 :attr:`debug`.
858 Threaded mode is enabled by default.
860 .. versionchanged:: 0.10
861 The default port is now picked from the ``SERVER_NAME``
862 variable.
863 """
864 # Change this into a no-op if the server is invoked from the
865 # command line. Have a look at cli.py for more information.
866 if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
867 from .debughelpers import explain_ignored_app_run
869 explain_ignored_app_run()
870 return
872 if get_load_dotenv(load_dotenv):
873 cli.load_dotenv()
875 # if set, let env vars override previous values
876 if "FLASK_ENV" in os.environ:
877 self.env = get_env()
878 self.debug = get_debug_flag()
879 elif "FLASK_DEBUG" in os.environ:
880 self.debug = get_debug_flag()
882 # debug passed to method overrides all other sources
883 if debug is not None:
884 self.debug = bool(debug)
886 server_name = self.config.get("SERVER_NAME")
887 sn_host = sn_port = None
889 if server_name:
890 sn_host, _, sn_port = server_name.partition(":")
892 if not host:
893 if sn_host:
894 host = sn_host
895 else:
896 host = "127.0.0.1"
898 if port or port == 0:
899 port = int(port)
900 elif sn_port:
901 port = int(sn_port)
902 else:
903 port = 5000
905 options.setdefault("use_reloader", self.debug)
906 options.setdefault("use_debugger", self.debug)
907 options.setdefault("threaded", True)
909 cli.show_server_banner(self.env, self.debug, self.name, False)
911 from werkzeug.serving import run_simple
913 try:
914 run_simple(t.cast(str, host), port, self, **options)
915 finally:
916 # reset the first request information if the development server
917 # reset normally. This makes it possible to restart the server
918 # without reloader and that stuff from an interactive shell.
919 self._got_first_request = False
921 def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> "FlaskClient":
922 """Creates a test client for this application. For information
923 about unit testing head over to :doc:`/testing`.
925 Note that if you are testing for assertions or exceptions in your
926 application code, you must set ``app.testing = True`` in order for the
927 exceptions to propagate to the test client. Otherwise, the exception
928 will be handled by the application (not visible to the test client) and
929 the only indication of an AssertionError or other exception will be a
930 500 status code response to the test client. See the :attr:`testing`
931 attribute. For example::
933 app.testing = True
934 client = app.test_client()
936 The test client can be used in a ``with`` block to defer the closing down
937 of the context until the end of the ``with`` block. This is useful if
938 you want to access the context locals for testing::
940 with app.test_client() as c:
941 rv = c.get('/?vodka=42')
942 assert request.args['vodka'] == '42'
944 Additionally, you may pass optional keyword arguments that will then
945 be passed to the application's :attr:`test_client_class` constructor.
946 For example::
948 from flask.testing import FlaskClient
950 class CustomClient(FlaskClient):
951 def __init__(self, *args, **kwargs):
952 self._authentication = kwargs.pop("authentication")
953 super(CustomClient,self).__init__( *args, **kwargs)
955 app.test_client_class = CustomClient
956 client = app.test_client(authentication='Basic ....')
958 See :class:`~flask.testing.FlaskClient` for more information.
960 .. versionchanged:: 0.4
961 added support for ``with`` block usage for the client.
963 .. versionadded:: 0.7
964 The `use_cookies` parameter was added as well as the ability
965 to override the client to be used by setting the
966 :attr:`test_client_class` attribute.
968 .. versionchanged:: 0.11
969 Added `**kwargs` to support passing additional keyword arguments to
970 the constructor of :attr:`test_client_class`.
971 """
972 cls = self.test_client_class
973 if cls is None:
974 from .testing import FlaskClient as cls # type: ignore
975 return cls( # type: ignore
976 self, self.response_class, use_cookies=use_cookies, **kwargs
977 )
979 def test_cli_runner(self, **kwargs: t.Any) -> "FlaskCliRunner":
980 """Create a CLI runner for testing CLI commands.
981 See :ref:`testing-cli`.
983 Returns an instance of :attr:`test_cli_runner_class`, by default
984 :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
985 passed as the first argument.
987 .. versionadded:: 1.0
988 """
989 cls = self.test_cli_runner_class
991 if cls is None:
992 from .testing import FlaskCliRunner as cls # type: ignore
994 return cls(self, **kwargs) # type: ignore
996 @setupmethod
997 def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
998 """Register a :class:`~flask.Blueprint` on the application. Keyword
999 arguments passed to this method will override the defaults set on the
1000 blueprint.
1002 Calls the blueprint's :meth:`~flask.Blueprint.register` method after
1003 recording the blueprint in the application's :attr:`blueprints`.
1005 :param blueprint: The blueprint to register.
1006 :param url_prefix: Blueprint routes will be prefixed with this.
1007 :param subdomain: Blueprint routes will match on this subdomain.
1008 :param url_defaults: Blueprint routes will use these default values for
1009 view arguments.
1010 :param options: Additional keyword arguments are passed to
1011 :class:`~flask.blueprints.BlueprintSetupState`. They can be
1012 accessed in :meth:`~flask.Blueprint.record` callbacks.
1014 .. versionchanged:: 2.0.1
1015 The ``name`` option can be used to change the (pre-dotted)
1016 name the blueprint is registered with. This allows the same
1017 blueprint to be registered multiple times with unique names
1018 for ``url_for``.
1020 .. versionadded:: 0.7
1021 """
1022 blueprint.register(self, options)
1024 def iter_blueprints(self) -> t.ValuesView["Blueprint"]:
1025 """Iterates over all blueprints by the order they were registered.
1027 .. versionadded:: 0.11
1028 """
1029 return self.blueprints.values()
1031 @setupmethod
1032 def add_url_rule(
1033 self,
1034 rule: str,
1035 endpoint: t.Optional[str] = None,
1036 view_func: t.Optional[ft.ViewCallable] = None,
1037 provide_automatic_options: t.Optional[bool] = None,
1038 **options: t.Any,
1039 ) -> None:
1040 if endpoint is None:
1041 endpoint = _endpoint_from_view_func(view_func) # type: ignore
1042 options["endpoint"] = endpoint
1043 methods = options.pop("methods", None)
1045 # if the methods are not given and the view_func object knows its
1046 # methods we can use that instead. If neither exists, we go with
1047 # a tuple of only ``GET`` as default.
1048 if methods is None:
1049 methods = getattr(view_func, "methods", None) or ("GET",)
1050 if isinstance(methods, str):
1051 raise TypeError(
1052 "Allowed methods must be a list of strings, for"
1053 ' example: @app.route(..., methods=["POST"])'
1054 )
1055 methods = {item.upper() for item in methods}
1057 # Methods that should always be added
1058 required_methods = set(getattr(view_func, "required_methods", ()))
1060 # starting with Flask 0.8 the view_func object can disable and
1061 # force-enable the automatic options handling.
1062 if provide_automatic_options is None:
1063 provide_automatic_options = getattr(
1064 view_func, "provide_automatic_options", None
1065 )
1067 if provide_automatic_options is None:
1068 if "OPTIONS" not in methods:
1069 provide_automatic_options = True
1070 required_methods.add("OPTIONS")
1071 else:
1072 provide_automatic_options = False
1074 # Add the required methods now.
1075 methods |= required_methods
1077 rule = self.url_rule_class(rule, methods=methods, **options)
1078 rule.provide_automatic_options = provide_automatic_options # type: ignore
1080 self.url_map.add(rule)
1081 if view_func is not None:
1082 old_func = self.view_functions.get(endpoint)
1083 if old_func is not None and old_func != view_func:
1084 raise AssertionError(
1085 "View function mapping is overwriting an existing"
1086 f" endpoint function: {endpoint}"
1087 )
1088 self.view_functions[endpoint] = view_func
1090 @setupmethod
1091 def template_filter(
1092 self, name: t.Optional[str] = None
1093 ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]:
1094 """A decorator that is used to register custom template filter.
1095 You can specify a name for the filter, otherwise the function
1096 name will be used. Example::
1098 @app.template_filter()
1099 def reverse(s):
1100 return s[::-1]
1102 :param name: the optional name of the filter, otherwise the
1103 function name will be used.
1104 """
1106 def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:
1107 self.add_template_filter(f, name=name)
1108 return f
1110 return decorator
1112 @setupmethod
1113 def add_template_filter(
1114 self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None
1115 ) -> None:
1116 """Register a custom template filter. Works exactly like the
1117 :meth:`template_filter` decorator.
1119 :param name: the optional name of the filter, otherwise the
1120 function name will be used.
1121 """
1122 self.jinja_env.filters[name or f.__name__] = f
1124 @setupmethod
1125 def template_test(
1126 self, name: t.Optional[str] = None
1127 ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]:
1128 """A decorator that is used to register custom template test.
1129 You can specify a name for the test, otherwise the function
1130 name will be used. Example::
1132 @app.template_test()
1133 def is_prime(n):
1134 if n == 2:
1135 return True
1136 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
1137 if n % i == 0:
1138 return False
1139 return True
1141 .. versionadded:: 0.10
1143 :param name: the optional name of the test, otherwise the
1144 function name will be used.
1145 """
1147 def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:
1148 self.add_template_test(f, name=name)
1149 return f
1151 return decorator
1153 @setupmethod
1154 def add_template_test(
1155 self, f: ft.TemplateTestCallable, name: t.Optional[str] = None
1156 ) -> None:
1157 """Register a custom template test. Works exactly like the
1158 :meth:`template_test` decorator.
1160 .. versionadded:: 0.10
1162 :param name: the optional name of the test, otherwise the
1163 function name will be used.
1164 """
1165 self.jinja_env.tests[name or f.__name__] = f
1167 @setupmethod
1168 def template_global(
1169 self, name: t.Optional[str] = None
1170 ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]:
1171 """A decorator that is used to register a custom template global function.
1172 You can specify a name for the global function, otherwise the function
1173 name will be used. Example::
1175 @app.template_global()
1176 def double(n):
1177 return 2 * n
1179 .. versionadded:: 0.10
1181 :param name: the optional name of the global function, otherwise the
1182 function name will be used.
1183 """
1185 def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:
1186 self.add_template_global(f, name=name)
1187 return f
1189 return decorator
1191 @setupmethod
1192 def add_template_global(
1193 self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None
1194 ) -> None:
1195 """Register a custom template global function. Works exactly like the
1196 :meth:`template_global` decorator.
1198 .. versionadded:: 0.10
1200 :param name: the optional name of the global function, otherwise the
1201 function name will be used.
1202 """
1203 self.jinja_env.globals[name or f.__name__] = f
1205 @setupmethod
1206 def before_first_request(
1207 self, f: ft.BeforeFirstRequestCallable
1208 ) -> ft.BeforeFirstRequestCallable:
1209 """Registers a function to be run before the first request to this
1210 instance of the application.
1212 The function will be called without any arguments and its return
1213 value is ignored.
1215 .. versionadded:: 0.8
1216 """
1217 self.before_first_request_funcs.append(f)
1218 return f
1220 @setupmethod
1221 def teardown_appcontext(self, f: ft.TeardownCallable) -> ft.TeardownCallable:
1222 """Registers a function to be called when the application context
1223 ends. These functions are typically also called when the request
1224 context is popped.
1226 Example::
1228 ctx = app.app_context()
1229 ctx.push()
1230 ...
1231 ctx.pop()
1233 When ``ctx.pop()`` is executed in the above example, the teardown
1234 functions are called just before the app context moves from the
1235 stack of active contexts. This becomes relevant if you are using
1236 such constructs in tests.
1238 Since a request context typically also manages an application
1239 context it would also be called when you pop a request context.
1241 When a teardown function was called because of an unhandled exception
1242 it will be passed an error object. If an :meth:`errorhandler` is
1243 registered, it will handle the exception and the teardown will not
1244 receive it.
1246 The return values of teardown functions are ignored.
1248 .. versionadded:: 0.9
1249 """
1250 self.teardown_appcontext_funcs.append(f)
1251 return f
1253 @setupmethod
1254 def shell_context_processor(self, f: t.Callable) -> t.Callable:
1255 """Registers a shell context processor function.
1257 .. versionadded:: 0.11
1258 """
1259 self.shell_context_processors.append(f)
1260 return f
1262 def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]:
1263 """Return a registered error handler for an exception in this order:
1264 blueprint handler for a specific code, app handler for a specific code,
1265 blueprint handler for an exception class, app handler for an exception
1266 class, or ``None`` if a suitable handler is not found.
1267 """
1268 exc_class, code = self._get_exc_class_and_code(type(e))
1269 names = (*request.blueprints, None)
1271 for c in (code, None) if code is not None else (None,):
1272 for name in names:
1273 handler_map = self.error_handler_spec[name][c]
1275 if not handler_map:
1276 continue
1278 for cls in exc_class.__mro__:
1279 handler = handler_map.get(cls)
1281 if handler is not None:
1282 return handler
1283 return None
1285 def handle_http_exception(
1286 self, e: HTTPException
1287 ) -> t.Union[HTTPException, ft.ResponseReturnValue]:
1288 """Handles an HTTP exception. By default this will invoke the
1289 registered error handlers and fall back to returning the
1290 exception as response.
1292 .. versionchanged:: 1.0.3
1293 ``RoutingException``, used internally for actions such as
1294 slash redirects during routing, is not passed to error
1295 handlers.
1297 .. versionchanged:: 1.0
1298 Exceptions are looked up by code *and* by MRO, so
1299 ``HTTPException`` subclasses can be handled with a catch-all
1300 handler for the base ``HTTPException``.
1302 .. versionadded:: 0.3
1303 """
1304 # Proxy exceptions don't have error codes. We want to always return
1305 # those unchanged as errors
1306 if e.code is None:
1307 return e
1309 # RoutingExceptions are used internally to trigger routing
1310 # actions, such as slash redirects raising RequestRedirect. They
1311 # are not raised or handled in user code.
1312 if isinstance(e, RoutingException):
1313 return e
1315 handler = self._find_error_handler(e)
1316 if handler is None:
1317 return e
1318 return self.ensure_sync(handler)(e)
1320 def trap_http_exception(self, e: Exception) -> bool:
1321 """Checks if an HTTP exception should be trapped or not. By default
1322 this will return ``False`` for all exceptions except for a bad request
1323 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
1324 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
1326 This is called for all HTTP exceptions raised by a view function.
1327 If it returns ``True`` for any exception the error handler for this
1328 exception is not called and it shows up as regular exception in the
1329 traceback. This is helpful for debugging implicitly raised HTTP
1330 exceptions.
1332 .. versionchanged:: 1.0
1333 Bad request errors are not trapped by default in debug mode.
1335 .. versionadded:: 0.8
1336 """
1337 if self.config["TRAP_HTTP_EXCEPTIONS"]:
1338 return True
1340 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
1342 # if unset, trap key errors in debug mode
1343 if (
1344 trap_bad_request is None
1345 and self.debug
1346 and isinstance(e, BadRequestKeyError)
1347 ):
1348 return True
1350 if trap_bad_request:
1351 return isinstance(e, BadRequest)
1353 return False
1355 def handle_user_exception(
1356 self, e: Exception
1357 ) -> t.Union[HTTPException, ft.ResponseReturnValue]:
1358 """This method is called whenever an exception occurs that
1359 should be handled. A special case is :class:`~werkzeug
1360 .exceptions.HTTPException` which is forwarded to the
1361 :meth:`handle_http_exception` method. This function will either
1362 return a response value or reraise the exception with the same
1363 traceback.
1365 .. versionchanged:: 1.0
1366 Key errors raised from request data like ``form`` show the
1367 bad key in debug mode rather than a generic bad request
1368 message.
1370 .. versionadded:: 0.7
1371 """
1372 if isinstance(e, BadRequestKeyError) and (
1373 self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
1374 ):
1375 e.show_exception = True
1377 if isinstance(e, HTTPException) and not self.trap_http_exception(e):
1378 return self.handle_http_exception(e)
1380 handler = self._find_error_handler(e)
1382 if handler is None:
1383 raise
1385 return self.ensure_sync(handler)(e)
1387 def handle_exception(self, e: Exception) -> Response:
1388 """Handle an exception that did not have an error handler
1389 associated with it, or that was raised from an error handler.
1390 This always causes a 500 ``InternalServerError``.
1392 Always sends the :data:`got_request_exception` signal.
1394 If :attr:`propagate_exceptions` is ``True``, such as in debug
1395 mode, the error will be re-raised so that the debugger can
1396 display it. Otherwise, the original exception is logged, and
1397 an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
1399 If an error handler is registered for ``InternalServerError`` or
1400 ``500``, it will be used. For consistency, the handler will
1401 always receive the ``InternalServerError``. The original
1402 unhandled exception is available as ``e.original_exception``.
1404 .. versionchanged:: 1.1.0
1405 Always passes the ``InternalServerError`` instance to the
1406 handler, setting ``original_exception`` to the unhandled
1407 error.
1409 .. versionchanged:: 1.1.0
1410 ``after_request`` functions and other finalization is done
1411 even for the default 500 response when there is no handler.
1413 .. versionadded:: 0.3
1414 """
1415 exc_info = sys.exc_info()
1416 got_request_exception.send(self, exception=e)
1418 if self.propagate_exceptions:
1419 # Re-raise if called with an active exception, otherwise
1420 # raise the passed in exception.
1421 if exc_info[1] is e:
1422 raise
1424 raise e
1426 self.log_exception(exc_info)
1427 server_error: t.Union[InternalServerError, ft.ResponseReturnValue]
1428 server_error = InternalServerError(original_exception=e)
1429 handler = self._find_error_handler(server_error)
1431 if handler is not None:
1432 server_error = self.ensure_sync(handler)(server_error)
1434 return self.finalize_request(server_error, from_error_handler=True)
1436 def log_exception(
1437 self,
1438 exc_info: t.Union[
1439 t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]
1440 ],
1441 ) -> None:
1442 """Logs an exception. This is called by :meth:`handle_exception`
1443 if debugging is disabled and right before the handler is called.
1444 The default implementation logs the exception as error on the
1445 :attr:`logger`.
1447 .. versionadded:: 0.8
1448 """
1449 self.logger.error(
1450 f"Exception on {request.path} [{request.method}]", exc_info=exc_info
1451 )
1453 def raise_routing_exception(self, request: Request) -> "te.NoReturn":
1454 """Intercept routing exceptions and possibly do something else.
1456 In debug mode, intercept a routing redirect and replace it with
1457 an error if the body will be discarded.
1459 With modern Werkzeug this shouldn't occur, since it now uses a
1460 308 status which tells the browser to resend the method and
1461 body.
1463 .. versionchanged:: 2.1
1464 Don't intercept 307 and 308 redirects.
1466 :meta private:
1467 :internal:
1468 """
1469 if (
1470 not self.debug
1471 or not isinstance(request.routing_exception, RequestRedirect)
1472 or request.routing_exception.code in {307, 308}
1473 or request.method in {"GET", "HEAD", "OPTIONS"}
1474 ):
1475 raise request.routing_exception # type: ignore
1477 from .debughelpers import FormDataRoutingRedirect
1479 raise FormDataRoutingRedirect(request)
1481 def dispatch_request(self) -> ft.ResponseReturnValue:
1482 """Does the request dispatching. Matches the URL and returns the
1483 return value of the view or error handler. This does not have to
1484 be a response object. In order to convert the return value to a
1485 proper response object, call :func:`make_response`.
1487 .. versionchanged:: 0.7
1488 This no longer does the exception handling, this code was
1489 moved to the new :meth:`full_dispatch_request`.
1490 """
1491 req = _request_ctx_stack.top.request
1492 if req.routing_exception is not None:
1493 self.raise_routing_exception(req)
1494 rule = req.url_rule
1495 # if we provide automatic options for this URL and the
1496 # request came with the OPTIONS method, reply automatically
1497 if (
1498 getattr(rule, "provide_automatic_options", False)
1499 and req.method == "OPTIONS"
1500 ):
1501 return self.make_default_options_response()
1502 # otherwise dispatch to the handler for that endpoint
1503 return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
1505 def full_dispatch_request(self) -> Response:
1506 """Dispatches the request and on top of that performs request
1507 pre and postprocessing as well as HTTP exception catching and
1508 error handling.
1510 .. versionadded:: 0.7
1511 """
1512 self.try_trigger_before_first_request_functions()
1513 try:
1514 request_started.send(self)
1515 rv = self.preprocess_request()
1516 if rv is None:
1517 rv = self.dispatch_request()
1518 except Exception as e:
1519 rv = self.handle_user_exception(e)
1520 return self.finalize_request(rv)
1522 def finalize_request(
1523 self,
1524 rv: t.Union[ft.ResponseReturnValue, HTTPException],
1525 from_error_handler: bool = False,
1526 ) -> Response:
1527 """Given the return value from a view function this finalizes
1528 the request by converting it into a response and invoking the
1529 postprocessing functions. This is invoked for both normal
1530 request dispatching as well as error handlers.
1532 Because this means that it might be called as a result of a
1533 failure a special safe mode is available which can be enabled
1534 with the `from_error_handler` flag. If enabled, failures in
1535 response processing will be logged and otherwise ignored.
1537 :internal:
1538 """
1539 response = self.make_response(rv)
1540 try:
1541 response = self.process_response(response)
1542 request_finished.send(self, response=response)
1543 except Exception:
1544 if not from_error_handler:
1545 raise
1546 self.logger.exception(
1547 "Request finalizing failed with an error while handling an error"
1548 )
1549 return response
1551 def try_trigger_before_first_request_functions(self) -> None:
1552 """Called before each request and will ensure that it triggers
1553 the :attr:`before_first_request_funcs` and only exactly once per
1554 application instance (which means process usually).
1556 :internal:
1557 """
1558 if self._got_first_request:
1559 return
1560 with self._before_request_lock:
1561 if self._got_first_request:
1562 return
1563 for func in self.before_first_request_funcs:
1564 self.ensure_sync(func)()
1565 self._got_first_request = True
1567 def make_default_options_response(self) -> Response:
1568 """This method is called to create the default ``OPTIONS`` response.
1569 This can be changed through subclassing to change the default
1570 behavior of ``OPTIONS`` responses.
1572 .. versionadded:: 0.7
1573 """
1574 adapter = _request_ctx_stack.top.url_adapter
1575 methods = adapter.allowed_methods()
1576 rv = self.response_class()
1577 rv.allow.update(methods)
1578 return rv
1580 def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:
1581 """This is called to figure out if an error should be ignored
1582 or not as far as the teardown system is concerned. If this
1583 function returns ``True`` then the teardown handlers will not be
1584 passed the error.
1586 .. versionadded:: 0.10
1587 """
1588 return False
1590 def ensure_sync(self, func: t.Callable) -> t.Callable:
1591 """Ensure that the function is synchronous for WSGI workers.
1592 Plain ``def`` functions are returned as-is. ``async def``
1593 functions are wrapped to run and wait for the response.
1595 Override this method to change how the app runs async views.
1597 .. versionadded:: 2.0
1598 """
1599 if iscoroutinefunction(func):
1600 return self.async_to_sync(func)
1602 return func
1604 def async_to_sync(
1605 self, func: t.Callable[..., t.Coroutine]
1606 ) -> t.Callable[..., t.Any]:
1607 """Return a sync function that will run the coroutine function.
1609 .. code-block:: python
1611 result = app.async_to_sync(func)(*args, **kwargs)
1613 Override this method to change how the app converts async code
1614 to be synchronously callable.
1616 .. versionadded:: 2.0
1617 """
1618 try:
1619 from asgiref.sync import async_to_sync as asgiref_async_to_sync
1620 except ImportError:
1621 raise RuntimeError(
1622 "Install Flask with the 'async' extra in order to use async views."
1623 ) from None
1625 return asgiref_async_to_sync(func)
1627 def make_response(self, rv: ft.ResponseReturnValue) -> Response:
1628 """Convert the return value from a view function to an instance of
1629 :attr:`response_class`.
1631 :param rv: the return value from the view function. The view function
1632 must return a response. Returning ``None``, or the view ending
1633 without returning, is not allowed. The following types are allowed
1634 for ``view_rv``:
1636 ``str``
1637 A response object is created with the string encoded to UTF-8
1638 as the body.
1640 ``bytes``
1641 A response object is created with the bytes as the body.
1643 ``dict``
1644 A dictionary that will be jsonify'd before being returned.
1646 ``tuple``
1647 Either ``(body, status, headers)``, ``(body, status)``, or
1648 ``(body, headers)``, where ``body`` is any of the other types
1649 allowed here, ``status`` is a string or an integer, and
1650 ``headers`` is a dictionary or a list of ``(key, value)``
1651 tuples. If ``body`` is a :attr:`response_class` instance,
1652 ``status`` overwrites the exiting value and ``headers`` are
1653 extended.
1655 :attr:`response_class`
1656 The object is returned unchanged.
1658 other :class:`~werkzeug.wrappers.Response` class
1659 The object is coerced to :attr:`response_class`.
1661 :func:`callable`
1662 The function is called as a WSGI application. The result is
1663 used to create a response object.
1665 .. versionchanged:: 0.9
1666 Previously a tuple was interpreted as the arguments for the
1667 response object.
1668 """
1670 status = headers = None
1672 # unpack tuple returns
1673 if isinstance(rv, tuple):
1674 len_rv = len(rv)
1676 # a 3-tuple is unpacked directly
1677 if len_rv == 3:
1678 rv, status, headers = rv # type: ignore[misc]
1679 # decide if a 2-tuple has status or headers
1680 elif len_rv == 2:
1681 if isinstance(rv[1], (Headers, dict, tuple, list)):
1682 rv, headers = rv
1683 else:
1684 rv, status = rv # type: ignore[assignment,misc]
1685 # other sized tuples are not allowed
1686 else:
1687 raise TypeError(
1688 "The view function did not return a valid response tuple."
1689 " The tuple must have the form (body, status, headers),"
1690 " (body, status), or (body, headers)."
1691 )
1693 # the body must not be None
1694 if rv is None:
1695 raise TypeError(
1696 f"The view function for {request.endpoint!r} did not"
1697 " return a valid response. The function either returned"
1698 " None or ended without a return statement."
1699 )
1701 # make sure the body is an instance of the response class
1702 if not isinstance(rv, self.response_class):
1703 if isinstance(rv, (str, bytes, bytearray)):
1704 # let the response class set the status and headers instead of
1705 # waiting to do it manually, so that the class can handle any
1706 # special logic
1707 rv = self.response_class(
1708 rv,
1709 status=status,
1710 headers=headers, # type: ignore[arg-type]
1711 )
1712 status = headers = None
1713 elif isinstance(rv, dict):
1714 rv = jsonify(rv)
1715 elif isinstance(rv, BaseResponse) or callable(rv):
1716 # evaluate a WSGI callable, or coerce a different response
1717 # class to the correct type
1718 try:
1719 rv = self.response_class.force_type(
1720 rv, request.environ # type: ignore[arg-type]
1721 )
1722 except TypeError as e:
1723 raise TypeError(
1724 f"{e}\nThe view function did not return a valid"
1725 " response. The return type must be a string,"
1726 " dict, tuple, Response instance, or WSGI"
1727 f" callable, but it was a {type(rv).__name__}."
1728 ).with_traceback(sys.exc_info()[2]) from None
1729 else:
1730 raise TypeError(
1731 "The view function did not return a valid"
1732 " response. The return type must be a string,"
1733 " dict, tuple, Response instance, or WSGI"
1734 f" callable, but it was a {type(rv).__name__}."
1735 )
1737 rv = t.cast(Response, rv)
1738 # prefer the status if it was provided
1739 if status is not None:
1740 if isinstance(status, (str, bytes, bytearray)):
1741 rv.status = status
1742 else:
1743 rv.status_code = status
1745 # extend existing headers with provided headers
1746 if headers:
1747 rv.headers.update(headers) # type: ignore[arg-type]
1749 return rv
1751 def create_url_adapter(
1752 self, request: t.Optional[Request]
1753 ) -> t.Optional[MapAdapter]:
1754 """Creates a URL adapter for the given request. The URL adapter
1755 is created at a point where the request context is not yet set
1756 up so the request is passed explicitly.
1758 .. versionadded:: 0.6
1760 .. versionchanged:: 0.9
1761 This can now also be called without a request object when the
1762 URL adapter is created for the application context.
1764 .. versionchanged:: 1.0
1765 :data:`SERVER_NAME` no longer implicitly enables subdomain
1766 matching. Use :attr:`subdomain_matching` instead.
1767 """
1768 if request is not None:
1769 # If subdomain matching is disabled (the default), use the
1770 # default subdomain in all cases. This should be the default
1771 # in Werkzeug but it currently does not have that feature.
1772 if not self.subdomain_matching:
1773 subdomain = self.url_map.default_subdomain or None
1774 else:
1775 subdomain = None
1777 return self.url_map.bind_to_environ(
1778 request.environ,
1779 server_name=self.config["SERVER_NAME"],
1780 subdomain=subdomain,
1781 )
1782 # We need at the very least the server name to be set for this
1783 # to work.
1784 if self.config["SERVER_NAME"] is not None:
1785 return self.url_map.bind(
1786 self.config["SERVER_NAME"],
1787 script_name=self.config["APPLICATION_ROOT"],
1788 url_scheme=self.config["PREFERRED_URL_SCHEME"],
1789 )
1791 return None
1793 def inject_url_defaults(self, endpoint: str, values: dict) -> None:
1794 """Injects the URL defaults for the given endpoint directly into
1795 the values dictionary passed. This is used internally and
1796 automatically called on URL building.
1798 .. versionadded:: 0.7
1799 """
1800 names: t.Iterable[t.Optional[str]] = (None,)
1802 # url_for may be called outside a request context, parse the
1803 # passed endpoint instead of using request.blueprints.
1804 if "." in endpoint:
1805 names = chain(
1806 names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))
1807 )
1809 for name in names:
1810 if name in self.url_default_functions:
1811 for func in self.url_default_functions[name]:
1812 func(endpoint, values)
1814 def handle_url_build_error(
1815 self, error: Exception, endpoint: str, values: dict
1816 ) -> str:
1817 """Handle :class:`~werkzeug.routing.BuildError` on
1818 :meth:`url_for`.
1819 """
1820 for handler in self.url_build_error_handlers:
1821 try:
1822 rv = handler(error, endpoint, values)
1823 except BuildError as e:
1824 # make error available outside except block
1825 error = e
1826 else:
1827 if rv is not None:
1828 return rv
1830 # Re-raise if called with an active exception, otherwise raise
1831 # the passed in exception.
1832 if error is sys.exc_info()[1]:
1833 raise
1835 raise error
1837 def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]:
1838 """Called before the request is dispatched. Calls
1839 :attr:`url_value_preprocessors` registered with the app and the
1840 current blueprint (if any). Then calls :attr:`before_request_funcs`
1841 registered with the app and the blueprint.
1843 If any :meth:`before_request` handler returns a non-None value, the
1844 value is handled as if it was the return value from the view, and
1845 further request handling is stopped.
1846 """
1847 names = (None, *reversed(request.blueprints))
1849 for name in names:
1850 if name in self.url_value_preprocessors:
1851 for url_func in self.url_value_preprocessors[name]:
1852 url_func(request.endpoint, request.view_args)
1854 for name in names:
1855 if name in self.before_request_funcs:
1856 for before_func in self.before_request_funcs[name]:
1857 rv = self.ensure_sync(before_func)()
1859 if rv is not None:
1860 return rv
1862 return None
1864 def process_response(self, response: Response) -> Response:
1865 """Can be overridden in order to modify the response object
1866 before it's sent to the WSGI server. By default this will
1867 call all the :meth:`after_request` decorated functions.
1869 .. versionchanged:: 0.5
1870 As of Flask 0.5 the functions registered for after request
1871 execution are called in reverse order of registration.
1873 :param response: a :attr:`response_class` object.
1874 :return: a new response object or the same, has to be an
1875 instance of :attr:`response_class`.
1876 """
1877 ctx = _request_ctx_stack.top
1879 for func in ctx._after_request_functions:
1880 response = self.ensure_sync(func)(response)
1882 for name in chain(request.blueprints, (None,)):
1883 if name in self.after_request_funcs:
1884 for func in reversed(self.after_request_funcs[name]):
1885 response = self.ensure_sync(func)(response)
1887 if not self.session_interface.is_null_session(ctx.session):
1888 self.session_interface.save_session(self, ctx.session, response)
1890 return response
1892 def do_teardown_request(
1893 self, exc: t.Optional[BaseException] = _sentinel # type: ignore
1894 ) -> None:
1895 """Called after the request is dispatched and the response is
1896 returned, right before the request context is popped.
1898 This calls all functions decorated with
1899 :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
1900 if a blueprint handled the request. Finally, the
1901 :data:`request_tearing_down` signal is sent.
1903 This is called by
1904 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
1905 which may be delayed during testing to maintain access to
1906 resources.
1908 :param exc: An unhandled exception raised while dispatching the
1909 request. Detected from the current exception information if
1910 not passed. Passed to each teardown function.
1912 .. versionchanged:: 0.9
1913 Added the ``exc`` argument.
1914 """
1915 if exc is _sentinel:
1916 exc = sys.exc_info()[1]
1918 for name in chain(request.blueprints, (None,)):
1919 if name in self.teardown_request_funcs:
1920 for func in reversed(self.teardown_request_funcs[name]):
1921 self.ensure_sync(func)(exc)
1923 request_tearing_down.send(self, exc=exc)
1925 def do_teardown_appcontext(
1926 self, exc: t.Optional[BaseException] = _sentinel # type: ignore
1927 ) -> None:
1928 """Called right before the application context is popped.
1930 When handling a request, the application context is popped
1931 after the request context. See :meth:`do_teardown_request`.
1933 This calls all functions decorated with
1934 :meth:`teardown_appcontext`. Then the
1935 :data:`appcontext_tearing_down` signal is sent.
1937 This is called by
1938 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
1940 .. versionadded:: 0.9
1941 """
1942 if exc is _sentinel:
1943 exc = sys.exc_info()[1]
1945 for func in reversed(self.teardown_appcontext_funcs):
1946 self.ensure_sync(func)(exc)
1948 appcontext_tearing_down.send(self, exc=exc)
1950 def app_context(self) -> AppContext:
1951 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
1952 block to push the context, which will make :data:`current_app`
1953 point at this application.
1955 An application context is automatically pushed by
1956 :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
1957 when handling a request, and when running a CLI command. Use
1958 this to manually create a context outside of these situations.
1960 ::
1962 with app.app_context():
1963 init_db()
1965 See :doc:`/appcontext`.
1967 .. versionadded:: 0.9
1968 """
1969 return AppContext(self)
1971 def request_context(self, environ: dict) -> RequestContext:
1972 """Create a :class:`~flask.ctx.RequestContext` representing a
1973 WSGI environment. Use a ``with`` block to push the context,
1974 which will make :data:`request` point at this request.
1976 See :doc:`/reqcontext`.
1978 Typically you should not call this from your own code. A request
1979 context is automatically pushed by the :meth:`wsgi_app` when
1980 handling a request. Use :meth:`test_request_context` to create
1981 an environment and context instead of this method.
1983 :param environ: a WSGI environment
1984 """
1985 return RequestContext(self, environ)
1987 def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:
1988 """Create a :class:`~flask.ctx.RequestContext` for a WSGI
1989 environment created from the given values. This is mostly useful
1990 during testing, where you may want to run a function that uses
1991 request data without dispatching a full request.
1993 See :doc:`/reqcontext`.
1995 Use a ``with`` block to push the context, which will make
1996 :data:`request` point at the request for the created
1997 environment. ::
1999 with test_request_context(...):
2000 generate_report()
2002 When using the shell, it may be easier to push and pop the
2003 context manually to avoid indentation. ::
2005 ctx = app.test_request_context(...)
2006 ctx.push()
2007 ...
2008 ctx.pop()
2010 Takes the same arguments as Werkzeug's
2011 :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
2012 the application. See the linked Werkzeug docs for most of the
2013 available arguments. Flask-specific behavior is listed here.
2015 :param path: URL path being requested.
2016 :param base_url: Base URL where the app is being served, which
2017 ``path`` is relative to. If not given, built from
2018 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
2019 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
2020 :param subdomain: Subdomain name to append to
2021 :data:`SERVER_NAME`.
2022 :param url_scheme: Scheme to use instead of
2023 :data:`PREFERRED_URL_SCHEME`.
2024 :param data: The request body, either as a string or a dict of
2025 form keys and values.
2026 :param json: If given, this is serialized as JSON and passed as
2027 ``data``. Also defaults ``content_type`` to
2028 ``application/json``.
2029 :param args: other positional arguments passed to
2030 :class:`~werkzeug.test.EnvironBuilder`.
2031 :param kwargs: other keyword arguments passed to
2032 :class:`~werkzeug.test.EnvironBuilder`.
2033 """
2034 from .testing import EnvironBuilder
2036 builder = EnvironBuilder(self, *args, **kwargs)
2038 try:
2039 return self.request_context(builder.get_environ())
2040 finally:
2041 builder.close()
2043 def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:
2044 """The actual WSGI application. This is not implemented in
2045 :meth:`__call__` so that middlewares can be applied without
2046 losing a reference to the app object. Instead of doing this::
2048 app = MyMiddleware(app)
2050 It's a better idea to do this instead::
2052 app.wsgi_app = MyMiddleware(app.wsgi_app)
2054 Then you still have the original application object around and
2055 can continue to call methods on it.
2057 .. versionchanged:: 0.7
2058 Teardown events for the request and app contexts are called
2059 even if an unhandled error occurs. Other events may not be
2060 called depending on when an error occurs during dispatch.
2061 See :ref:`callbacks-and-errors`.
2063 :param environ: A WSGI environment.
2064 :param start_response: A callable accepting a status code,
2065 a list of headers, and an optional exception context to
2066 start the response.
2067 """
2068 ctx = self.request_context(environ)
2069 error: t.Optional[BaseException] = None
2070 try:
2071 try:
2072 ctx.push()
2073 response = self.full_dispatch_request()
2074 except Exception as e:
2075 error = e
2076 response = self.handle_exception(e)
2077 except: # noqa: B001
2078 error = sys.exc_info()[1]
2079 raise
2080 return response(environ, start_response)
2081 finally:
2082 if self.should_ignore_error(error):
2083 error = None
2084 ctx.auto_pop(error)
2086 def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
2087 """The WSGI server calls the Flask application object as the
2088 WSGI application. This calls :meth:`wsgi_app`, which can be
2089 wrapped to apply middleware.
2090 """
2091 return self.wsgi_app(environ, start_response)