Format: application/x-python-code
⬇ Download File (49.7 KB)
   1  o
   2  
   3  D'h��@sddlmZddlmZddlZddlZddlZddl	Z	ddl
   4  mZddlm
   5  Z
   6  ddlmZddlmZddlmZddlZddlmZdd	lmZdd
   7  lmZddlmZddlmZdd
   8  lmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$ddl%m&Z'ddl(m)Z)ddl*m+Z+ddl*mZ,ddl-m.Z.ddl-m/Z/ddl0m1Z1ddl0m2Z2ddl0m3Z3ddl0m4Z4ddl0m5Z5ddl0m6Z6dd l0m7Z7dd!l8m9Z9dd"l8m:Z:dd#l8m;Z;dd$l8m<Z<dd%l=m>Z>dd&l?m@Z@dd'lAmBZBdd(lAmCZCdd)lDmEZEdd*lDmFZFdd+lDmGZGdd,lDmHZHdd-lDmIZIdd.lJmKZKdd/lLmMZMddlLm&Z&ejN�rPdd0lOmPZPdd1lOmQZQdd2lRmSZSdd3lRmTZTdd4lmUZUejVd5e,jWd6�ZXejVd7e,jYd6�ZZejVd8e,j[d6�Z\ejVd9e,j]d6�Z^ejVd:e,j_d6�Z`dCd?d@�ZaGdAdB�dBe>�ZbdS)D�)�annotationsN)�	timedelta)�iscoroutinefunction)�chain)�
   9  TracebackType)�quote)�Headers)�
  10  ImmutableDict)�BadRequestKeyError)�
  11  HTTPException)�InternalServerError)�
  12  BuildError)�
  13  MapAdapter)�RequestRedirect)�RoutingException)�Rule)�is_running_from_reloader)�Response)�get_host�)�cli)�typing��
  14  AppContext��RequestContext)�_cv_app)�_cv_request)�current_app)�g)�request)�request_ctx)�session)�get_debug_flag)�get_flashed_messages)�get_load_dotenv)�send_from_directory)�App)�	_sentinel)�SecureCookieSessionInterface)�SessionInterface)�appcontext_tearing_down)�got_request_exception)�request_finished)�request_started)�request_tearing_down)�Environment)�Request)�
  15  StartResponse)�WSGIEnvironment��FlaskClient��FlaskCliRunner)�HeadersValue�T_shell_context_processor)�bound�
  16  T_teardown�T_template_filter�T_template_global�T_template_test�value�timedelta | int | None�return�timedelta | NonecCs |dus	t|t�r|St|d�S)N)�seconds)�
  17  isinstancer)r?�rE�?C:\Users\shubh\Videos\agent\nova\Lib\site-packages\flask/app.py�_make_timedeltaJs
  18  rGcsfeZdZUdZeidd�dd�dd�dd�dd�d	ed
  19  d��dd�d
  20  d�dd�dd�dd�dd�dd�dd�dd�dd�dd�ddddddddddddd���ZeZde	d <e
  21  Zd!e	d"<e�Z
  22  d#e	d$<		%				&			d�d��fd5d6�
  23  Zd�d:d;�Zd�d=d>�Z	d�d�dDdE�Z	Fd�d�dGdH�Zd�dJdK�Zd�dOdP�Zd�dSdT�Zd�dXdY�Zd�dZd[�Z				d�d�dcdd�Zd�d�dhdi�Zd�dkdl�Zd�dpdq�Zd�dsdt�Zd�dudv�Zd�dydz�Zd�d|d}�Zd�d~d�Z 	d�d�d�d��Z!d�d�d��Z"d�d�d��Z#d�d�d��Z$ddddd��d�d�d��Z%d�d�d��Z&d�d�d��Z'd�d�d��Z(e)fd�d�d��Z*e)fd�d�d��Z+d�d�d��Z,d�d�d��Z-d�d�d��Z.d�d�d��Z/d�d�d��Z0�Z1S)��Flaska�The flask object implements a WSGI application and acts as the central
  24      object.  It is passed the name of the module or package of the
  25      application.  Once it is created it will act as a central registry for
  26      the view functions, the URL rules, template configuration and much more.
  27  
  28      The name of the package is used to resolve resources from inside the
  29      package or the folder the module is contained in depending on if the
  30      package parameter resolves to an actual python package (a folder with
  31      an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
  32  
  33      For more information about resource loading, see :func:`open_resource`.
  34  
  35      Usually you create a :class:`Flask` instance in your main module or
  36      in the :file:`__init__.py` file of your package like this::
  37  
  38          from flask import Flask
  39          app = Flask(__name__)
  40  
  41      .. admonition:: About the First Parameter
  42  
  43          The idea of the first parameter is to give Flask an idea of what
  44          belongs to your application.  This name is used to find resources
  45          on the filesystem, can be used by extensions to improve debugging
  46          information and a lot more.
  47  
  48          So it's important what you provide there.  If you are using a single
  49          module, `__name__` is always the correct value.  If you however are
  50          using a package, it's usually recommended to hardcode the name of
  51          your package there.
  52  
  53          For example if your application is defined in :file:`yourapplication/app.py`
  54          you should create it with one of the two versions below::
  55  
  56              app = Flask('yourapplication')
  57              app = Flask(__name__.split('.')[0])
  58  
  59          Why is that?  The application will work even with `__name__`, thanks
  60          to how resources are looked up.  However it will make debugging more
  61          painful.  Certain extensions can make assumptions based on the
  62          import name of your application.  For example the Flask-SQLAlchemy
  63          extension will look for the code in your application that triggered
  64          an SQL query in debug mode.  If the import name is not properly set
  65          up, that debugging information is lost.  (For example it would only
  66          pick up SQL queries in `yourapplication.app` and not
  67          `yourapplication.views.frontend`)
  68  
  69      .. versionadded:: 0.7
  70         The `static_url_path`, `static_folder`, and `template_folder`
  71         parameters were added.
  72  
  73      .. versionadded:: 0.8
  74         The `instance_path` and `instance_relative_config` parameters were
  75         added.
  76  
  77      .. versionadded:: 0.11
  78         The `root_path` parameter was added.
  79  
  80      .. versionadded:: 1.0
  81         The ``host_matching`` and ``static_host`` parameters were added.
  82  
  83      .. versionadded:: 1.0
  84         The ``subdomain_matching`` parameter was added. Subdomain
  85         matching needs to be enabled manually now. Setting
  86         :data:`SERVER_NAME` does not implicitly enable it.
  87  
  88      :param import_name: the name of the application package
  89      :param static_url_path: can be used to specify a different path for the
  90                              static files on the web.  Defaults to the name
  91                              of the `static_folder` folder.
  92      :param static_folder: The folder with static files that is served at
  93          ``static_url_path``. Relative to the application ``root_path``
  94          or an absolute path. Defaults to ``'static'``.
  95      :param static_host: the host to use when adding the static route.
  96          Defaults to None. Required when using ``host_matching=True``
  97          with a ``static_folder`` configured.
  98      :param host_matching: set ``url_map.host_matching`` attribute.
  99          Defaults to False.
 100      :param subdomain_matching: consider the subdomain relative to
 101          :data:`SERVER_NAME` when matching routes. Defaults to False.
 102      :param template_folder: the folder that contains the templates that should
 103                              be used by the application.  Defaults to
 104                              ``'templates'`` folder in the root path of the
 105                              application.
 106      :param instance_path: An alternative instance path for the application.
 107                            By default the folder ``'instance'`` next to the
 108                            package or module is assumed to be the instance
 109                            path.
 110      :param instance_relative_config: if set to ``True`` relative filenames
 111                                       for loading the config are assumed to
 112                                       be relative to the instance path instead
 113                                       of the application root.
 114      :param root_path: The path to the root of the application files.
 115          This should only be set manually when it can't be detected
 116          automatically, such as for namespace packages.
 117      �DEBUGNZTESTINGF�PROPAGATE_EXCEPTIONSZ
 118  SECRET_KEYZSECRET_KEY_FALLBACKSZPERMANENT_SESSION_LIFETIME�)�daysZUSE_X_SENDFILE�
 119  TRUSTED_HOSTS�SERVER_NAME�APPLICATION_ROOT�/ZSESSION_COOKIE_NAMEr"ZSESSION_COOKIE_DOMAINZSESSION_COOKIE_PATHZSESSION_COOKIE_HTTPONLYTZSESSION_COOKIE_SECUREZSESSION_COOKIE_PARTITIONEDZSESSION_COOKIE_SAMESITEi �i��httpi�)ZSESSION_REFRESH_EACH_REQUESTZMAX_CONTENT_LENGTHZMAX_FORM_MEMORY_SIZEZMAX_FORM_PARTS�SEND_FILE_MAX_AGE_DEFAULT�TRAP_BAD_REQUEST_ERRORSZTRAP_HTTP_EXCEPTIONSZEXPLAIN_TEMPLATE_LOADING�PREFERRED_URL_SCHEME�TEMPLATES_AUTO_RELOADZMAX_COOKIE_SIZEZPROVIDE_AUTOMATIC_OPTIONSz
 120  type[Request]�
 121  request_classztype[Response]�response_classr*�session_interface�static�	templates�import_name�str�static_url_path�
 122  str | None�
 123  static_folder�str | os.PathLike[str] | None�static_host�
 124  host_matching�bool�subdomain_matching�template_folder�
 125  instance_path�instance_relative_config�	root_pathcs�t�j|||||||||	|
 126  d�
 127  t��|_|j|j_|jr?t|�|ks'Jd��t�|��|j	|j
 128  �d�d|�fdd�d�dSdS)N)
 129  r[r]r_rarbrdrerfrgrhz-Invalid static_host/host_matching combinationz/<path:filename>rYcs��jdi|��S)NrE)�send_static_file)�kw�Zself_refrErF�<lambda>sz Flask.__init__.<locals>.<lambda>)�endpoint�hostZ	view_func)�super�__init__rZAppGroup�name�has_static_folderrc�weakref�refZadd_url_ruler])�selfr[r]r_rarbrdrerfrgrh��	__class__rkrFrp�s4
 130  �
 131  
 132  �
 133  
 134  
 135  
 136  ��zFlask.__init__�filenamerA�
 137  int | NonecCs0tjd}|durdSt|t�rt|���S|S)anUsed by :func:`send_file` to determine the ``max_age`` cache
 138          value for a given file path if it wasn't passed.
 139  
 140          By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
 141          the configuration of :data:`~flask.current_app`. This defaults
 142          to ``None``, which tells the browser to use conditional requests
 143          instead of a timed cache, which is usually preferable.
 144  
 145          Note this is a duplicate of the same method in the Flask
 146          class.
 147  
 148          .. versionchanged:: 2.0
 149              The default configuration is ``None`` instead of 12 hours.
 150  
 151          .. versionadded:: 0.9
 152          rRN)r�configrDr�int�
 153  total_seconds)rurxr?rErErF�get_send_file_max_ages
 154  
 155  zFlask.get_send_file_max_agercCs0|jstd��|�|�}tt�t|j�||d�S)aAThe view function used to serve files from
 156          :attr:`static_folder`. A route is automatically registered for
 157          this view at :attr:`static_url_path` if :attr:`static_folder` is
 158          set.
 159  
 160          Note this is a duplicate of the same method in the Flask
 161          class.
 162  
 163          .. versionadded:: 0.5
 164  
 165          z2'static_folder' must be set to serve static_files.)�max_age)rr�RuntimeErrorr}r&�t�castr\r_)rurxr~rErErFri4s
 166  �zFlask.send_static_file�rb�resource�mode�encoding�t.IO[t.AnyStr]cCs@|dvrtd��tj�|j|�}|dkrt||�St|||d�S)a Open a resource file relative to :attr:`root_path` for reading.
 167  
 168          For example, if the file ``schema.sql`` is next to the file
 169          ``app.py`` where the ``Flask`` app is defined, it can be opened
 170          with:
 171  
 172          .. code-block:: python
 173  
 174              with app.open_resource("schema.sql") as f:
 175                  conn.executescript(f.read())
 176  
 177          :param resource: Path to the resource relative to :attr:`root_path`.
 178          :param mode: Open the file in this mode. Only reading is supported,
 179              valid values are ``"r"`` (or ``"rt"``) and ``"rb"``.
 180          :param encoding: Open the file with this encoding when opening in text
 181              mode. This is ignored when opening in binary mode.
 182  
 183          .. versionchanged:: 3.1
 184              Added the ``encoding`` parameter.
 185          >�rr��rtz)Resources can only be opened for reading.r��r�)�
 186  ValueError�os�path�joinrh�open�rur�r�r�r�rErErF�
 187  open_resourceJs
 188  zFlask.open_resource�utf-8cCs0tj�|j|�}d|vrt||�St|||d�S)a(Open a resource file relative to the application's instance folder
 189          :attr:`instance_path`. Unlike :meth:`open_resource`, files in the
 190          instance folder can be opened for writing.
 191  
 192          :param resource: Path to the resource relative to :attr:`instance_path`.
 193          :param mode: Open the file in this mode.
 194          :param encoding: Open the file with this encoding when opening in text
 195              mode. This is ignored when opening in binary mode.
 196  
 197          .. versionchanged:: 3.1
 198              Added the ``encoding`` parameter.
 199          �br�)r�r�r�rfr�r�rErErF�open_instance_resourceks
 200  zFlask.open_instance_resourcer0cCs�t|j�}d|vr|j|d<d|vr"|jd}|dur|j}||d<|j|fi|��}|jj|jt	|jt
 201  ttd�|j
 202  j|jd<|S)a�Create the Jinja environment based on :attr:`jinja_options`
 203          and the various Jinja-related methods of the app. Changing
 204          :attr:`jinja_options` after this will have no effect. Also adds
 205          Flask-related globals and filters to the environment.
 206  
 207          .. versionchanged:: 0.11
 208             ``Environment.auto_reload`` set in accordance with
 209             ``TEMPLATES_AUTO_RELOAD`` configuration option.
 210  
 211          .. versionadded:: 0.5
 212          Z
 213  autoescape�auto_reloadrUN)�url_forr$rzr r"rzjson.dumps_function)�dictZ
 214  jinja_optionsZselect_jinja_autoescaperz�debugZjinja_environment�globals�updater�r$r r"r�json�dumpsZpolicies)ru�optionsr��rvrErErF�create_jinja_environment�s&
 215  
 216  
 217  �zFlask.create_jinja_environmentr �Request | None�MapAdapter | NonecCs�|dur9|jd}dur||_t|j|j�|_d}|jd}|jjr&d}n	|js/|jjp.d}|jj	|j||d�S|jddurR|jj
 218  |jd|jd|jdd�SdS)	a�Creates a URL adapter for the given request. The URL adapter
 219          is created at a point where the request context is not yet set
 220          up so the request is passed explicitly.
 221  
 222          .. versionchanged:: 3.1
 223              If :data:`SERVER_NAME` is set, it does not restrict requests to
 224              only that domain, for both ``subdomain_matching`` and
 225              ``host_matching``.
 226  
 227          .. versionchanged:: 1.0
 228              :data:`SERVER_NAME` no longer implicitly enables subdomain
 229              matching. Use :attr:`subdomain_matching` instead.
 230  
 231          .. versionchanged:: 0.9
 232             This can be called outside a request when the URL adapter is created
 233             for an application context.
 234  
 235          .. versionadded:: 0.6
 236          NrMrN�)�server_name�	subdomainrOrT)�script_name�
 237  url_scheme)rz�
 238  trusted_hostsr�environrnZurl_maprbrdZdefault_subdomainZbind_to_environ�bind)rur r�r�r�rErErF�create_url_adapter�s(
 239  ��zFlask.create_url_adapterr1�
 240  t.NoReturncCsB|jrt|jt�r|jjdvs|jdvr|j�ddlm}||��)a�Intercept routing exceptions and possibly do something else.
 241  
 242          In debug mode, intercept a routing redirect and replace it with
 243          an error if the body will be discarded.
 244  
 245          With modern Werkzeug this shouldn't occur, since it now uses a
 246          308 status which tells the browser to resend the method and
 247          body.
 248  
 249          .. versionchanged:: 2.1
 250              Don't intercept 307 and 308 redirects.
 251  
 252          :meta private:
 253          :internal:
 254          >i3i4>�HEAD�OPTIONS�GETr)�FormDataRoutingRedirect)r�rD�routing_exceptionr�code�methodZdebughelpersr�)rur r�rErErF�raise_routing_exception�s�
 255  �
 256  zFlask.raise_routing_exception�context�dict[str, t.Any]�NonecCsdd}trt|ttj��}|��}|D]}||jvr*|j|D]}|�|�|���qq|�|�dS)aUpdate the template context with some commonly used variables.
 257          This injects request, session, config and g into the template
 258          context as well as everything template context processors want
 259          to inject.  Note that the as of Flask 0.6, the original values
 260          in the context will not be overridden if a context processor
 261          decides to return a value with the same key.
 262  
 263          :param context: the context as a dictionary that is updated in place
 264                          to add extra variables.
 265          �NN)r r�reversed�
 266  blueprints�copyZtemplate_context_processorsr��ensure_sync)rur��namesZorig_ctxrq�funcrErErF�update_template_context�s
 267  �zFlask.update_template_contextcCs&|td�}|jD]}|�|��q|S)z�Returns the shell context for an interactive shell for this
 268          application.  This runs all the registered shell context
 269          processors.
 270  
 271          .. versionadded:: 0.11
 272          )Zappr)rZshell_context_processorsr�)rur��	processorrErErF�make_shell_contexts
 273  
 274  zFlask.make_shell_contextrn�portr��bool | None�load_dotenvr��t.AnycKs4tj�d�dkrt�stjddd�dSt|�r%t��dtjvr%t	�|_
 275  |dur.t|�|_
 276  |j�d�}d}}|rB|�
 277  d	�\}}	}|sK|rI|}nd
 278  }|sQ|dkrVt|�}n	|r]t|�}nd}|�d
 279  |j
 280  �|�d|j
 281  �|�dd�t�|j
 282  |j�ddlm}
 283  z|
 284  t�t|�||fi|��Wd|_dSd|_w)a�
 285  Runs the application on a local development server.
 286  
 287          Do not use ``run()`` in a production setting. It is not intended to
 288          meet security and performance requirements for a production server.
 289          Instead, see :doc:`/deploying/index` for WSGI server recommendations.
 290  
 291          If the :attr:`debug` flag is set the server will automatically reload
 292          for code changes and show a debugger in case an exception happened.
 293  
 294          If you want to run the application in debug mode, but disable the
 295          code execution on the interactive debugger, you can pass
 296          ``use_evalex=False`` as parameter.  This will keep the debugger's
 297          traceback screen active, but disable code execution.
 298  
 299          It is not recommended to use this function for development with
 300          automatic reloading as this is badly supported.  Instead you should
 301          be using the :command:`flask` command line script's ``run`` support.
 302  
 303          .. admonition:: Keep in Mind
 304  
 305             Flask will suppress any server error with a generic error page
 306             unless it is in debug mode.  As such to enable just the
 307             interactive debugger without the code reloading, you have to
 308             invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
 309             Setting ``use_debugger`` to ``True`` without being in debug mode
 310             won't catch any exceptions because there won't be any to
 311             catch.
 312  
 313          :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
 314              have the server available externally as well. Defaults to
 315              ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
 316              if present.
 317          :param port: the port of the webserver. Defaults to ``5000`` or the
 318              port defined in the ``SERVER_NAME`` config variable if present.
 319          :param debug: if given, enable or disable debug mode. See
 320              :attr:`debug`.
 321          :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
 322              files to set environment variables. Will also change the working
 323              directory to the directory containing the first file found.
 324          :param options: the options to be forwarded to the underlying Werkzeug
 325              server. See :func:`werkzeug.serving.run_simple` for more
 326              information.
 327  
 328          .. versionchanged:: 1.0
 329              If installed, python-dotenv will be used to load environment
 330              variables from :file:`.env` and :file:`.flaskenv` files.
 331  
 332              The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.
 333  
 334              Threaded mode is enabled by default.
 335  
 336          .. versionchanged:: 0.10
 337              The default port is now picked from the ``SERVER_NAME``
 338              variable.
 339          ZFLASK_RUN_FROM_CLI�truez� * Ignoring a call to 'app.run()' that would block the current 'flask' CLI command.
 340     Only call 'app.run()' in an 'if __name__ == "__main__"' guard.�red)ZfgNZFLASK_DEBUGrN�:z	127.0.0.1ri�Zuse_reloaderZuse_debuggerZthreadedT)�
 341  run_simpleF)r�r��getr�clickZsechor%rr�r#r�rcrz�	partitionr{�
 342  setdefaultZshow_server_bannerrq�werkzeug.servingr�r�r�r\�_got_first_request)rurnr�r�r�r�r�Zsn_hostZsn_port�_r�rErErF�run"sDA�
 343  
 344  
 345  
 346  z	Flask.run�use_cookies�kwargsr5cKs2|j}|dur
 347  ddlm}|||jfd|i|��S)a�Creates a test client for this application.  For information
 348          about unit testing head over to :doc:`/testing`.
 349  
 350          Note that if you are testing for assertions or exceptions in your
 351          application code, you must set ``app.testing = True`` in order for the
 352          exceptions to propagate to the test client.  Otherwise, the exception
 353          will be handled by the application (not visible to the test client) and
 354          the only indication of an AssertionError or other exception will be a
 355          500 status code response to the test client.  See the :attr:`testing`
 356          attribute.  For example::
 357  
 358              app.testing = True
 359              client = app.test_client()
 360  
 361          The test client can be used in a ``with`` block to defer the closing down
 362          of the context until the end of the ``with`` block.  This is useful if
 363          you want to access the context locals for testing::
 364  
 365              with app.test_client() as c:
 366                  rv = c.get('/?vodka=42')
 367                  assert request.args['vodka'] == '42'
 368  
 369          Additionally, you may pass optional keyword arguments that will then
 370          be passed to the application's :attr:`test_client_class` constructor.
 371          For example::
 372  
 373              from flask.testing import FlaskClient
 374  
 375              class CustomClient(FlaskClient):
 376                  def __init__(self, *args, **kwargs):
 377                      self._authentication = kwargs.pop("authentication")
 378                      super(CustomClient,self).__init__( *args, **kwargs)
 379  
 380              app.test_client_class = CustomClient
 381              client = app.test_client(authentication='Basic ....')
 382  
 383          See :class:`~flask.testing.FlaskClient` for more information.
 384  
 385          .. versionchanged:: 0.4
 386             added support for ``with`` block usage for the client.
 387  
 388          .. versionadded:: 0.7
 389             The `use_cookies` parameter was added as well as the ability
 390             to override the client to be used by setting the
 391             :attr:`test_client_class` attribute.
 392  
 393          .. versionchanged:: 0.11
 394             Added `**kwargs` to support passing additional keyword arguments to
 395             the constructor of :attr:`test_client_class`.
 396          Nrr4r�)Ztest_client_class�testingr5rW)rur�r��clsrErErF�test_client�s3���zFlask.test_clientr7cKs*|j}|dur
 397  ddlm}||fi|��S)a-Create a CLI runner for testing CLI commands.
 398          See :ref:`testing-cli`.
 399  
 400          Returns an instance of :attr:`test_cli_runner_class`, by default
 401          :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
 402          passed as the first argument.
 403  
 404          .. versionadded:: 1.0
 405          Nrr6)Ztest_cli_runner_classr�r7)rur�r�rErErF�test_cli_runner�s
 406  zFlask.test_cli_runner�er�&HTTPException | ft.ResponseReturnValuecCsD|jdur|St|t�r|S|�|tj�}|dur|S|�|�|�S)acHandles an HTTP exception.  By default this will invoke the
 407          registered error handlers and fall back to returning the
 408          exception as response.
 409  
 410          .. versionchanged:: 1.0.3
 411              ``RoutingException``, used internally for actions such as
 412               slash redirects during routing, is not passed to error
 413               handlers.
 414  
 415          .. versionchanged:: 1.0
 416              Exceptions are looked up by code *and* by MRO, so
 417              ``HTTPException`` subclasses can be handled with a catch-all
 418              handler for the base ``HTTPException``.
 419  
 420          .. versionadded:: 0.3
 421          N)r�rDr�_find_error_handlerr r�r��rur��handlerrErErF�handle_http_exception�s
 422  
 423  zFlask.handle_http_exception�	ExceptioncCsdt|t�r|js
 424  |jdrd|_t|t�r|�|�s|�|�S|�|t	j
 425  �}|dur+�|�|�|�S)a>This method is called whenever an exception occurs that
 426          should be handled. A special case is :class:`~werkzeug
 427          .exceptions.HTTPException` which is forwarded to the
 428          :meth:`handle_http_exception` method. This function will either
 429          return a response value or reraise the exception with the same
 430          traceback.
 431  
 432          .. versionchanged:: 1.0
 433              Key errors raised from request data like ``form`` show the
 434              bad key in debug mode rather than a generic bad request
 435              message.
 436  
 437          .. versionadded:: 0.7
 438          rSTN)rDr
 439  r�rzZshow_exceptionrZtrap_http_exceptionr�r�r r�r�r�rErErF�handle_user_exceptions
 440  ��
 441  zFlask.handle_user_exceptioncCs�t��}tj||j|d�|jd}|dur|jp|j}|r'|d|ur%�|�|�|�t	|d�}|�
 442  |tj�}|durC|�|�|�}|j
 443  |dd�S)a�Handle an exception that did not have an error handler
 444          associated with it, or that was raised from an error handler.
 445          This always causes a 500 ``InternalServerError``.
 446  
 447          Always sends the :data:`got_request_exception` signal.
 448  
 449          If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug
 450          mode, the error will be re-raised so that the debugger can
 451          display it. Otherwise, the original exception is logged, and
 452          an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
 453  
 454          If an error handler is registered for ``InternalServerError`` or
 455          ``500``, it will be used. For consistency, the handler will
 456          always receive the ``InternalServerError``. The original
 457          unhandled exception is available as ``e.original_exception``.
 458  
 459          .. versionchanged:: 1.1.0
 460              Always passes the ``InternalServerError`` instance to the
 461              handler, setting ``original_exception`` to the unhandled
 462              error.
 463  
 464          .. versionchanged:: 1.1.0
 465              ``after_request`` functions and other finalization is done
 466              even for the default 500 response when there is no handler.
 467  
 468          .. versionadded:: 0.3
 469          )�_async_wrapper�	exceptionrJNr)Zoriginal_exceptionT)�from_error_handler)�sys�exc_infor,�sendr�rzr�r��
 470  log_exceptionrr�r r��finalize_request)rur�r��	propagate�server_errorr�rErErF�handle_exception+s
 471  
 472  
 473  zFlask.handle_exceptionr��Ctuple[type, BaseException, TracebackType] | tuple[None, None, None]cCs&|jjdtj�dtj�d�|d�dS)a
 474  Logs an exception.  This is called by :meth:`handle_exception`
 475          if debugging is disabled and right before the handler is called.
 476          The default implementation logs the exception as error on the
 477          :attr:`logger`.
 478  
 479          .. versionadded:: 0.8
 480          z
 481  Exception on z [�])r�N)�logger�errorr r�r�)rur�rErErFr�`s
 482  �zFlask.log_exception�ft.ResponseReturnValuecCs`tj}|jdur
 483  |�|�|j}t|dd�r|jdkr|��S|j}|�	|j
 484  |j�di|��S)a�Does the request dispatching.  Matches the URL and returns the
 485          return value of the view or error handler.  This does not have to
 486          be a response object.  In order to convert the return value to a
 487          proper response object, call :func:`make_response`.
 488  
 489          .. versionchanged:: 0.7
 490             This no longer does the exception handling, this code was
 491             moved to the new :meth:`full_dispatch_request`.
 492          NZprovide_automatic_optionsFr�rE)r!r r�r�Zurl_rule�getattrr��make_default_options_response�	view_argsr�Zview_functionsrm)ru�req�ruler�rErErF�dispatch_requestos
 493  
 494  
 495  
 496  �
 497  zFlask.dispatch_requestc
 498  Csld|_ztj||jd�|��}|dur|��}Wnty0}z|�|�}WYd}~nd}~ww|�|�S)z�Dispatches the request and on top of that performs request
 499          pre and postprocessing as well as HTTP exception catching and
 500          error handling.
 501  
 502          .. versionadded:: 0.7
 503          T)r�N)	r�r.r�r��preprocess_requestr�r�r�r�)rur�r�rErErF�full_dispatch_request�s���
 504  zFlask.full_dispatch_requestr��&ft.ResponseReturnValue | HTTPExceptionr�cCsT|�|�}z|�|�}tj||j|d�W|Sty)|s �|j�d�Y|Sw)a)Given the return value from a view function this finalizes
 505          the request by converting it into a response and invoking the
 506          postprocessing functions.  This is invoked for both normal
 507          request dispatching as well as error handlers.
 508  
 509          Because this means that it might be called as a result of a
 510          failure a special safe mode is available which can be enabled
 511          with the `from_error_handler` flag.  If enabled, failures in
 512          response processing will be logged and otherwise ignored.
 513  
 514          :internal:
 515          )r��responsez?Request finalizing failed with an error while handling an error)�
 516  make_response�process_responser-r�r�r�r�r�)rur�r�r�rErErFr��s
 517  
 518  �	���zFlask.finalize_requestcCs&tj}|��}|��}|j�|�|S)z�This method is called to create the default ``OPTIONS`` response.
 519          This can be changed through subclassing to change the default
 520          behavior of ``OPTIONS`` responses.
 521  
 522          .. versionadded:: 0.7
 523          )r!�url_adapter�allowed_methodsrWZallowr�)ru�adapter�methodsr�rErErFr��s
 524  z#Flask.make_default_options_responser��t.Callable[..., t.Any]cCst|�r	|�|�S|S)a)Ensure that the function is synchronous for WSGI workers.
 525          Plain ``def`` functions are returned as-is. ``async def``
 526          functions are wrapped to run and wait for the response.
 527  
 528          Override this method to change how the app runs async views.
 529  
 530          .. versionadded:: 2.0
 531          )r�
 532  async_to_sync)rur�rErErFr��s	
 533  zFlask.ensure_sync�1t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]cCs0zddlm}W||�Stytd�d�w)a1Return a sync function that will run the coroutine function.
 534  
 535          .. code-block:: python
 536  
 537              result = app.async_to_sync(func)(*args, **kwargs)
 538  
 539          Override this method to change how the app converts async code
 540          to be synchronously callable.
 541  
 542          .. versionadded:: 2.0
 543          r)r�zAInstall Flask with the 'async' extra in order to use async views.N)Zasgiref.syncr��ImportErrorr)rur�Zasgiref_async_to_syncrErErFr��s����zFlask.async_to_sync��_anchor�_method�_scheme�	_externalrmrrrr�valuesc
 544  
 545  KsHt�d�}|dur2|j}|jj}	|dd�dkr)|	dur#|	�|��}n|dd�}|dur1|du}n t�d�}
 546  |
 547  dur?|
 548  j}n|�d�}|durLtd��|durRd}|dur\|s\td��|�	||�z|j
 549  |||||d�}Wn"ty�}z|j||||d�|�
 550  |||�WYd}~Sd}~ww|dur�t|d	d
 551  �}|�d|��}|S)a	Generate a URL to the given endpoint with the given values.
 552  
 553          This is called by :func:`flask.url_for`, and can be called
 554          directly as well.
 555  
 556          An *endpoint* is the name of a URL rule, usually added with
 557          :meth:`@app.route() <route>`, and usually the same name as the
 558          view function. A route defined in a :class:`~flask.Blueprint`
 559          will prepend the blueprint's name separated by a ``.`` to the
 560          endpoint.
 561  
 562          In some cases, such as email messages, you want URLs to include
 563          the scheme and domain, like ``https://example.com/hello``. When
 564          not in an active request, URLs will be external by default, but
 565          this requires setting :data:`SERVER_NAME` so Flask knows what
 566          domain to use. :data:`APPLICATION_ROOT` and
 567          :data:`PREFERRED_URL_SCHEME` should also be configured as
 568          needed. This config is only used when not in an active request.
 569  
 570          Functions can be decorated with :meth:`url_defaults` to modify
 571          keyword arguments before the URL is built.
 572  
 573          If building fails for some reason, such as an unknown endpoint
 574          or incorrect values, the app's :meth:`handle_url_build_error`
 575          method is called. If that returns a string, that is returned,
 576          otherwise a :exc:`~werkzeug.routing.BuildError` is raised.
 577  
 578          :param endpoint: The endpoint name associated with the URL to
 579              generate. If this starts with a ``.``, the current blueprint
 580              name (if any) will be used.
 581          :param _anchor: If given, append this as ``#anchor`` to the URL.
 582          :param _method: If given, generate the URL associated with this
 583              method for the endpoint.
 584          :param _scheme: If given, the URL will have this scheme if it
 585              is external.
 586          :param _external: If given, prefer the URL to be internal
 587              (False) or require it to be external (True). External URLs
 588              include the scheme and domain. When not in an active
 589              request, URLs are external by default.
 590          :param values: Values to use for the variable parts of the URL
 591              rule. Unknown keys are appended as query string arguments,
 592              like ``?a=b&c=d``.
 593  
 594          .. versionadded:: 2.2
 595              Moved from ``flask.url_for``, which calls this method.
 596          Nr�.z�Unable to build URLs outside an active request without 'SERVER_NAME' configured. Also configure 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as needed.Tz4When specifying '_scheme', '_external' must be True.)r�r�Zforce_externalrz%!#$&'()*+,/:;=?@)�safe�#)rr�r�r Z	blueprintrr�rr�Zinject_url_defaults�buildr
 597  r�Zhandle_url_build_error�
 598  _url_quote)
 599  rurmrrrrrZreq_ctxr�Zblueprint_nameZapp_ctxr�r�rErErFr��sV
 600  9�
 601  
 602  �	
 603  ����z
 604  Flask.url_forc
 605  Cs�d}d}t|t�r4t|�}|dkr|\}}}n|dkr0t|dttttf�r+|\}}n	|\}}ntd��|durAtdtj�d���t||j	�s�t|t
 606  ttf�sUt|t
 607  j�rb|j	|||d�}d}}nNt|ttf�rp|j�|�}n@t|t�syt|�r�z
 608  |j	�|tj�}Wn,ty�}zt|�d	t|�j�d
 609  ���t��d�d�d}~wwtdt|�j�d
 610  ���t�t|�}|dur�t|t
 611  ttf�r�||_n||_|r�|j� |�|S)a�Convert the return value from a view function to an instance of
 612          :attr:`response_class`.
 613  
 614          :param rv: the return value from the view function. The view function
 615              must return a response. Returning ``None``, or the view ending
 616              without returning, is not allowed. The following types are allowed
 617              for ``view_rv``:
 618  
 619              ``str``
 620                  A response object is created with the string encoded to UTF-8
 621                  as the body.
 622  
 623              ``bytes``
 624                  A response object is created with the bytes as the body.
 625  
 626              ``dict``
 627                  A dictionary that will be jsonify'd before being returned.
 628  
 629              ``list``
 630                  A list that will be jsonify'd before being returned.
 631  
 632              ``generator`` or ``iterator``
 633                  A generator that returns ``str`` or ``bytes`` to be
 634                  streamed as the response.
 635  
 636              ``tuple``
 637                  Either ``(body, status, headers)``, ``(body, status)``, or
 638                  ``(body, headers)``, where ``body`` is any of the other types
 639                  allowed here, ``status`` is a string or an integer, and
 640                  ``headers`` is a dictionary or a list of ``(key, value)``
 641                  tuples. If ``body`` is a :attr:`response_class` instance,
 642                  ``status`` overwrites the exiting value and ``headers`` are
 643                  extended.
 644  
 645              :attr:`response_class`
 646                  The object is returned unchanged.
 647  
 648              other :class:`~werkzeug.wrappers.Response` class
 649                  The object is coerced to :attr:`response_class`.
 650  
 651              :func:`callable`
 652                  The function is called as a WSGI application. The result is
 653                  used to create a response object.
 654  
 655          .. versionchanged:: 2.2
 656              A generator will be converted to a streaming response.
 657              A list will be converted to a JSON response.
 658  
 659          .. versionchanged:: 1.1
 660              A dict will be converted to a JSON response.
 661  
 662          .. versionchanged:: 0.9
 663             Previously a tuple was interpreted as the arguments for the
 664             response object.
 665          N��rz�The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).zThe view function for zh did not return a valid response. The function either returned None or ended without a return statement.)�status�headersz�
 666  The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a rz�The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a )!rD�tuple�lenrr��list�	TypeErrorr rmrWr\�bytes�	bytearray�cabc�Iteratorr�r��BaseResponse�callableZ
 667  force_typer��type�__name__�with_tracebackr�r�r�r�rr�status_coderr�)rur�rrZlen_rvr�rErErFr�isp9
 668  
 669  
 670  ���
 671  ������	��zFlask.make_response�ft.ResponseReturnValue | NonecCs�dgttj��R}|D]}||jvr!|j|D]	}|tjtj�qq|D]}||jvrC|j|D]}|�|��}|durB|Sq0q$dS)a�Called before the request is dispatched. Calls
 672          :attr:`url_value_preprocessors` registered with the app and the
 673          current blueprint (if any). Then calls :attr:`before_request_funcs`
 674          registered with the app and the blueprint.
 675  
 676          If any :meth:`before_request` handler returns a non-None value, the
 677          value is handled as if it was the return value from the view, and
 678          further request handling is stopped.
 679          N)r�r r�Zurl_value_preprocessorsrmr�Zbefore_request_funcsr�)rur�rqZurl_funcZbefore_funcr�rErErFr��s
 680  
 681  �
 682  ��zFlask.preprocess_requestr�cCs�t��}|jD]	}|�|�|�}qttjd�D]}||jvr/t|j|�D]	}|�|�|�}q%q|j	�
 683  |j�s@|j	�||j|�|S)aCan be overridden in order to modify the response object
 684          before it's sent to the WSGI server.  By default this will
 685          call all the :meth:`after_request` decorated functions.
 686  
 687          .. versionchanged:: 0.5
 688             As of Flask 0.5 the functions registered for after request
 689             execution are called in reverse order of registration.
 690  
 691          :param response: a :attr:`response_class` object.
 692          :return: a new response object or the same, has to be an
 693                   instance of :attr:`response_class`.
 694          r�)
 695  r!Z_get_current_objectZ_after_request_functionsr�rr r�Zafter_request_funcsr�rXZis_null_sessionr"Zsave_session)rur��ctxr�rqrErErFr�s
 696  
 697  �zFlask.process_response�exc�BaseException | NonecCsh|tur
 698  t��d}ttjd�D]}||jvr(t|j|�D]	}|�|�|�qqt	j
 699  ||j|d�dS)a2Called after the request is dispatched and the response is
 700          returned, right before the request context is popped.
 701  
 702          This calls all functions decorated with
 703          :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
 704          if a blueprint handled the request. Finally, the
 705          :data:`request_tearing_down` signal is sent.
 706  
 707          This is called by
 708          :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
 709          which may be delayed during testing to maintain access to
 710          resources.
 711  
 712          :param exc: An unhandled exception raised while dispatching the
 713              request. Detected from the current exception information if
 714              not passed. Passed to each teardown function.
 715  
 716          .. versionchanged:: 0.9
 717              Added the ``exc`` argument.
 718          rr��r�r!N)r(r�r�rr r�Zteardown_request_funcsr�r�r/r�)rur!rqr�rErErF�do_teardown_request.s
 719  �zFlask.do_teardown_requestcCsH|tur
 720  t��d}t|j�D]	}|�|�|�qtj||j|d�dS)a�Called right before the application context is popped.
 721  
 722          When handling a request, the application context is popped
 723          after the request context. See :meth:`do_teardown_request`.
 724  
 725          This calls all functions decorated with
 726          :meth:`teardown_appcontext`. Then the
 727          :data:`appcontext_tearing_down` signal is sent.
 728  
 729          This is called by
 730          :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
 731  
 732          .. versionadded:: 0.9
 733          rr#N)r(r�r�r�Zteardown_appcontext_funcsr�r+r�)rur!r�rErErF�do_teardown_appcontextPs
 734  zFlask.do_teardown_appcontextrcCst|�S)aFCreate an :class:`~flask.ctx.AppContext`. Use as a ``with``
 735          block to push the context, which will make :data:`current_app`
 736          point at this application.
 737  
 738          An application context is automatically pushed by
 739          :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
 740          when handling a request, and when running a CLI command. Use
 741          this to manually create a context outside of these situations.
 742  
 743          ::
 744  
 745              with app.app_context():
 746                  init_db()
 747  
 748          See :doc:`/appcontext`.
 749  
 750          .. versionadded:: 0.9
 751          r)rurErErF�app_contextjszFlask.app_contextr�r3rcCs
 752  t||�S)a$Create a :class:`~flask.ctx.RequestContext` representing a
 753          WSGI environment. Use a ``with`` block to push the context,
 754          which will make :data:`request` point at this request.
 755  
 756          See :doc:`/reqcontext`.
 757  
 758          Typically you should not call this from your own code. A request
 759          context is automatically pushed by the :meth:`wsgi_app` when
 760          handling a request. Use :meth:`test_request_context` to create
 761          an environment and context instead of this method.
 762  
 763          :param environ: a WSGI environment
 764          r)rur�rErErF�request_contexts
 765  zFlask.request_context�argscOsFddlm}||g|�Ri|��}z|�|���W|��S|��w)a�Create a :class:`~flask.ctx.RequestContext` for a WSGI
 766          environment created from the given values. This is mostly useful
 767          during testing, where you may want to run a function that uses
 768          request data without dispatching a full request.
 769  
 770          See :doc:`/reqcontext`.
 771  
 772          Use a ``with`` block to push the context, which will make
 773          :data:`request` point at the request for the created
 774          environment. ::
 775  
 776              with app.test_request_context(...):
 777                  generate_report()
 778  
 779          When using the shell, it may be easier to push and pop the
 780          context manually to avoid indentation. ::
 781  
 782              ctx = app.test_request_context(...)
 783              ctx.push()
 784              ...
 785              ctx.pop()
 786  
 787          Takes the same arguments as Werkzeug's
 788          :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
 789          the application. See the linked Werkzeug docs for most of the
 790          available arguments. Flask-specific behavior is listed here.
 791  
 792          :param path: URL path being requested.
 793          :param base_url: Base URL where the app is being served, which
 794              ``path`` is relative to. If not given, built from
 795              :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
 796              :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
 797          :param subdomain: Subdomain name to append to
 798              :data:`SERVER_NAME`.
 799          :param url_scheme: Scheme to use instead of
 800              :data:`PREFERRED_URL_SCHEME`.
 801          :param data: The request body, either as a string or a dict of
 802              form keys and values.
 803          :param json: If given, this is serialized as JSON and passed as
 804              ``data``. Also defaults ``content_type`` to
 805              ``application/json``.
 806          :param args: other positional arguments passed to
 807              :class:`~werkzeug.test.EnvironBuilder`.
 808          :param kwargs: other keyword arguments passed to
 809              :class:`~werkzeug.test.EnvironBuilder`.
 810          r)�EnvironBuilder)r�r)r'Zget_environ�close)rur(r�r)ZbuilderrErErF�test_request_context�s
 811  /zFlask.test_request_context�start_responser2�cabc.Iterable[bytes]c
 812  Cs|�|�}d}zWz
 813  |��|��}Wn"ty+}z
 814  |}|�|�}WYd}~nd}~wt��d}�|||�Wd|vrN|dt���|dt	���|durY|�
 815  |�rYd}|�|�Sd|vrs|dt���|dt	���|dur~|�
 816  |�r~d}|�|�w)a�The actual WSGI application. This is not implemented in
 817          :meth:`__call__` so that middlewares can be applied without
 818          losing a reference to the app object. Instead of doing this::
 819  
 820              app = MyMiddleware(app)
 821  
 822          It's a better idea to do this instead::
 823  
 824              app.wsgi_app = MyMiddleware(app.wsgi_app)
 825  
 826          Then you still have the original application object around and
 827          can continue to call methods on it.
 828  
 829          .. versionchanged:: 0.7
 830              Teardown events for the request and app contexts are called
 831              even if an unhandled error occurs. Other events may not be
 832              called depending on when an error occurs during dispatch.
 833              See :ref:`callbacks-and-errors`.
 834  
 835          :param environ: A WSGI environment.
 836          :param start_response: A callable accepting a status code,
 837              a list of headers, and an optional exception context to
 838              start the response.
 839          Nrzwerkzeug.debug.preserve_context)r'�pushr�r�r�r�r�rr�rZshould_ignore_error�pop)rur�r,r r�r�r�rErErF�wsgi_app�s4
 840  �
 841  �zFlask.wsgi_appcCs|�||�S)z�The WSGI server calls the Flask application object as the
 842          WSGI application. This calls :meth:`wsgi_app`, which can be
 843          wrapped to apply middleware.
 844          )r0)rur�r,rErErF�__call__�szFlask.__call__)	NrYNFFrZNFN)r[r\r]r^r_r`rar^rbrcrdrcrer`rfr^rgrcrhr^)rxr^rAry)rxr\rAr)r�N)r�r\r�r\r�r^rAr�)r�r�)rAr0)r r�rAr�)r r1rAr�)r�r�rAr�)rAr�)NNNT)rnr^r�ryr�r�r�rcr�r�rAr�)T)r�rcr�r�rAr5)r�r�rAr7)r�rrAr�)r�r�rAr�)r�r�rAr)r�r�rAr�)rAr�)rAr)F)r�r�r�rcrAr)r�r�rAr�)r�rrAr�)rmr\rr^rr^rr^rr�rr�rAr\)r�r�rAr)rAr)r�rrAr)r!r"rAr�)rAr)r�r3rAr)r(r�r�r�rAr)r�r3r,r2rAr-)2r�
 845  __module__�__qualname__�__doc__r	rZdefault_configr1rV�__annotations__rrWr)rXrpr}rir�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r(r$r%r&r'r+r0r1�
 846  __classcell__rErErvrFrHQs�
 847  `�����
 848  ���	�
 849  ���
 850  �������$�
 851  7
 852  �"�
 853  
 854  (
 855  5
 856  
 857  �{
 858  :
 859  
 860  #
 861   
 862  5
 863  
 864  �
 865  
 866  
 867  �
 868  ~
 869  
 870  �$�
 871  
 872  
 873  
 874  82rH)r?r@rArB)c�
 875  __future__r�collections.abc�abcrr�r�rr�rs�datetimer�inspectr�	itertoolsr�typesr�urllib.parserrr�Zwerkzeug.datastructuresrr	Zwerkzeug.exceptionsr
 876  rrZwerkzeug.routingr
 877  rrrrr�rZwerkzeug.wrappersrrZ
 878  werkzeug.wsgirr�r�ftr rrr�rrrrr r!r"�helpersr#r$r%r&Z
 879  sansio.appr'Zsansio.scaffoldr(�sessionsr)r*Zsignalsr+r,r-r.r/Z
 880  templatingr0Zwrappersr1�
 881  TYPE_CHECKINGZ_typeshed.wsgir2r3r�r5r7r8�TypeVarZShellContextProcessorCallabler9ZTeardownCallabler;ZTemplateFilterCallabler<ZTemplateGlobalCallabler=ZTemplateTestCallabler>rGrHrErErErF�<module>s��
 882