"Fossies" - the Fresh Open Source Software Archive

Member "flask-1.1.2/src/flask/app.py" (3 Apr 2020, 98059 Bytes) of package /linux/www/flask-1.1.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "app.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.1.1_vs_1.1.2.

    1 # -*- coding: utf-8 -*-
    2 """
    3     flask.app
    4     ~~~~~~~~~
    5 
    6     This module implements the central WSGI application object.
    7 
    8     :copyright: 2010 Pallets
    9     :license: BSD-3-Clause
   10 """
   11 import os
   12 import sys
   13 import warnings
   14 from datetime import timedelta
   15 from functools import update_wrapper
   16 from itertools import chain
   17 from threading import Lock
   18 
   19 from werkzeug.datastructures import Headers
   20 from werkzeug.datastructures import ImmutableDict
   21 from werkzeug.exceptions import BadRequest
   22 from werkzeug.exceptions import BadRequestKeyError
   23 from werkzeug.exceptions import default_exceptions
   24 from werkzeug.exceptions import HTTPException
   25 from werkzeug.exceptions import InternalServerError
   26 from werkzeug.exceptions import MethodNotAllowed
   27 from werkzeug.routing import BuildError
   28 from werkzeug.routing import Map
   29 from werkzeug.routing import RequestRedirect
   30 from werkzeug.routing import RoutingException
   31 from werkzeug.routing import Rule
   32 from werkzeug.wrappers import BaseResponse
   33 
   34 from . import cli
   35 from . import json
   36 from ._compat import integer_types
   37 from ._compat import reraise
   38 from ._compat import string_types
   39 from ._compat import text_type
   40 from .config import Config
   41 from .config import ConfigAttribute
   42 from .ctx import _AppCtxGlobals
   43 from .ctx import AppContext
   44 from .ctx import RequestContext
   45 from .globals import _request_ctx_stack
   46 from .globals import g
   47 from .globals import request
   48 from .globals import session
   49 from .helpers import _endpoint_from_view_func
   50 from .helpers import _PackageBoundObject
   51 from .helpers import find_package
   52 from .helpers import get_debug_flag
   53 from .helpers import get_env
   54 from .helpers import get_flashed_messages
   55 from .helpers import get_load_dotenv
   56 from .helpers import locked_cached_property
   57 from .helpers import url_for
   58 from .json import jsonify
   59 from .logging import create_logger
   60 from .sessions import SecureCookieSessionInterface
   61 from .signals import appcontext_tearing_down
   62 from .signals import got_request_exception
   63 from .signals import request_finished
   64 from .signals import request_started
   65 from .signals import request_tearing_down
   66 from .templating import _default_template_ctx_processor
   67 from .templating import DispatchingJinjaLoader
   68 from .templating import Environment
   69 from .wrappers import Request
   70 from .wrappers import Response
   71 
   72 # a singleton sentinel value for parameter defaults
   73 _sentinel = object()
   74 
   75 
   76 def _make_timedelta(value):
   77     if not isinstance(value, timedelta):
   78         return timedelta(seconds=value)
   79     return value
   80 
   81 
   82 def setupmethod(f):
   83     """Wraps a method so that it performs a check in debug mode if the
   84     first request was already handled.
   85     """
   86 
   87     def wrapper_func(self, *args, **kwargs):
   88         if self.debug and self._got_first_request:
   89             raise AssertionError(
   90                 "A setup function was called after the "
   91                 "first request was handled.  This usually indicates a bug "
   92                 "in the application where a module was not imported "
   93                 "and decorators or other functionality was called too late.\n"
   94                 "To fix this make sure to import all your view modules, "
   95                 "database models and everything related at a central place "
   96                 "before the application starts serving requests."
   97             )
   98         return f(self, *args, **kwargs)
   99 
  100     return update_wrapper(wrapper_func, f)
  101 
  102 
  103 class Flask(_PackageBoundObject):
  104     """The flask object implements a WSGI application and acts as the central
  105     object.  It is passed the name of the module or package of the
  106     application.  Once it is created it will act as a central registry for
  107     the view functions, the URL rules, template configuration and much more.
  108 
  109     The name of the package is used to resolve resources from inside the
  110     package or the folder the module is contained in depending on if the
  111     package parameter resolves to an actual python package (a folder with
  112     an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
  113 
  114     For more information about resource loading, see :func:`open_resource`.
  115 
  116     Usually you create a :class:`Flask` instance in your main module or
  117     in the :file:`__init__.py` file of your package like this::
  118 
  119         from flask import Flask
  120         app = Flask(__name__)
  121 
  122     .. admonition:: About the First Parameter
  123 
  124         The idea of the first parameter is to give Flask an idea of what
  125         belongs to your application.  This name is used to find resources
  126         on the filesystem, can be used by extensions to improve debugging
  127         information and a lot more.
  128 
  129         So it's important what you provide there.  If you are using a single
  130         module, `__name__` is always the correct value.  If you however are
  131         using a package, it's usually recommended to hardcode the name of
  132         your package there.
  133 
  134         For example if your application is defined in :file:`yourapplication/app.py`
  135         you should create it with one of the two versions below::
  136 
  137             app = Flask('yourapplication')
  138             app = Flask(__name__.split('.')[0])
  139 
  140         Why is that?  The application will work even with `__name__`, thanks
  141         to how resources are looked up.  However it will make debugging more
  142         painful.  Certain extensions can make assumptions based on the
  143         import name of your application.  For example the Flask-SQLAlchemy
  144         extension will look for the code in your application that triggered
  145         an SQL query in debug mode.  If the import name is not properly set
  146         up, that debugging information is lost.  (For example it would only
  147         pick up SQL queries in `yourapplication.app` and not
  148         `yourapplication.views.frontend`)
  149 
  150     .. versionadded:: 0.7
  151        The `static_url_path`, `static_folder`, and `template_folder`
  152        parameters were added.
  153 
  154     .. versionadded:: 0.8
  155        The `instance_path` and `instance_relative_config` parameters were
  156        added.
  157 
  158     .. versionadded:: 0.11
  159        The `root_path` parameter was added.
  160 
  161     .. versionadded:: 1.0
  162        The ``host_matching`` and ``static_host`` parameters were added.
  163 
  164     .. versionadded:: 1.0
  165        The ``subdomain_matching`` parameter was added. Subdomain
  166        matching needs to be enabled manually now. Setting
  167        :data:`SERVER_NAME` does not implicitly enable it.
  168 
  169     :param import_name: the name of the application package
  170     :param static_url_path: can be used to specify a different path for the
  171                             static files on the web.  Defaults to the name
  172                             of the `static_folder` folder.
  173     :param static_folder: The folder with static files that is served at
  174         ``static_url_path``. Relative to the application ``root_path``
  175         or an absolute path. Defaults to ``'static'``.
  176     :param static_host: the host to use when adding the static route.
  177         Defaults to None. Required when using ``host_matching=True``
  178         with a ``static_folder`` configured.
  179     :param host_matching: set ``url_map.host_matching`` attribute.
  180         Defaults to False.
  181     :param subdomain_matching: consider the subdomain relative to
  182         :data:`SERVER_NAME` when matching routes. Defaults to False.
  183     :param template_folder: the folder that contains the templates that should
  184                             be used by the application.  Defaults to
  185                             ``'templates'`` folder in the root path of the
  186                             application.
  187     :param instance_path: An alternative instance path for the application.
  188                           By default the folder ``'instance'`` next to the
  189                           package or module is assumed to be the instance
  190                           path.
  191     :param instance_relative_config: if set to ``True`` relative filenames
  192                                      for loading the config are assumed to
  193                                      be relative to the instance path instead
  194                                      of the application root.
  195     :param root_path: Flask by default will automatically calculate the path
  196                       to the root of the application.  In certain situations
  197                       this cannot be achieved (for instance if the package
  198                       is a Python 3 namespace package) and needs to be
  199                       manually defined.
  200     """
  201 
  202     #: The class that is used for request objects.  See :class:`~flask.Request`
  203     #: for more information.
  204     request_class = Request
  205 
  206     #: The class that is used for response objects.  See
  207     #: :class:`~flask.Response` for more information.
  208     response_class = Response
  209 
  210     #: The class that is used for the Jinja environment.
  211     #:
  212     #: .. versionadded:: 0.11
  213     jinja_environment = Environment
  214 
  215     #: The class that is used for the :data:`~flask.g` instance.
  216     #:
  217     #: Example use cases for a custom class:
  218     #:
  219     #: 1. Store arbitrary attributes on flask.g.
  220     #: 2. Add a property for lazy per-request database connectors.
  221     #: 3. Return None instead of AttributeError on unexpected attributes.
  222     #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
  223     #:
  224     #: In Flask 0.9 this property was called `request_globals_class` but it
  225     #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
  226     #: flask.g object is now application context scoped.
  227     #:
  228     #: .. versionadded:: 0.10
  229     app_ctx_globals_class = _AppCtxGlobals
  230 
  231     #: The class that is used for the ``config`` attribute of this app.
  232     #: Defaults to :class:`~flask.Config`.
  233     #:
  234     #: Example use cases for a custom class:
  235     #:
  236     #: 1. Default values for certain config options.
  237     #: 2. Access to config values through attributes in addition to keys.
  238     #:
  239     #: .. versionadded:: 0.11
  240     config_class = Config
  241 
  242     #: The testing flag.  Set this to ``True`` to enable the test mode of
  243     #: Flask extensions (and in the future probably also Flask itself).
  244     #: For example this might activate test helpers that have an
  245     #: additional runtime cost which should not be enabled by default.
  246     #:
  247     #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
  248     #: default it's implicitly enabled.
  249     #:
  250     #: This attribute can also be configured from the config with the
  251     #: ``TESTING`` configuration key.  Defaults to ``False``.
  252     testing = ConfigAttribute("TESTING")
  253 
  254     #: If a secret key is set, cryptographic components can use this to
  255     #: sign cookies and other things. Set this to a complex random value
  256     #: when you want to use the secure cookie for instance.
  257     #:
  258     #: This attribute can also be configured from the config with the
  259     #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.
  260     secret_key = ConfigAttribute("SECRET_KEY")
  261 
  262     #: The secure cookie uses this for the name of the session cookie.
  263     #:
  264     #: This attribute can also be configured from the config with the
  265     #: ``SESSION_COOKIE_NAME`` configuration key.  Defaults to ``'session'``
  266     session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")
  267 
  268     #: A :class:`~datetime.timedelta` which is used to set the expiration
  269     #: date of a permanent session.  The default is 31 days which makes a
  270     #: permanent session survive for roughly one month.
  271     #:
  272     #: This attribute can also be configured from the config with the
  273     #: ``PERMANENT_SESSION_LIFETIME`` configuration key.  Defaults to
  274     #: ``timedelta(days=31)``
  275     permanent_session_lifetime = ConfigAttribute(
  276         "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
  277     )
  278 
  279     #: A :class:`~datetime.timedelta` which is used as default cache_timeout
  280     #: for the :func:`send_file` functions. The default is 12 hours.
  281     #:
  282     #: This attribute can also be configured from the config with the
  283     #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration
  284     #: variable can also be set with an integer value used as seconds.
  285     #: Defaults to ``timedelta(hours=12)``
  286     send_file_max_age_default = ConfigAttribute(
  287         "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta
  288     )
  289 
  290     #: Enable this if you want to use the X-Sendfile feature.  Keep in
  291     #: mind that the server has to support this.  This only affects files
  292     #: sent with the :func:`send_file` method.
  293     #:
  294     #: .. versionadded:: 0.2
  295     #:
  296     #: This attribute can also be configured from the config with the
  297     #: ``USE_X_SENDFILE`` configuration key.  Defaults to ``False``.
  298     use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")
  299 
  300     #: The JSON encoder class to use.  Defaults to :class:`~flask.json.JSONEncoder`.
  301     #:
  302     #: .. versionadded:: 0.10
  303     json_encoder = json.JSONEncoder
  304 
  305     #: The JSON decoder class to use.  Defaults to :class:`~flask.json.JSONDecoder`.
  306     #:
  307     #: .. versionadded:: 0.10
  308     json_decoder = json.JSONDecoder
  309 
  310     #: Options that are passed to the Jinja environment in
  311     #: :meth:`create_jinja_environment`. Changing these options after
  312     #: the environment is created (accessing :attr:`jinja_env`) will
  313     #: have no effect.
  314     #:
  315     #: .. versionchanged:: 1.1.0
  316     #:     This is a ``dict`` instead of an ``ImmutableDict`` to allow
  317     #:     easier configuration.
  318     #:
  319     jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]}
  320 
  321     #: Default configuration parameters.
  322     default_config = ImmutableDict(
  323         {
  324             "ENV": None,
  325             "DEBUG": None,
  326             "TESTING": False,
  327             "PROPAGATE_EXCEPTIONS": None,
  328             "PRESERVE_CONTEXT_ON_EXCEPTION": None,
  329             "SECRET_KEY": None,
  330             "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
  331             "USE_X_SENDFILE": False,
  332             "SERVER_NAME": None,
  333             "APPLICATION_ROOT": "/",
  334             "SESSION_COOKIE_NAME": "session",
  335             "SESSION_COOKIE_DOMAIN": None,
  336             "SESSION_COOKIE_PATH": None,
  337             "SESSION_COOKIE_HTTPONLY": True,
  338             "SESSION_COOKIE_SECURE": False,
  339             "SESSION_COOKIE_SAMESITE": None,
  340             "SESSION_REFRESH_EACH_REQUEST": True,
  341             "MAX_CONTENT_LENGTH": None,
  342             "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),
  343             "TRAP_BAD_REQUEST_ERRORS": None,
  344             "TRAP_HTTP_EXCEPTIONS": False,
  345             "EXPLAIN_TEMPLATE_LOADING": False,
  346             "PREFERRED_URL_SCHEME": "http",
  347             "JSON_AS_ASCII": True,
  348             "JSON_SORT_KEYS": True,
  349             "JSONIFY_PRETTYPRINT_REGULAR": False,
  350             "JSONIFY_MIMETYPE": "application/json",
  351             "TEMPLATES_AUTO_RELOAD": None,
  352             "MAX_COOKIE_SIZE": 4093,
  353         }
  354     )
  355 
  356     #: The rule object to use for URL rules created.  This is used by
  357     #: :meth:`add_url_rule`.  Defaults to :class:`werkzeug.routing.Rule`.
  358     #:
  359     #: .. versionadded:: 0.7
  360     url_rule_class = Rule
  361 
  362     #: The map object to use for storing the URL rules and routing
  363     #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
  364     #:
  365     #: .. versionadded:: 1.1.0
  366     url_map_class = Map
  367 
  368     #: the test client that is used with when `test_client` is used.
  369     #:
  370     #: .. versionadded:: 0.7
  371     test_client_class = None
  372 
  373     #: The :class:`~click.testing.CliRunner` subclass, by default
  374     #: :class:`~flask.testing.FlaskCliRunner` that is used by
  375     #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
  376     #: Flask app object as the first argument.
  377     #:
  378     #: .. versionadded:: 1.0
  379     test_cli_runner_class = None
  380 
  381     #: the session interface to use.  By default an instance of
  382     #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
  383     #:
  384     #: .. versionadded:: 0.8
  385     session_interface = SecureCookieSessionInterface()
  386 
  387     # TODO remove the next three attrs when Sphinx :inherited-members: works
  388     # https://github.com/sphinx-doc/sphinx/issues/741
  389 
  390     #: The name of the package or module that this app belongs to. Do not
  391     #: change this once it is set by the constructor.
  392     import_name = None
  393 
  394     #: Location of the template files to be added to the template lookup.
  395     #: ``None`` if templates should not be added.
  396     template_folder = None
  397 
  398     #: Absolute path to the package on the filesystem. Used to look up
  399     #: resources contained in the package.
  400     root_path = None
  401 
  402     def __init__(
  403         self,
  404         import_name,
  405         static_url_path=None,
  406         static_folder="static",
  407         static_host=None,
  408         host_matching=False,
  409         subdomain_matching=False,
  410         template_folder="templates",
  411         instance_path=None,
  412         instance_relative_config=False,
  413         root_path=None,
  414     ):
  415         _PackageBoundObject.__init__(
  416             self, import_name, template_folder=template_folder, root_path=root_path
  417         )
  418 
  419         self.static_url_path = static_url_path
  420         self.static_folder = static_folder
  421 
  422         if instance_path is None:
  423             instance_path = self.auto_find_instance_path()
  424         elif not os.path.isabs(instance_path):
  425             raise ValueError(
  426                 "If an instance path is provided it must be absolute."
  427                 " A relative path was given instead."
  428             )
  429 
  430         #: Holds the path to the instance folder.
  431         #:
  432         #: .. versionadded:: 0.8
  433         self.instance_path = instance_path
  434 
  435         #: The configuration dictionary as :class:`Config`.  This behaves
  436         #: exactly like a regular dictionary but supports additional methods
  437         #: to load a config from files.
  438         self.config = self.make_config(instance_relative_config)
  439 
  440         #: A dictionary of all view functions registered.  The keys will
  441         #: be function names which are also used to generate URLs and
  442         #: the values are the function objects themselves.
  443         #: To register a view function, use the :meth:`route` decorator.
  444         self.view_functions = {}
  445 
  446         #: A dictionary of all registered error handlers.  The key is ``None``
  447         #: for error handlers active on the application, otherwise the key is
  448         #: the name of the blueprint.  Each key points to another dictionary
  449         #: where the key is the status code of the http exception.  The
  450         #: special key ``None`` points to a list of tuples where the first item
  451         #: is the class for the instance check and the second the error handler
  452         #: function.
  453         #:
  454         #: To register an error handler, use the :meth:`errorhandler`
  455         #: decorator.
  456         self.error_handler_spec = {}
  457 
  458         #: A list of functions that are called when :meth:`url_for` raises a
  459         #: :exc:`~werkzeug.routing.BuildError`.  Each function registered here
  460         #: is called with `error`, `endpoint` and `values`.  If a function
  461         #: returns ``None`` or raises a :exc:`BuildError` the next function is
  462         #: tried.
  463         #:
  464         #: .. versionadded:: 0.9
  465         self.url_build_error_handlers = []
  466 
  467         #: A dictionary with lists of functions that will be called at the
  468         #: beginning of each request. The key of the dictionary is the name of
  469         #: the blueprint this function is active for, or ``None`` for all
  470         #: requests. To register a function, use the :meth:`before_request`
  471         #: decorator.
  472         self.before_request_funcs = {}
  473 
  474         #: A list of functions that will be called at the beginning of the
  475         #: first request to this instance. To register a function, use the
  476         #: :meth:`before_first_request` decorator.
  477         #:
  478         #: .. versionadded:: 0.8
  479         self.before_first_request_funcs = []
  480 
  481         #: A dictionary with lists of functions that should be called after
  482         #: each request.  The key of the dictionary is the name of the blueprint
  483         #: this function is active for, ``None`` for all requests.  This can for
  484         #: example be used to close database connections. To register a function
  485         #: here, use the :meth:`after_request` decorator.
  486         self.after_request_funcs = {}
  487 
  488         #: A dictionary with lists of functions that are called after
  489         #: each request, even if an exception has occurred. The key of the
  490         #: dictionary is the name of the blueprint this function is active for,
  491         #: ``None`` for all requests. These functions are not allowed to modify
  492         #: the request, and their return values are ignored. If an exception
  493         #: occurred while processing the request, it gets passed to each
  494         #: teardown_request function. To register a function here, use the
  495         #: :meth:`teardown_request` decorator.
  496         #:
  497         #: .. versionadded:: 0.7
  498         self.teardown_request_funcs = {}
  499 
  500         #: A list of functions that are called when the application context
  501         #: is destroyed.  Since the application context is also torn down
  502         #: if the request ends this is the place to store code that disconnects
  503         #: from databases.
  504         #:
  505         #: .. versionadded:: 0.9
  506         self.teardown_appcontext_funcs = []
  507 
  508         #: A dictionary with lists of functions that are called before the
  509         #: :attr:`before_request_funcs` functions. The key of the dictionary is
  510         #: the name of the blueprint this function is active for, or ``None``
  511         #: for all requests. To register a function, use
  512         #: :meth:`url_value_preprocessor`.
  513         #:
  514         #: .. versionadded:: 0.7
  515         self.url_value_preprocessors = {}
  516 
  517         #: A dictionary with lists of functions that can be used as URL value
  518         #: preprocessors.  The key ``None`` here is used for application wide
  519         #: callbacks, otherwise the key is the name of the blueprint.
  520         #: Each of these functions has the chance to modify the dictionary
  521         #: of URL values before they are used as the keyword arguments of the
  522         #: view function.  For each function registered this one should also
  523         #: provide a :meth:`url_defaults` function that adds the parameters
  524         #: automatically again that were removed that way.
  525         #:
  526         #: .. versionadded:: 0.7
  527         self.url_default_functions = {}
  528 
  529         #: A dictionary with list of functions that are called without argument
  530         #: to populate the template context.  The key of the dictionary is the
  531         #: name of the blueprint this function is active for, ``None`` for all
  532         #: requests.  Each returns a dictionary that the template context is
  533         #: updated with.  To register a function here, use the
  534         #: :meth:`context_processor` decorator.
  535         self.template_context_processors = {None: [_default_template_ctx_processor]}
  536 
  537         #: A list of shell context processor functions that should be run
  538         #: when a shell context is created.
  539         #:
  540         #: .. versionadded:: 0.11
  541         self.shell_context_processors = []
  542 
  543         #: all the attached blueprints in a dictionary by name.  Blueprints
  544         #: can be attached multiple times so this dictionary does not tell
  545         #: you how often they got attached.
  546         #:
  547         #: .. versionadded:: 0.7
  548         self.blueprints = {}
  549         self._blueprint_order = []
  550 
  551         #: a place where extensions can store application specific state.  For
  552         #: example this is where an extension could store database engines and
  553         #: similar things.  For backwards compatibility extensions should register
  554         #: themselves like this::
  555         #:
  556         #:      if not hasattr(app, 'extensions'):
  557         #:          app.extensions = {}
  558         #:      app.extensions['extensionname'] = SomeObject()
  559         #:
  560         #: The key must match the name of the extension module. For example in
  561         #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
  562         #: ``'foo'``.
  563         #:
  564         #: .. versionadded:: 0.7
  565         self.extensions = {}
  566 
  567         #: The :class:`~werkzeug.routing.Map` for this instance.  You can use
  568         #: this to change the routing converters after the class was created
  569         #: but before any routes are connected.  Example::
  570         #:
  571         #:    from werkzeug.routing import BaseConverter
  572         #:
  573         #:    class ListConverter(BaseConverter):
  574         #:        def to_python(self, value):
  575         #:            return value.split(',')
  576         #:        def to_url(self, values):
  577         #:            return ','.join(super(ListConverter, self).to_url(value)
  578         #:                            for value in values)
  579         #:
  580         #:    app = Flask(__name__)
  581         #:    app.url_map.converters['list'] = ListConverter
  582         self.url_map = self.url_map_class()
  583 
  584         self.url_map.host_matching = host_matching
  585         self.subdomain_matching = subdomain_matching
  586 
  587         # tracks internally if the application already handled at least one
  588         # request.
  589         self._got_first_request = False
  590         self._before_request_lock = Lock()
  591 
  592         # Add a static route using the provided static_url_path, static_host,
  593         # and static_folder if there is a configured static_folder.
  594         # Note we do this without checking if static_folder exists.
  595         # For one, it might be created while the server is running (e.g. during
  596         # development). Also, Google App Engine stores static files somewhere
  597         if self.has_static_folder:
  598             assert (
  599                 bool(static_host) == host_matching
  600             ), "Invalid static_host/host_matching combination"
  601             self.add_url_rule(
  602                 self.static_url_path + "/<path:filename>",
  603                 endpoint="static",
  604                 host=static_host,
  605                 view_func=self.send_static_file,
  606             )
  607 
  608         # Set the name of the Click group in case someone wants to add
  609         # the app's commands to another CLI tool.
  610         self.cli.name = self.name
  611 
  612     @locked_cached_property
  613     def name(self):
  614         """The name of the application.  This is usually the import name
  615         with the difference that it's guessed from the run file if the
  616         import name is main.  This name is used as a display name when
  617         Flask needs the name of the application.  It can be set and overridden
  618         to change the value.
  619 
  620         .. versionadded:: 0.8
  621         """
  622         if self.import_name == "__main__":
  623             fn = getattr(sys.modules["__main__"], "__file__", None)
  624             if fn is None:
  625                 return "__main__"
  626             return os.path.splitext(os.path.basename(fn))[0]
  627         return self.import_name
  628 
  629     @property
  630     def propagate_exceptions(self):
  631         """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
  632         value in case it's set, otherwise a sensible default is returned.
  633 
  634         .. versionadded:: 0.7
  635         """
  636         rv = self.config["PROPAGATE_EXCEPTIONS"]
  637         if rv is not None:
  638             return rv
  639         return self.testing or self.debug
  640 
  641     @property
  642     def preserve_context_on_exception(self):
  643         """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
  644         configuration value in case it's set, otherwise a sensible default
  645         is returned.
  646 
  647         .. versionadded:: 0.7
  648         """
  649         rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]
  650         if rv is not None:
  651             return rv
  652         return self.debug
  653 
  654     @locked_cached_property
  655     def logger(self):
  656         """A standard Python :class:`~logging.Logger` for the app, with
  657         the same name as :attr:`name`.
  658 
  659         In debug mode, the logger's :attr:`~logging.Logger.level` will
  660         be set to :data:`~logging.DEBUG`.
  661 
  662         If there are no handlers configured, a default handler will be
  663         added. See :doc:`/logging` for more information.
  664 
  665         .. versionchanged:: 1.1.0
  666             The logger takes the same name as :attr:`name` rather than
  667             hard-coding ``"flask.app"``.
  668 
  669         .. versionchanged:: 1.0.0
  670             Behavior was simplified. The logger is always named
  671             ``"flask.app"``. The level is only set during configuration,
  672             it doesn't check ``app.debug`` each time. Only one format is
  673             used, not different ones depending on ``app.debug``. No
  674             handlers are removed, and a handler is only added if no
  675             handlers are already configured.
  676 
  677         .. versionadded:: 0.3
  678         """
  679         return create_logger(self)
  680 
  681     @locked_cached_property
  682     def jinja_env(self):
  683         """The Jinja environment used to load templates.
  684 
  685         The environment is created the first time this property is
  686         accessed. Changing :attr:`jinja_options` after that will have no
  687         effect.
  688         """
  689         return self.create_jinja_environment()
  690 
  691     @property
  692     def got_first_request(self):
  693         """This attribute is set to ``True`` if the application started
  694         handling the first request.
  695 
  696         .. versionadded:: 0.8
  697         """
  698         return self._got_first_request
  699 
  700     def make_config(self, instance_relative=False):
  701         """Used to create the config attribute by the Flask constructor.
  702         The `instance_relative` parameter is passed in from the constructor
  703         of Flask (there named `instance_relative_config`) and indicates if
  704         the config should be relative to the instance path or the root path
  705         of the application.
  706 
  707         .. versionadded:: 0.8
  708         """
  709         root_path = self.root_path
  710         if instance_relative:
  711             root_path = self.instance_path
  712         defaults = dict(self.default_config)
  713         defaults["ENV"] = get_env()
  714         defaults["DEBUG"] = get_debug_flag()
  715         return self.config_class(root_path, defaults)
  716 
  717     def auto_find_instance_path(self):
  718         """Tries to locate the instance path if it was not provided to the
  719         constructor of the application class.  It will basically calculate
  720         the path to a folder named ``instance`` next to your main file or
  721         the package.
  722 
  723         .. versionadded:: 0.8
  724         """
  725         prefix, package_path = find_package(self.import_name)
  726         if prefix is None:
  727             return os.path.join(package_path, "instance")
  728         return os.path.join(prefix, "var", self.name + "-instance")
  729 
  730     def open_instance_resource(self, resource, mode="rb"):
  731         """Opens a resource from the application's instance folder
  732         (:attr:`instance_path`).  Otherwise works like
  733         :meth:`open_resource`.  Instance resources can also be opened for
  734         writing.
  735 
  736         :param resource: the name of the resource.  To access resources within
  737                          subfolders use forward slashes as separator.
  738         :param mode: resource file opening mode, default is 'rb'.
  739         """
  740         return open(os.path.join(self.instance_path, resource), mode)
  741 
  742     @property
  743     def templates_auto_reload(self):
  744         """Reload templates when they are changed. Used by
  745         :meth:`create_jinja_environment`.
  746 
  747         This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If
  748         not set, it will be enabled in debug mode.
  749 
  750         .. versionadded:: 1.0
  751             This property was added but the underlying config and behavior
  752             already existed.
  753         """
  754         rv = self.config["TEMPLATES_AUTO_RELOAD"]
  755         return rv if rv is not None else self.debug
  756 
  757     @templates_auto_reload.setter
  758     def templates_auto_reload(self, value):
  759         self.config["TEMPLATES_AUTO_RELOAD"] = value
  760 
  761     def create_jinja_environment(self):
  762         """Create the Jinja environment based on :attr:`jinja_options`
  763         and the various Jinja-related methods of the app. Changing
  764         :attr:`jinja_options` after this will have no effect. Also adds
  765         Flask-related globals and filters to the environment.
  766 
  767         .. versionchanged:: 0.11
  768            ``Environment.auto_reload`` set in accordance with
  769            ``TEMPLATES_AUTO_RELOAD`` configuration option.
  770 
  771         .. versionadded:: 0.5
  772         """
  773         options = dict(self.jinja_options)
  774 
  775         if "autoescape" not in options:
  776             options["autoescape"] = self.select_jinja_autoescape
  777 
  778         if "auto_reload" not in options:
  779             options["auto_reload"] = self.templates_auto_reload
  780 
  781         rv = self.jinja_environment(self, **options)
  782         rv.globals.update(
  783             url_for=url_for,
  784             get_flashed_messages=get_flashed_messages,
  785             config=self.config,
  786             # request, session and g are normally added with the
  787             # context processor for efficiency reasons but for imported
  788             # templates we also want the proxies in there.
  789             request=request,
  790             session=session,
  791             g=g,
  792         )
  793         rv.filters["tojson"] = json.tojson_filter
  794         return rv
  795 
  796     def create_global_jinja_loader(self):
  797         """Creates the loader for the Jinja2 environment.  Can be used to
  798         override just the loader and keeping the rest unchanged.  It's
  799         discouraged to override this function.  Instead one should override
  800         the :meth:`jinja_loader` function instead.
  801 
  802         The global loader dispatches between the loaders of the application
  803         and the individual blueprints.
  804 
  805         .. versionadded:: 0.7
  806         """
  807         return DispatchingJinjaLoader(self)
  808 
  809     def select_jinja_autoescape(self, filename):
  810         """Returns ``True`` if autoescaping should be active for the given
  811         template name. If no template name is given, returns `True`.
  812 
  813         .. versionadded:: 0.5
  814         """
  815         if filename is None:
  816             return True
  817         return filename.endswith((".html", ".htm", ".xml", ".xhtml"))
  818 
  819     def update_template_context(self, context):
  820         """Update the template context with some commonly used variables.
  821         This injects request, session, config and g into the template
  822         context as well as everything template context processors want
  823         to inject.  Note that the as of Flask 0.6, the original values
  824         in the context will not be overridden if a context processor
  825         decides to return a value with the same key.
  826 
  827         :param context: the context as a dictionary that is updated in place
  828                         to add extra variables.
  829         """
  830         funcs = self.template_context_processors[None]
  831         reqctx = _request_ctx_stack.top
  832         if reqctx is not None:
  833             bp = reqctx.request.blueprint
  834             if bp is not None and bp in self.template_context_processors:
  835                 funcs = chain(funcs, self.template_context_processors[bp])
  836         orig_ctx = context.copy()
  837         for func in funcs:
  838             context.update(func())
  839         # make sure the original values win.  This makes it possible to
  840         # easier add new variables in context processors without breaking
  841         # existing views.
  842         context.update(orig_ctx)
  843 
  844     def make_shell_context(self):
  845         """Returns the shell context for an interactive shell for this
  846         application.  This runs all the registered shell context
  847         processors.
  848 
  849         .. versionadded:: 0.11
  850         """
  851         rv = {"app": self, "g": g}
  852         for processor in self.shell_context_processors:
  853             rv.update(processor())
  854         return rv
  855 
  856     #: What environment the app is running in. Flask and extensions may
  857     #: enable behaviors based on the environment, such as enabling debug
  858     #: mode. This maps to the :data:`ENV` config key. This is set by the
  859     #: :envvar:`FLASK_ENV` environment variable and may not behave as
  860     #: expected if set in code.
  861     #:
  862     #: **Do not enable development when deploying in production.**
  863     #:
  864     #: Default: ``'production'``
  865     env = ConfigAttribute("ENV")
  866 
  867     @property
  868     def debug(self):
  869         """Whether debug mode is enabled. When using ``flask run`` to start
  870         the development server, an interactive debugger will be shown for
  871         unhandled exceptions, and the server will be reloaded when code
  872         changes. This maps to the :data:`DEBUG` config key. This is
  873         enabled when :attr:`env` is ``'development'`` and is overridden
  874         by the ``FLASK_DEBUG`` environment variable. It may not behave as
  875         expected if set in code.
  876 
  877         **Do not enable debug mode when deploying in production.**
  878 
  879         Default: ``True`` if :attr:`env` is ``'development'``, or
  880         ``False`` otherwise.
  881         """
  882         return self.config["DEBUG"]
  883 
  884     @debug.setter
  885     def debug(self, value):
  886         self.config["DEBUG"] = value
  887         self.jinja_env.auto_reload = self.templates_auto_reload
  888 
  889     def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
  890         """Runs the application on a local development server.
  891 
  892         Do not use ``run()`` in a production setting. It is not intended to
  893         meet security and performance requirements for a production server.
  894         Instead, see :ref:`deployment` for WSGI server recommendations.
  895 
  896         If the :attr:`debug` flag is set the server will automatically reload
  897         for code changes and show a debugger in case an exception happened.
  898 
  899         If you want to run the application in debug mode, but disable the
  900         code execution on the interactive debugger, you can pass
  901         ``use_evalex=False`` as parameter.  This will keep the debugger's
  902         traceback screen active, but disable code execution.
  903 
  904         It is not recommended to use this function for development with
  905         automatic reloading as this is badly supported.  Instead you should
  906         be using the :command:`flask` command line script's ``run`` support.
  907 
  908         .. admonition:: Keep in Mind
  909 
  910            Flask will suppress any server error with a generic error page
  911            unless it is in debug mode.  As such to enable just the
  912            interactive debugger without the code reloading, you have to
  913            invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
  914            Setting ``use_debugger`` to ``True`` without being in debug mode
  915            won't catch any exceptions because there won't be any to
  916            catch.
  917 
  918         :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
  919             have the server available externally as well. Defaults to
  920             ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
  921             if present.
  922         :param port: the port of the webserver. Defaults to ``5000`` or the
  923             port defined in the ``SERVER_NAME`` config variable if present.
  924         :param debug: if given, enable or disable debug mode. See
  925             :attr:`debug`.
  926         :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
  927             files to set environment variables. Will also change the working
  928             directory to the directory containing the first file found.
  929         :param options: the options to be forwarded to the underlying Werkzeug
  930             server. See :func:`werkzeug.serving.run_simple` for more
  931             information.
  932 
  933         .. versionchanged:: 1.0
  934             If installed, python-dotenv will be used to load environment
  935             variables from :file:`.env` and :file:`.flaskenv` files.
  936 
  937             If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`
  938             environment variables will override :attr:`env` and
  939             :attr:`debug`.
  940 
  941             Threaded mode is enabled by default.
  942 
  943         .. versionchanged:: 0.10
  944             The default port is now picked from the ``SERVER_NAME``
  945             variable.
  946         """
  947         # Change this into a no-op if the server is invoked from the
  948         # command line. Have a look at cli.py for more information.
  949         if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
  950             from .debughelpers import explain_ignored_app_run
  951 
  952             explain_ignored_app_run()
  953             return
  954 
  955         if get_load_dotenv(load_dotenv):
  956             cli.load_dotenv()
  957 
  958             # if set, let env vars override previous values
  959             if "FLASK_ENV" in os.environ:
  960                 self.env = get_env()
  961                 self.debug = get_debug_flag()
  962             elif "FLASK_DEBUG" in os.environ:
  963                 self.debug = get_debug_flag()
  964 
  965         # debug passed to method overrides all other sources
  966         if debug is not None:
  967             self.debug = bool(debug)
  968 
  969         _host = "127.0.0.1"
  970         _port = 5000
  971         server_name = self.config.get("SERVER_NAME")
  972         sn_host, sn_port = None, None
  973 
  974         if server_name:
  975             sn_host, _, sn_port = server_name.partition(":")
  976 
  977         host = host or sn_host or _host
  978         # pick the first value that's not None (0 is allowed)
  979         port = int(next((p for p in (port, sn_port) if p is not None), _port))
  980 
  981         options.setdefault("use_reloader", self.debug)
  982         options.setdefault("use_debugger", self.debug)
  983         options.setdefault("threaded", True)
  984 
  985         cli.show_server_banner(self.env, self.debug, self.name, False)
  986 
  987         from werkzeug.serving import run_simple
  988 
  989         try:
  990             run_simple(host, port, self, **options)
  991         finally:
  992             # reset the first request information if the development server
  993             # reset normally.  This makes it possible to restart the server
  994             # without reloader and that stuff from an interactive shell.
  995             self._got_first_request = False
  996 
  997     def test_client(self, use_cookies=True, **kwargs):
  998         """Creates a test client for this application.  For information
  999         about unit testing head over to :ref:`testing`.
 1000 
 1001         Note that if you are testing for assertions or exceptions in your
 1002         application code, you must set ``app.testing = True`` in order for the
 1003         exceptions to propagate to the test client.  Otherwise, the exception
 1004         will be handled by the application (not visible to the test client) and
 1005         the only indication of an AssertionError or other exception will be a
 1006         500 status code response to the test client.  See the :attr:`testing`
 1007         attribute.  For example::
 1008 
 1009             app.testing = True
 1010             client = app.test_client()
 1011 
 1012         The test client can be used in a ``with`` block to defer the closing down
 1013         of the context until the end of the ``with`` block.  This is useful if
 1014         you want to access the context locals for testing::
 1015 
 1016             with app.test_client() as c:
 1017                 rv = c.get('/?vodka=42')
 1018                 assert request.args['vodka'] == '42'
 1019 
 1020         Additionally, you may pass optional keyword arguments that will then
 1021         be passed to the application's :attr:`test_client_class` constructor.
 1022         For example::
 1023 
 1024             from flask.testing import FlaskClient
 1025 
 1026             class CustomClient(FlaskClient):
 1027                 def __init__(self, *args, **kwargs):
 1028                     self._authentication = kwargs.pop("authentication")
 1029                     super(CustomClient,self).__init__( *args, **kwargs)
 1030 
 1031             app.test_client_class = CustomClient
 1032             client = app.test_client(authentication='Basic ....')
 1033 
 1034         See :class:`~flask.testing.FlaskClient` for more information.
 1035 
 1036         .. versionchanged:: 0.4
 1037            added support for ``with`` block usage for the client.
 1038 
 1039         .. versionadded:: 0.7
 1040            The `use_cookies` parameter was added as well as the ability
 1041            to override the client to be used by setting the
 1042            :attr:`test_client_class` attribute.
 1043 
 1044         .. versionchanged:: 0.11
 1045            Added `**kwargs` to support passing additional keyword arguments to
 1046            the constructor of :attr:`test_client_class`.
 1047         """
 1048         cls = self.test_client_class
 1049         if cls is None:
 1050             from .testing import FlaskClient as cls
 1051         return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)
 1052 
 1053     def test_cli_runner(self, **kwargs):
 1054         """Create a CLI runner for testing CLI commands.
 1055         See :ref:`testing-cli`.
 1056 
 1057         Returns an instance of :attr:`test_cli_runner_class`, by default
 1058         :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
 1059         passed as the first argument.
 1060 
 1061         .. versionadded:: 1.0
 1062         """
 1063         cls = self.test_cli_runner_class
 1064 
 1065         if cls is None:
 1066             from .testing import FlaskCliRunner as cls
 1067 
 1068         return cls(self, **kwargs)
 1069 
 1070     def open_session(self, request):
 1071         """Creates or opens a new session.  Default implementation stores all
 1072         session data in a signed cookie.  This requires that the
 1073         :attr:`secret_key` is set.  Instead of overriding this method
 1074         we recommend replacing the :class:`session_interface`.
 1075 
 1076         .. deprecated: 1.0
 1077             Will be removed in 2.0. Use
 1078             ``session_interface.open_session`` instead.
 1079 
 1080         :param request: an instance of :attr:`request_class`.
 1081         """
 1082 
 1083         warnings.warn(
 1084             DeprecationWarning(
 1085                 '"open_session" is deprecated and will be removed in'
 1086                 ' 2.0. Use "session_interface.open_session" instead.'
 1087             )
 1088         )
 1089         return self.session_interface.open_session(self, request)
 1090 
 1091     def save_session(self, session, response):
 1092         """Saves the session if it needs updates.  For the default
 1093         implementation, check :meth:`open_session`.  Instead of overriding this
 1094         method we recommend replacing the :class:`session_interface`.
 1095 
 1096         .. deprecated: 1.0
 1097             Will be removed in 2.0. Use
 1098             ``session_interface.save_session`` instead.
 1099 
 1100         :param session: the session to be saved (a
 1101                         :class:`~werkzeug.contrib.securecookie.SecureCookie`
 1102                         object)
 1103         :param response: an instance of :attr:`response_class`
 1104         """
 1105 
 1106         warnings.warn(
 1107             DeprecationWarning(
 1108                 '"save_session" is deprecated and will be removed in'
 1109                 ' 2.0. Use "session_interface.save_session" instead.'
 1110             )
 1111         )
 1112         return self.session_interface.save_session(self, session, response)
 1113 
 1114     def make_null_session(self):
 1115         """Creates a new instance of a missing session.  Instead of overriding
 1116         this method we recommend replacing the :class:`session_interface`.
 1117 
 1118         .. deprecated: 1.0
 1119             Will be removed in 2.0. Use
 1120             ``session_interface.make_null_session`` instead.
 1121 
 1122         .. versionadded:: 0.7
 1123         """
 1124 
 1125         warnings.warn(
 1126             DeprecationWarning(
 1127                 '"make_null_session" is deprecated and will be removed'
 1128                 ' in 2.0. Use "session_interface.make_null_session"'
 1129                 " instead."
 1130             )
 1131         )
 1132         return self.session_interface.make_null_session(self)
 1133 
 1134     @setupmethod
 1135     def register_blueprint(self, blueprint, **options):
 1136         """Register a :class:`~flask.Blueprint` on the application. Keyword
 1137         arguments passed to this method will override the defaults set on the
 1138         blueprint.
 1139 
 1140         Calls the blueprint's :meth:`~flask.Blueprint.register` method after
 1141         recording the blueprint in the application's :attr:`blueprints`.
 1142 
 1143         :param blueprint: The blueprint to register.
 1144         :param url_prefix: Blueprint routes will be prefixed with this.
 1145         :param subdomain: Blueprint routes will match on this subdomain.
 1146         :param url_defaults: Blueprint routes will use these default values for
 1147             view arguments.
 1148         :param options: Additional keyword arguments are passed to
 1149             :class:`~flask.blueprints.BlueprintSetupState`. They can be
 1150             accessed in :meth:`~flask.Blueprint.record` callbacks.
 1151 
 1152         .. versionadded:: 0.7
 1153         """
 1154         first_registration = False
 1155 
 1156         if blueprint.name in self.blueprints:
 1157             assert self.blueprints[blueprint.name] is blueprint, (
 1158                 "A name collision occurred between blueprints %r and %r. Both"
 1159                 ' share the same name "%s". Blueprints that are created on the'
 1160                 " fly need unique names."
 1161                 % (blueprint, self.blueprints[blueprint.name], blueprint.name)
 1162             )
 1163         else:
 1164             self.blueprints[blueprint.name] = blueprint
 1165             self._blueprint_order.append(blueprint)
 1166             first_registration = True
 1167 
 1168         blueprint.register(self, options, first_registration)
 1169 
 1170     def iter_blueprints(self):
 1171         """Iterates over all blueprints by the order they were registered.
 1172 
 1173         .. versionadded:: 0.11
 1174         """
 1175         return iter(self._blueprint_order)
 1176 
 1177     @setupmethod
 1178     def add_url_rule(
 1179         self,
 1180         rule,
 1181         endpoint=None,
 1182         view_func=None,
 1183         provide_automatic_options=None,
 1184         **options
 1185     ):
 1186         """Connects a URL rule.  Works exactly like the :meth:`route`
 1187         decorator.  If a view_func is provided it will be registered with the
 1188         endpoint.
 1189 
 1190         Basically this example::
 1191 
 1192             @app.route('/')
 1193             def index():
 1194                 pass
 1195 
 1196         Is equivalent to the following::
 1197 
 1198             def index():
 1199                 pass
 1200             app.add_url_rule('/', 'index', index)
 1201 
 1202         If the view_func is not provided you will need to connect the endpoint
 1203         to a view function like so::
 1204 
 1205             app.view_functions['index'] = index
 1206 
 1207         Internally :meth:`route` invokes :meth:`add_url_rule` so if you want
 1208         to customize the behavior via subclassing you only need to change
 1209         this method.
 1210 
 1211         For more information refer to :ref:`url-route-registrations`.
 1212 
 1213         .. versionchanged:: 0.2
 1214            `view_func` parameter added.
 1215 
 1216         .. versionchanged:: 0.6
 1217            ``OPTIONS`` is added automatically as method.
 1218 
 1219         :param rule: the URL rule as string
 1220         :param endpoint: the endpoint for the registered URL rule.  Flask
 1221                          itself assumes the name of the view function as
 1222                          endpoint
 1223         :param view_func: the function to call when serving a request to the
 1224                           provided endpoint
 1225         :param provide_automatic_options: controls whether the ``OPTIONS``
 1226             method should be added automatically. This can also be controlled
 1227             by setting the ``view_func.provide_automatic_options = False``
 1228             before adding the rule.
 1229         :param options: the options to be forwarded to the underlying
 1230                         :class:`~werkzeug.routing.Rule` object.  A change
 1231                         to Werkzeug is handling of method options.  methods
 1232                         is a list of methods this rule should be limited
 1233                         to (``GET``, ``POST`` etc.).  By default a rule
 1234                         just listens for ``GET`` (and implicitly ``HEAD``).
 1235                         Starting with Flask 0.6, ``OPTIONS`` is implicitly
 1236                         added and handled by the standard request handling.
 1237         """
 1238         if endpoint is None:
 1239             endpoint = _endpoint_from_view_func(view_func)
 1240         options["endpoint"] = endpoint
 1241         methods = options.pop("methods", None)
 1242 
 1243         # if the methods are not given and the view_func object knows its
 1244         # methods we can use that instead.  If neither exists, we go with
 1245         # a tuple of only ``GET`` as default.
 1246         if methods is None:
 1247             methods = getattr(view_func, "methods", None) or ("GET",)
 1248         if isinstance(methods, string_types):
 1249             raise TypeError(
 1250                 "Allowed methods have to be iterables of strings, "
 1251                 'for example: @app.route(..., methods=["POST"])'
 1252             )
 1253         methods = set(item.upper() for item in methods)
 1254 
 1255         # Methods that should always be added
 1256         required_methods = set(getattr(view_func, "required_methods", ()))
 1257 
 1258         # starting with Flask 0.8 the view_func object can disable and
 1259         # force-enable the automatic options handling.
 1260         if provide_automatic_options is None:
 1261             provide_automatic_options = getattr(
 1262                 view_func, "provide_automatic_options", None
 1263             )
 1264 
 1265         if provide_automatic_options is None:
 1266             if "OPTIONS" not in methods:
 1267                 provide_automatic_options = True
 1268                 required_methods.add("OPTIONS")
 1269             else:
 1270                 provide_automatic_options = False
 1271 
 1272         # Add the required methods now.
 1273         methods |= required_methods
 1274 
 1275         rule = self.url_rule_class(rule, methods=methods, **options)
 1276         rule.provide_automatic_options = provide_automatic_options
 1277 
 1278         self.url_map.add(rule)
 1279         if view_func is not None:
 1280             old_func = self.view_functions.get(endpoint)
 1281             if old_func is not None and old_func != view_func:
 1282                 raise AssertionError(
 1283                     "View function mapping is overwriting an "
 1284                     "existing endpoint function: %s" % endpoint
 1285                 )
 1286             self.view_functions[endpoint] = view_func
 1287 
 1288     def route(self, rule, **options):
 1289         """A decorator that is used to register a view function for a
 1290         given URL rule.  This does the same thing as :meth:`add_url_rule`
 1291         but is intended for decorator usage::
 1292 
 1293             @app.route('/')
 1294             def index():
 1295                 return 'Hello World'
 1296 
 1297         For more information refer to :ref:`url-route-registrations`.
 1298 
 1299         :param rule: the URL rule as string
 1300         :param endpoint: the endpoint for the registered URL rule.  Flask
 1301                          itself assumes the name of the view function as
 1302                          endpoint
 1303         :param options: the options to be forwarded to the underlying
 1304                         :class:`~werkzeug.routing.Rule` object.  A change
 1305                         to Werkzeug is handling of method options.  methods
 1306                         is a list of methods this rule should be limited
 1307                         to (``GET``, ``POST`` etc.).  By default a rule
 1308                         just listens for ``GET`` (and implicitly ``HEAD``).
 1309                         Starting with Flask 0.6, ``OPTIONS`` is implicitly
 1310                         added and handled by the standard request handling.
 1311         """
 1312 
 1313         def decorator(f):
 1314             endpoint = options.pop("endpoint", None)
 1315             self.add_url_rule(rule, endpoint, f, **options)
 1316             return f
 1317 
 1318         return decorator
 1319 
 1320     @setupmethod
 1321     def endpoint(self, endpoint):
 1322         """A decorator to register a function as an endpoint.
 1323         Example::
 1324 
 1325             @app.endpoint('example.endpoint')
 1326             def example():
 1327                 return "example"
 1328 
 1329         :param endpoint: the name of the endpoint
 1330         """
 1331 
 1332         def decorator(f):
 1333             self.view_functions[endpoint] = f
 1334             return f
 1335 
 1336         return decorator
 1337 
 1338     @staticmethod
 1339     def _get_exc_class_and_code(exc_class_or_code):
 1340         """Get the exception class being handled. For HTTP status codes
 1341         or ``HTTPException`` subclasses, return both the exception and
 1342         status code.
 1343 
 1344         :param exc_class_or_code: Any exception class, or an HTTP status
 1345             code as an integer.
 1346         """
 1347         if isinstance(exc_class_or_code, integer_types):
 1348             exc_class = default_exceptions[exc_class_or_code]
 1349         else:
 1350             exc_class = exc_class_or_code
 1351 
 1352         assert issubclass(exc_class, Exception)
 1353 
 1354         if issubclass(exc_class, HTTPException):
 1355             return exc_class, exc_class.code
 1356         else:
 1357             return exc_class, None
 1358 
 1359     @setupmethod
 1360     def errorhandler(self, code_or_exception):
 1361         """Register a function to handle errors by code or exception class.
 1362 
 1363         A decorator that is used to register a function given an
 1364         error code.  Example::
 1365 
 1366             @app.errorhandler(404)
 1367             def page_not_found(error):
 1368                 return 'This page does not exist', 404
 1369 
 1370         You can also register handlers for arbitrary exceptions::
 1371 
 1372             @app.errorhandler(DatabaseError)
 1373             def special_exception_handler(error):
 1374                 return 'Database connection failed', 500
 1375 
 1376         .. versionadded:: 0.7
 1377             Use :meth:`register_error_handler` instead of modifying
 1378             :attr:`error_handler_spec` directly, for application wide error
 1379             handlers.
 1380 
 1381         .. versionadded:: 0.7
 1382            One can now additionally also register custom exception types
 1383            that do not necessarily have to be a subclass of the
 1384            :class:`~werkzeug.exceptions.HTTPException` class.
 1385 
 1386         :param code_or_exception: the code as integer for the handler, or
 1387                                   an arbitrary exception
 1388         """
 1389 
 1390         def decorator(f):
 1391             self._register_error_handler(None, code_or_exception, f)
 1392             return f
 1393 
 1394         return decorator
 1395 
 1396     @setupmethod
 1397     def register_error_handler(self, code_or_exception, f):
 1398         """Alternative error attach function to the :meth:`errorhandler`
 1399         decorator that is more straightforward to use for non decorator
 1400         usage.
 1401 
 1402         .. versionadded:: 0.7
 1403         """
 1404         self._register_error_handler(None, code_or_exception, f)
 1405 
 1406     @setupmethod
 1407     def _register_error_handler(self, key, code_or_exception, f):
 1408         """
 1409         :type key: None|str
 1410         :type code_or_exception: int|T<=Exception
 1411         :type f: callable
 1412         """
 1413         if isinstance(code_or_exception, HTTPException):  # old broken behavior
 1414             raise ValueError(
 1415                 "Tried to register a handler for an exception instance {0!r}."
 1416                 " Handlers can only be registered for exception classes or"
 1417                 " HTTP error codes.".format(code_or_exception)
 1418             )
 1419 
 1420         try:
 1421             exc_class, code = self._get_exc_class_and_code(code_or_exception)
 1422         except KeyError:
 1423             raise KeyError(
 1424                 "'{0}' is not a recognized HTTP error code. Use a subclass of"
 1425                 " HTTPException with that code instead.".format(code_or_exception)
 1426             )
 1427 
 1428         handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})
 1429         handlers[exc_class] = f
 1430 
 1431     @setupmethod
 1432     def template_filter(self, name=None):
 1433         """A decorator that is used to register custom template filter.
 1434         You can specify a name for the filter, otherwise the function
 1435         name will be used. Example::
 1436 
 1437           @app.template_filter()
 1438           def reverse(s):
 1439               return s[::-1]
 1440 
 1441         :param name: the optional name of the filter, otherwise the
 1442                      function name will be used.
 1443         """
 1444 
 1445         def decorator(f):
 1446             self.add_template_filter(f, name=name)
 1447             return f
 1448 
 1449         return decorator
 1450 
 1451     @setupmethod
 1452     def add_template_filter(self, f, name=None):
 1453         """Register a custom template filter.  Works exactly like the
 1454         :meth:`template_filter` decorator.
 1455 
 1456         :param name: the optional name of the filter, otherwise the
 1457                      function name will be used.
 1458         """
 1459         self.jinja_env.filters[name or f.__name__] = f
 1460 
 1461     @setupmethod
 1462     def template_test(self, name=None):
 1463         """A decorator that is used to register custom template test.
 1464         You can specify a name for the test, otherwise the function
 1465         name will be used. Example::
 1466 
 1467           @app.template_test()
 1468           def is_prime(n):
 1469               if n == 2:
 1470                   return True
 1471               for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
 1472                   if n % i == 0:
 1473                       return False
 1474               return True
 1475 
 1476         .. versionadded:: 0.10
 1477 
 1478         :param name: the optional name of the test, otherwise the
 1479                      function name will be used.
 1480         """
 1481 
 1482         def decorator(f):
 1483             self.add_template_test(f, name=name)
 1484             return f
 1485 
 1486         return decorator
 1487 
 1488     @setupmethod
 1489     def add_template_test(self, f, name=None):
 1490         """Register a custom template test.  Works exactly like the
 1491         :meth:`template_test` decorator.
 1492 
 1493         .. versionadded:: 0.10
 1494 
 1495         :param name: the optional name of the test, otherwise the
 1496                      function name will be used.
 1497         """
 1498         self.jinja_env.tests[name or f.__name__] = f
 1499 
 1500     @setupmethod
 1501     def template_global(self, name=None):
 1502         """A decorator that is used to register a custom template global function.
 1503         You can specify a name for the global function, otherwise the function
 1504         name will be used. Example::
 1505 
 1506             @app.template_global()
 1507             def double(n):
 1508                 return 2 * n
 1509 
 1510         .. versionadded:: 0.10
 1511 
 1512         :param name: the optional name of the global function, otherwise the
 1513                      function name will be used.
 1514         """
 1515 
 1516         def decorator(f):
 1517             self.add_template_global(f, name=name)
 1518             return f
 1519 
 1520         return decorator
 1521 
 1522     @setupmethod
 1523     def add_template_global(self, f, name=None):
 1524         """Register a custom template global function. Works exactly like the
 1525         :meth:`template_global` decorator.
 1526 
 1527         .. versionadded:: 0.10
 1528 
 1529         :param name: the optional name of the global function, otherwise the
 1530                      function name will be used.
 1531         """
 1532         self.jinja_env.globals[name or f.__name__] = f
 1533 
 1534     @setupmethod
 1535     def before_request(self, f):
 1536         """Registers a function to run before each request.
 1537 
 1538         For example, this can be used to open a database connection, or to load
 1539         the logged in user from the session.
 1540 
 1541         The function will be called without any arguments. If it returns a
 1542         non-None value, the value is handled as if it was the return value from
 1543         the view, and further request handling is stopped.
 1544         """
 1545         self.before_request_funcs.setdefault(None, []).append(f)
 1546         return f
 1547 
 1548     @setupmethod
 1549     def before_first_request(self, f):
 1550         """Registers a function to be run before the first request to this
 1551         instance of the application.
 1552 
 1553         The function will be called without any arguments and its return
 1554         value is ignored.
 1555 
 1556         .. versionadded:: 0.8
 1557         """
 1558         self.before_first_request_funcs.append(f)
 1559         return f
 1560 
 1561     @setupmethod
 1562     def after_request(self, f):
 1563         """Register a function to be run after each request.
 1564 
 1565         Your function must take one parameter, an instance of
 1566         :attr:`response_class` and return a new response object or the
 1567         same (see :meth:`process_response`).
 1568 
 1569         As of Flask 0.7 this function might not be executed at the end of the
 1570         request in case an unhandled exception occurred.
 1571         """
 1572         self.after_request_funcs.setdefault(None, []).append(f)
 1573         return f
 1574 
 1575     @setupmethod
 1576     def teardown_request(self, f):
 1577         """Register a function to be run at the end of each request,
 1578         regardless of whether there was an exception or not.  These functions
 1579         are executed when the request context is popped, even if not an
 1580         actual request was performed.
 1581 
 1582         Example::
 1583 
 1584             ctx = app.test_request_context()
 1585             ctx.push()
 1586             ...
 1587             ctx.pop()
 1588 
 1589         When ``ctx.pop()`` is executed in the above example, the teardown
 1590         functions are called just before the request context moves from the
 1591         stack of active contexts.  This becomes relevant if you are using
 1592         such constructs in tests.
 1593 
 1594         Generally teardown functions must take every necessary step to avoid
 1595         that they will fail.  If they do execute code that might fail they
 1596         will have to surround the execution of these code by try/except
 1597         statements and log occurring errors.
 1598 
 1599         When a teardown function was called because of an exception it will
 1600         be passed an error object.
 1601 
 1602         The return values of teardown functions are ignored.
 1603 
 1604         .. admonition:: Debug Note
 1605 
 1606            In debug mode Flask will not tear down a request on an exception
 1607            immediately.  Instead it will keep it alive so that the interactive
 1608            debugger can still access it.  This behavior can be controlled
 1609            by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
 1610         """
 1611         self.teardown_request_funcs.setdefault(None, []).append(f)
 1612         return f
 1613 
 1614     @setupmethod
 1615     def teardown_appcontext(self, f):
 1616         """Registers a function to be called when the application context
 1617         ends.  These functions are typically also called when the request
 1618         context is popped.
 1619 
 1620         Example::
 1621 
 1622             ctx = app.app_context()
 1623             ctx.push()
 1624             ...
 1625             ctx.pop()
 1626 
 1627         When ``ctx.pop()`` is executed in the above example, the teardown
 1628         functions are called just before the app context moves from the
 1629         stack of active contexts.  This becomes relevant if you are using
 1630         such constructs in tests.
 1631 
 1632         Since a request context typically also manages an application
 1633         context it would also be called when you pop a request context.
 1634 
 1635         When a teardown function was called because of an unhandled exception
 1636         it will be passed an error object. If an :meth:`errorhandler` is
 1637         registered, it will handle the exception and the teardown will not
 1638         receive it.
 1639 
 1640         The return values of teardown functions are ignored.
 1641 
 1642         .. versionadded:: 0.9
 1643         """
 1644         self.teardown_appcontext_funcs.append(f)
 1645         return f
 1646 
 1647     @setupmethod
 1648     def context_processor(self, f):
 1649         """Registers a template context processor function."""
 1650         self.template_context_processors[None].append(f)
 1651         return f
 1652 
 1653     @setupmethod
 1654     def shell_context_processor(self, f):
 1655         """Registers a shell context processor function.
 1656 
 1657         .. versionadded:: 0.11
 1658         """
 1659         self.shell_context_processors.append(f)
 1660         return f
 1661 
 1662     @setupmethod
 1663     def url_value_preprocessor(self, f):
 1664         """Register a URL value preprocessor function for all view
 1665         functions in the application. These functions will be called before the
 1666         :meth:`before_request` functions.
 1667 
 1668         The function can modify the values captured from the matched url before
 1669         they are passed to the view. For example, this can be used to pop a
 1670         common language code value and place it in ``g`` rather than pass it to
 1671         every view.
 1672 
 1673         The function is passed the endpoint name and values dict. The return
 1674         value is ignored.
 1675         """
 1676         self.url_value_preprocessors.setdefault(None, []).append(f)
 1677         return f
 1678 
 1679     @setupmethod
 1680     def url_defaults(self, f):
 1681         """Callback function for URL defaults for all view functions of the
 1682         application.  It's called with the endpoint and values and should
 1683         update the values passed in place.
 1684         """
 1685         self.url_default_functions.setdefault(None, []).append(f)
 1686         return f
 1687 
 1688     def _find_error_handler(self, e):
 1689         """Return a registered error handler for an exception in this order:
 1690         blueprint handler for a specific code, app handler for a specific code,
 1691         blueprint handler for an exception class, app handler for an exception
 1692         class, or ``None`` if a suitable handler is not found.
 1693         """
 1694         exc_class, code = self._get_exc_class_and_code(type(e))
 1695 
 1696         for name, c in (
 1697             (request.blueprint, code),
 1698             (None, code),
 1699             (request.blueprint, None),
 1700             (None, None),
 1701         ):
 1702             handler_map = self.error_handler_spec.setdefault(name, {}).get(c)
 1703 
 1704             if not handler_map:
 1705                 continue
 1706 
 1707             for cls in exc_class.__mro__:
 1708                 handler = handler_map.get(cls)
 1709 
 1710                 if handler is not None:
 1711                     return handler
 1712 
 1713     def handle_http_exception(self, e):
 1714         """Handles an HTTP exception.  By default this will invoke the
 1715         registered error handlers and fall back to returning the
 1716         exception as response.
 1717 
 1718         .. versionchanged:: 1.0.3
 1719             ``RoutingException``, used internally for actions such as
 1720              slash redirects during routing, is not passed to error
 1721              handlers.
 1722 
 1723         .. versionchanged:: 1.0
 1724             Exceptions are looked up by code *and* by MRO, so
 1725             ``HTTPExcpetion`` subclasses can be handled with a catch-all
 1726             handler for the base ``HTTPException``.
 1727 
 1728         .. versionadded:: 0.3
 1729         """
 1730         # Proxy exceptions don't have error codes.  We want to always return
 1731         # those unchanged as errors
 1732         if e.code is None:
 1733             return e
 1734 
 1735         # RoutingExceptions are used internally to trigger routing
 1736         # actions, such as slash redirects raising RequestRedirect. They
 1737         # are not raised or handled in user code.
 1738         if isinstance(e, RoutingException):
 1739             return e
 1740 
 1741         handler = self._find_error_handler(e)
 1742         if handler is None:
 1743             return e
 1744         return handler(e)
 1745 
 1746     def trap_http_exception(self, e):
 1747         """Checks if an HTTP exception should be trapped or not.  By default
 1748         this will return ``False`` for all exceptions except for a bad request
 1749         key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``.  It
 1750         also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
 1751 
 1752         This is called for all HTTP exceptions raised by a view function.
 1753         If it returns ``True`` for any exception the error handler for this
 1754         exception is not called and it shows up as regular exception in the
 1755         traceback.  This is helpful for debugging implicitly raised HTTP
 1756         exceptions.
 1757 
 1758         .. versionchanged:: 1.0
 1759             Bad request errors are not trapped by default in debug mode.
 1760 
 1761         .. versionadded:: 0.8
 1762         """
 1763         if self.config["TRAP_HTTP_EXCEPTIONS"]:
 1764             return True
 1765 
 1766         trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
 1767 
 1768         # if unset, trap key errors in debug mode
 1769         if (
 1770             trap_bad_request is None
 1771             and self.debug
 1772             and isinstance(e, BadRequestKeyError)
 1773         ):
 1774             return True
 1775 
 1776         if trap_bad_request:
 1777             return isinstance(e, BadRequest)
 1778 
 1779         return False
 1780 
 1781     def handle_user_exception(self, e):
 1782         """This method is called whenever an exception occurs that
 1783         should be handled. A special case is :class:`~werkzeug
 1784         .exceptions.HTTPException` which is forwarded to the
 1785         :meth:`handle_http_exception` method. This function will either
 1786         return a response value or reraise the exception with the same
 1787         traceback.
 1788 
 1789         .. versionchanged:: 1.0
 1790             Key errors raised from request data like ``form`` show the
 1791             bad key in debug mode rather than a generic bad request
 1792             message.
 1793 
 1794         .. versionadded:: 0.7
 1795         """
 1796         exc_type, exc_value, tb = sys.exc_info()
 1797         assert exc_value is e
 1798         # ensure not to trash sys.exc_info() at that point in case someone
 1799         # wants the traceback preserved in handle_http_exception.  Of course
 1800         # we cannot prevent users from trashing it themselves in a custom
 1801         # trap_http_exception method so that's their fault then.
 1802 
 1803         if isinstance(e, BadRequestKeyError):
 1804             if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:
 1805                 e.show_exception = True
 1806 
 1807                 # Werkzeug < 0.15 doesn't add the KeyError to the 400
 1808                 # message, add it in manually.
 1809                 # TODO: clean up once Werkzeug >= 0.15.5 is required
 1810                 if e.args[0] not in e.get_description():
 1811                     e.description = "KeyError: '{}'".format(*e.args)
 1812             elif not hasattr(BadRequestKeyError, "show_exception"):
 1813                 e.args = ()
 1814 
 1815         if isinstance(e, HTTPException) and not self.trap_http_exception(e):
 1816             return self.handle_http_exception(e)
 1817 
 1818         handler = self._find_error_handler(e)
 1819 
 1820         if handler is None:
 1821             reraise(exc_type, exc_value, tb)
 1822         return handler(e)
 1823 
 1824     def handle_exception(self, e):
 1825         """Handle an exception that did not have an error handler
 1826         associated with it, or that was raised from an error handler.
 1827         This always causes a 500 ``InternalServerError``.
 1828 
 1829         Always sends the :data:`got_request_exception` signal.
 1830 
 1831         If :attr:`propagate_exceptions` is ``True``, such as in debug
 1832         mode, the error will be re-raised so that the debugger can
 1833         display it. Otherwise, the original exception is logged, and
 1834         an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
 1835 
 1836         If an error handler is registered for ``InternalServerError`` or
 1837         ``500``, it will be used. For consistency, the handler will
 1838         always receive the ``InternalServerError``. The original
 1839         unhandled exception is available as ``e.original_exception``.
 1840 
 1841         .. note::
 1842             Prior to Werkzeug 1.0.0, ``InternalServerError`` will not
 1843             always have an ``original_exception`` attribute. Use
 1844             ``getattr(e, "original_exception", None)`` to simulate the
 1845             behavior for compatibility.
 1846 
 1847         .. versionchanged:: 1.1.0
 1848             Always passes the ``InternalServerError`` instance to the
 1849             handler, setting ``original_exception`` to the unhandled
 1850             error.
 1851 
 1852         .. versionchanged:: 1.1.0
 1853             ``after_request`` functions and other finalization is done
 1854             even for the default 500 response when there is no handler.
 1855 
 1856         .. versionadded:: 0.3
 1857         """
 1858         exc_type, exc_value, tb = sys.exc_info()
 1859         got_request_exception.send(self, exception=e)
 1860 
 1861         if self.propagate_exceptions:
 1862             # if we want to repropagate the exception, we can attempt to
 1863             # raise it with the whole traceback in case we can do that
 1864             # (the function was actually called from the except part)
 1865             # otherwise, we just raise the error again
 1866             if exc_value is e:
 1867                 reraise(exc_type, exc_value, tb)
 1868             else:
 1869                 raise e
 1870 
 1871         self.log_exception((exc_type, exc_value, tb))
 1872         server_error = InternalServerError()
 1873         # TODO: pass as param when Werkzeug>=1.0.0 is required
 1874         # TODO: also remove note about this from docstring and docs
 1875         server_error.original_exception = e
 1876         handler = self._find_error_handler(server_error)
 1877 
 1878         if handler is not None:
 1879             server_error = handler(server_error)
 1880 
 1881         return self.finalize_request(server_error, from_error_handler=True)
 1882 
 1883     def log_exception(self, exc_info):
 1884         """Logs an exception.  This is called by :meth:`handle_exception`
 1885         if debugging is disabled and right before the handler is called.
 1886         The default implementation logs the exception as error on the
 1887         :attr:`logger`.
 1888 
 1889         .. versionadded:: 0.8
 1890         """
 1891         self.logger.error(
 1892             "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info
 1893         )
 1894 
 1895     def raise_routing_exception(self, request):
 1896         """Exceptions that are recording during routing are reraised with
 1897         this method.  During debug we are not reraising redirect requests
 1898         for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
 1899         a different error instead to help debug situations.
 1900 
 1901         :internal:
 1902         """
 1903         if (
 1904             not self.debug
 1905             or not isinstance(request.routing_exception, RequestRedirect)
 1906             or request.method in ("GET", "HEAD", "OPTIONS")
 1907         ):
 1908             raise request.routing_exception
 1909 
 1910         from .debughelpers import FormDataRoutingRedirect
 1911 
 1912         raise FormDataRoutingRedirect(request)
 1913 
 1914     def dispatch_request(self):
 1915         """Does the request dispatching.  Matches the URL and returns the
 1916         return value of the view or error handler.  This does not have to
 1917         be a response object.  In order to convert the return value to a
 1918         proper response object, call :func:`make_response`.
 1919 
 1920         .. versionchanged:: 0.7
 1921            This no longer does the exception handling, this code was
 1922            moved to the new :meth:`full_dispatch_request`.
 1923         """
 1924         req = _request_ctx_stack.top.request
 1925         if req.routing_exception is not None:
 1926             self.raise_routing_exception(req)
 1927         rule = req.url_rule
 1928         # if we provide automatic options for this URL and the
 1929         # request came with the OPTIONS method, reply automatically
 1930         if (
 1931             getattr(rule, "provide_automatic_options", False)
 1932             and req.method == "OPTIONS"
 1933         ):
 1934             return self.make_default_options_response()
 1935         # otherwise dispatch to the handler for that endpoint
 1936         return self.view_functions[rule.endpoint](**req.view_args)
 1937 
 1938     def full_dispatch_request(self):
 1939         """Dispatches the request and on top of that performs request
 1940         pre and postprocessing as well as HTTP exception catching and
 1941         error handling.
 1942 
 1943         .. versionadded:: 0.7
 1944         """
 1945         self.try_trigger_before_first_request_functions()
 1946         try:
 1947             request_started.send(self)
 1948             rv = self.preprocess_request()
 1949             if rv is None:
 1950                 rv = self.dispatch_request()
 1951         except Exception as e:
 1952             rv = self.handle_user_exception(e)
 1953         return self.finalize_request(rv)
 1954 
 1955     def finalize_request(self, rv, from_error_handler=False):
 1956         """Given the return value from a view function this finalizes
 1957         the request by converting it into a response and invoking the
 1958         postprocessing functions.  This is invoked for both normal
 1959         request dispatching as well as error handlers.
 1960 
 1961         Because this means that it might be called as a result of a
 1962         failure a special safe mode is available which can be enabled
 1963         with the `from_error_handler` flag.  If enabled, failures in
 1964         response processing will be logged and otherwise ignored.
 1965 
 1966         :internal:
 1967         """
 1968         response = self.make_response(rv)
 1969         try:
 1970             response = self.process_response(response)
 1971             request_finished.send(self, response=response)
 1972         except Exception:
 1973             if not from_error_handler:
 1974                 raise
 1975             self.logger.exception(
 1976                 "Request finalizing failed with an error while handling an error"
 1977             )
 1978         return response
 1979 
 1980     def try_trigger_before_first_request_functions(self):
 1981         """Called before each request and will ensure that it triggers
 1982         the :attr:`before_first_request_funcs` and only exactly once per
 1983         application instance (which means process usually).
 1984 
 1985         :internal:
 1986         """
 1987         if self._got_first_request:
 1988             return
 1989         with self._before_request_lock:
 1990             if self._got_first_request:
 1991                 return
 1992             for func in self.before_first_request_funcs:
 1993                 func()
 1994             self._got_first_request = True
 1995 
 1996     def make_default_options_response(self):
 1997         """This method is called to create the default ``OPTIONS`` response.
 1998         This can be changed through subclassing to change the default
 1999         behavior of ``OPTIONS`` responses.
 2000 
 2001         .. versionadded:: 0.7
 2002         """
 2003         adapter = _request_ctx_stack.top.url_adapter
 2004         if hasattr(adapter, "allowed_methods"):
 2005             methods = adapter.allowed_methods()
 2006         else:
 2007             # fallback for Werkzeug < 0.7
 2008             methods = []
 2009             try:
 2010                 adapter.match(method="--")
 2011             except MethodNotAllowed as e:
 2012                 methods = e.valid_methods
 2013             except HTTPException:
 2014                 pass
 2015         rv = self.response_class()
 2016         rv.allow.update(methods)
 2017         return rv
 2018 
 2019     def should_ignore_error(self, error):
 2020         """This is called to figure out if an error should be ignored
 2021         or not as far as the teardown system is concerned.  If this
 2022         function returns ``True`` then the teardown handlers will not be
 2023         passed the error.
 2024 
 2025         .. versionadded:: 0.10
 2026         """
 2027         return False
 2028 
 2029     def make_response(self, rv):
 2030         """Convert the return value from a view function to an instance of
 2031         :attr:`response_class`.
 2032 
 2033         :param rv: the return value from the view function. The view function
 2034             must return a response. Returning ``None``, or the view ending
 2035             without returning, is not allowed. The following types are allowed
 2036             for ``view_rv``:
 2037 
 2038             ``str`` (``unicode`` in Python 2)
 2039                 A response object is created with the string encoded to UTF-8
 2040                 as the body.
 2041 
 2042             ``bytes`` (``str`` in Python 2)
 2043                 A response object is created with the bytes as the body.
 2044 
 2045             ``dict``
 2046                 A dictionary that will be jsonify'd before being returned.
 2047 
 2048             ``tuple``
 2049                 Either ``(body, status, headers)``, ``(body, status)``, or
 2050                 ``(body, headers)``, where ``body`` is any of the other types
 2051                 allowed here, ``status`` is a string or an integer, and
 2052                 ``headers`` is a dictionary or a list of ``(key, value)``
 2053                 tuples. If ``body`` is a :attr:`response_class` instance,
 2054                 ``status`` overwrites the exiting value and ``headers`` are
 2055                 extended.
 2056 
 2057             :attr:`response_class`
 2058                 The object is returned unchanged.
 2059 
 2060             other :class:`~werkzeug.wrappers.Response` class
 2061                 The object is coerced to :attr:`response_class`.
 2062 
 2063             :func:`callable`
 2064                 The function is called as a WSGI application. The result is
 2065                 used to create a response object.
 2066 
 2067         .. versionchanged:: 0.9
 2068            Previously a tuple was interpreted as the arguments for the
 2069            response object.
 2070         """
 2071 
 2072         status = headers = None
 2073 
 2074         # unpack tuple returns
 2075         if isinstance(rv, tuple):
 2076             len_rv = len(rv)
 2077 
 2078             # a 3-tuple is unpacked directly
 2079             if len_rv == 3:
 2080                 rv, status, headers = rv
 2081             # decide if a 2-tuple has status or headers
 2082             elif len_rv == 2:
 2083                 if isinstance(rv[1], (Headers, dict, tuple, list)):
 2084                     rv, headers = rv
 2085                 else:
 2086                     rv, status = rv
 2087             # other sized tuples are not allowed
 2088             else:
 2089                 raise TypeError(
 2090                     "The view function did not return a valid response tuple."
 2091                     " The tuple must have the form (body, status, headers),"
 2092                     " (body, status), or (body, headers)."
 2093                 )
 2094 
 2095         # the body must not be None
 2096         if rv is None:
 2097             raise TypeError(
 2098                 "The view function did not return a valid response. The"
 2099                 " function either returned None or ended without a return"
 2100                 " statement."
 2101             )
 2102 
 2103         # make sure the body is an instance of the response class
 2104         if not isinstance(rv, self.response_class):
 2105             if isinstance(rv, (text_type, bytes, bytearray)):
 2106                 # let the response class set the status and headers instead of
 2107                 # waiting to do it manually, so that the class can handle any
 2108                 # special logic
 2109                 rv = self.response_class(rv, status=status, headers=headers)
 2110                 status = headers = None
 2111             elif isinstance(rv, dict):
 2112                 rv = jsonify(rv)
 2113             elif isinstance(rv, BaseResponse) or callable(rv):
 2114                 # evaluate a WSGI callable, or coerce a different response
 2115                 # class to the correct type
 2116                 try:
 2117                     rv = self.response_class.force_type(rv, request.environ)
 2118                 except TypeError as e:
 2119                     new_error = TypeError(
 2120                         "{e}\nThe view function did not return a valid"
 2121                         " response. The return type must be a string, dict, tuple,"
 2122                         " Response instance, or WSGI callable, but it was a"
 2123                         " {rv.__class__.__name__}.".format(e=e, rv=rv)
 2124                     )
 2125                     reraise(TypeError, new_error, sys.exc_info()[2])
 2126             else:
 2127                 raise TypeError(
 2128                     "The view function did not return a valid"
 2129                     " response. The return type must be a string, dict, tuple,"
 2130                     " Response instance, or WSGI callable, but it was a"
 2131                     " {rv.__class__.__name__}.".format(rv=rv)
 2132                 )
 2133 
 2134         # prefer the status if it was provided
 2135         if status is not None:
 2136             if isinstance(status, (text_type, bytes, bytearray)):
 2137                 rv.status = status
 2138             else:
 2139                 rv.status_code = status
 2140 
 2141         # extend existing headers with provided headers
 2142         if headers:
 2143             rv.headers.extend(headers)
 2144 
 2145         return rv
 2146 
 2147     def create_url_adapter(self, request):
 2148         """Creates a URL adapter for the given request. The URL adapter
 2149         is created at a point where the request context is not yet set
 2150         up so the request is passed explicitly.
 2151 
 2152         .. versionadded:: 0.6
 2153 
 2154         .. versionchanged:: 0.9
 2155            This can now also be called without a request object when the
 2156            URL adapter is created for the application context.
 2157 
 2158         .. versionchanged:: 1.0
 2159             :data:`SERVER_NAME` no longer implicitly enables subdomain
 2160             matching. Use :attr:`subdomain_matching` instead.
 2161         """
 2162         if request is not None:
 2163             # If subdomain matching is disabled (the default), use the
 2164             # default subdomain in all cases. This should be the default
 2165             # in Werkzeug but it currently does not have that feature.
 2166             subdomain = (
 2167                 (self.url_map.default_subdomain or None)
 2168                 if not self.subdomain_matching
 2169                 else None
 2170             )
 2171             return self.url_map.bind_to_environ(
 2172                 request.environ,
 2173                 server_name=self.config["SERVER_NAME"],
 2174                 subdomain=subdomain,
 2175             )
 2176         # We need at the very least the server name to be set for this
 2177         # to work.
 2178         if self.config["SERVER_NAME"] is not None:
 2179             return self.url_map.bind(
 2180                 self.config["SERVER_NAME"],
 2181                 script_name=self.config["APPLICATION_ROOT"],
 2182                 url_scheme=self.config["PREFERRED_URL_SCHEME"],
 2183             )
 2184 
 2185     def inject_url_defaults(self, endpoint, values):
 2186         """Injects the URL defaults for the given endpoint directly into
 2187         the values dictionary passed.  This is used internally and
 2188         automatically called on URL building.
 2189 
 2190         .. versionadded:: 0.7
 2191         """
 2192         funcs = self.url_default_functions.get(None, ())
 2193         if "." in endpoint:
 2194             bp = endpoint.rsplit(".", 1)[0]
 2195             funcs = chain(funcs, self.url_default_functions.get(bp, ()))
 2196         for func in funcs:
 2197             func(endpoint, values)
 2198 
 2199     def handle_url_build_error(self, error, endpoint, values):
 2200         """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
 2201         """
 2202         exc_type, exc_value, tb = sys.exc_info()
 2203         for handler in self.url_build_error_handlers:
 2204             try:
 2205                 rv = handler(error, endpoint, values)
 2206                 if rv is not None:
 2207                     return rv
 2208             except BuildError as e:
 2209                 # make error available outside except block (py3)
 2210                 error = e
 2211 
 2212         # At this point we want to reraise the exception.  If the error is
 2213         # still the same one we can reraise it with the original traceback,
 2214         # otherwise we raise it from here.
 2215         if error is exc_value:
 2216             reraise(exc_type, exc_value, tb)
 2217         raise error
 2218 
 2219     def preprocess_request(self):
 2220         """Called before the request is dispatched. Calls
 2221         :attr:`url_value_preprocessors` registered with the app and the
 2222         current blueprint (if any). Then calls :attr:`before_request_funcs`
 2223         registered with the app and the blueprint.
 2224 
 2225         If any :meth:`before_request` handler returns a non-None value, the
 2226         value is handled as if it was the return value from the view, and
 2227         further request handling is stopped.
 2228         """
 2229 
 2230         bp = _request_ctx_stack.top.request.blueprint
 2231 
 2232         funcs = self.url_value_preprocessors.get(None, ())
 2233         if bp is not None and bp in self.url_value_preprocessors:
 2234             funcs = chain(funcs, self.url_value_preprocessors[bp])
 2235         for func in funcs:
 2236             func(request.endpoint, request.view_args)
 2237 
 2238         funcs = self.before_request_funcs.get(None, ())
 2239         if bp is not None and bp in self.before_request_funcs:
 2240             funcs = chain(funcs, self.before_request_funcs[bp])
 2241         for func in funcs:
 2242             rv = func()
 2243             if rv is not None:
 2244                 return rv
 2245 
 2246     def process_response(self, response):
 2247         """Can be overridden in order to modify the response object
 2248         before it's sent to the WSGI server.  By default this will
 2249         call all the :meth:`after_request` decorated functions.
 2250 
 2251         .. versionchanged:: 0.5
 2252            As of Flask 0.5 the functions registered for after request
 2253            execution are called in reverse order of registration.
 2254 
 2255         :param response: a :attr:`response_class` object.
 2256         :return: a new response object or the same, has to be an
 2257                  instance of :attr:`response_class`.
 2258         """
 2259         ctx = _request_ctx_stack.top
 2260         bp = ctx.request.blueprint
 2261         funcs = ctx._after_request_functions
 2262         if bp is not None and bp in self.after_request_funcs:
 2263             funcs = chain(funcs, reversed(self.after_request_funcs[bp]))
 2264         if None in self.after_request_funcs:
 2265             funcs = chain(funcs, reversed(self.after_request_funcs[None]))
 2266         for handler in funcs:
 2267             response = handler(response)
 2268         if not self.session_interface.is_null_session(ctx.session):
 2269             self.session_interface.save_session(self, ctx.session, response)
 2270         return response
 2271 
 2272     def do_teardown_request(self, exc=_sentinel):
 2273         """Called after the request is dispatched and the response is
 2274         returned, right before the request context is popped.
 2275 
 2276         This calls all functions decorated with
 2277         :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
 2278         if a blueprint handled the request. Finally, the
 2279         :data:`request_tearing_down` signal is sent.
 2280 
 2281         This is called by
 2282         :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
 2283         which may be delayed during testing to maintain access to
 2284         resources.
 2285 
 2286         :param exc: An unhandled exception raised while dispatching the
 2287             request. Detected from the current exception information if
 2288             not passed. Passed to each teardown function.
 2289 
 2290         .. versionchanged:: 0.9
 2291             Added the ``exc`` argument.
 2292         """
 2293         if exc is _sentinel:
 2294             exc = sys.exc_info()[1]
 2295         funcs = reversed(self.teardown_request_funcs.get(None, ()))
 2296         bp = _request_ctx_stack.top.request.blueprint
 2297         if bp is not None and bp in self.teardown_request_funcs:
 2298             funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))
 2299         for func in funcs:
 2300             func(exc)
 2301         request_tearing_down.send(self, exc=exc)
 2302 
 2303     def do_teardown_appcontext(self, exc=_sentinel):
 2304         """Called right before the application context is popped.
 2305 
 2306         When handling a request, the application context is popped
 2307         after the request context. See :meth:`do_teardown_request`.
 2308 
 2309         This calls all functions decorated with
 2310         :meth:`teardown_appcontext`. Then the
 2311         :data:`appcontext_tearing_down` signal is sent.
 2312 
 2313         This is called by
 2314         :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
 2315 
 2316         .. versionadded:: 0.9
 2317         """
 2318         if exc is _sentinel:
 2319             exc = sys.exc_info()[1]
 2320         for func in reversed(self.teardown_appcontext_funcs):
 2321             func(exc)
 2322         appcontext_tearing_down.send(self, exc=exc)
 2323 
 2324     def app_context(self):
 2325         """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
 2326         block to push the context, which will make :data:`current_app`
 2327         point at this application.
 2328 
 2329         An application context is automatically pushed by
 2330         :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
 2331         when handling a request, and when running a CLI command. Use
 2332         this to manually create a context outside of these situations.
 2333 
 2334         ::
 2335 
 2336             with app.app_context():
 2337                 init_db()
 2338 
 2339         See :doc:`/appcontext`.
 2340 
 2341         .. versionadded:: 0.9
 2342         """
 2343         return AppContext(self)
 2344 
 2345     def request_context(self, environ):
 2346         """Create a :class:`~flask.ctx.RequestContext` representing a
 2347         WSGI environment. Use a ``with`` block to push the context,
 2348         which will make :data:`request` point at this request.
 2349 
 2350         See :doc:`/reqcontext`.
 2351 
 2352         Typically you should not call this from your own code. A request
 2353         context is automatically pushed by the :meth:`wsgi_app` when
 2354         handling a request. Use :meth:`test_request_context` to create
 2355         an environment and context instead of this method.
 2356 
 2357         :param environ: a WSGI environment
 2358         """
 2359         return RequestContext(self, environ)
 2360 
 2361     def test_request_context(self, *args, **kwargs):
 2362         """Create a :class:`~flask.ctx.RequestContext` for a WSGI
 2363         environment created from the given values. This is mostly useful
 2364         during testing, where you may want to run a function that uses
 2365         request data without dispatching a full request.
 2366 
 2367         See :doc:`/reqcontext`.
 2368 
 2369         Use a ``with`` block to push the context, which will make
 2370         :data:`request` point at the request for the created
 2371         environment. ::
 2372 
 2373             with test_request_context(...):
 2374                 generate_report()
 2375 
 2376         When using the shell, it may be easier to push and pop the
 2377         context manually to avoid indentation. ::
 2378 
 2379             ctx = app.test_request_context(...)
 2380             ctx.push()
 2381             ...
 2382             ctx.pop()
 2383 
 2384         Takes the same arguments as Werkzeug's
 2385         :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
 2386         the application. See the linked Werkzeug docs for most of the
 2387         available arguments. Flask-specific behavior is listed here.
 2388 
 2389         :param path: URL path being requested.
 2390         :param base_url: Base URL where the app is being served, which
 2391             ``path`` is relative to. If not given, built from
 2392             :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
 2393             :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
 2394         :param subdomain: Subdomain name to append to
 2395             :data:`SERVER_NAME`.
 2396         :param url_scheme: Scheme to use instead of
 2397             :data:`PREFERRED_URL_SCHEME`.
 2398         :param data: The request body, either as a string or a dict of
 2399             form keys and values.
 2400         :param json: If given, this is serialized as JSON and passed as
 2401             ``data``. Also defaults ``content_type`` to
 2402             ``application/json``.
 2403         :param args: other positional arguments passed to
 2404             :class:`~werkzeug.test.EnvironBuilder`.
 2405         :param kwargs: other keyword arguments passed to
 2406             :class:`~werkzeug.test.EnvironBuilder`.
 2407         """
 2408         from .testing import EnvironBuilder
 2409 
 2410         builder = EnvironBuilder(self, *args, **kwargs)
 2411 
 2412         try:
 2413             return self.request_context(builder.get_environ())
 2414         finally:
 2415             builder.close()
 2416 
 2417     def wsgi_app(self, environ, start_response):
 2418         """The actual WSGI application. This is not implemented in
 2419         :meth:`__call__` so that middlewares can be applied without
 2420         losing a reference to the app object. Instead of doing this::
 2421 
 2422             app = MyMiddleware(app)
 2423 
 2424         It's a better idea to do this instead::
 2425 
 2426             app.wsgi_app = MyMiddleware(app.wsgi_app)
 2427 
 2428         Then you still have the original application object around and
 2429         can continue to call methods on it.
 2430 
 2431         .. versionchanged:: 0.7
 2432             Teardown events for the request and app contexts are called
 2433             even if an unhandled error occurs. Other events may not be
 2434             called depending on when an error occurs during dispatch.
 2435             See :ref:`callbacks-and-errors`.
 2436 
 2437         :param environ: A WSGI environment.
 2438         :param start_response: A callable accepting a status code,
 2439             a list of headers, and an optional exception context to
 2440             start the response.
 2441         """
 2442         ctx = self.request_context(environ)
 2443         error = None
 2444         try:
 2445             try:
 2446                 ctx.push()
 2447                 response = self.full_dispatch_request()
 2448             except Exception as e:
 2449                 error = e
 2450                 response = self.handle_exception(e)
 2451             except:  # noqa: B001
 2452                 error = sys.exc_info()[1]
 2453                 raise
 2454             return response(environ, start_response)
 2455         finally:
 2456             if self.should_ignore_error(error):
 2457                 error = None
 2458             ctx.auto_pop(error)
 2459 
 2460     def __call__(self, environ, start_response):
 2461         """The WSGI server calls the Flask application object as the
 2462         WSGI application. This calls :meth:`wsgi_app` which can be
 2463         wrapped to applying middleware."""
 2464         return self.wsgi_app(environ, start_response)
 2465 
 2466     def __repr__(self):
 2467         return "<%s %r>" % (self.__class__.__name__, self.name)