
_                @   s  d  Z  d d l Z d d l Z d d l Z d d l m Z d d l m Z d d l m	 Z	 d d l
 m Z d d l m Z d d l m Z d d	 l m Z d d
 l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m  Z  d d l! m" Z" d d l! m# Z# d d l! m$ Z$ d d l! m% Z% d d l& m' Z' d d l& m( Z( d d l) m* Z* d d l) m+ Z+ d d  l) m, Z, d d! l- m. Z. d d" l- m/ Z/ d d# l- m0 Z0 d d$ l- m1 Z1 d d% l2 m3 Z3 d d& l2 m4 Z4 d d' l2 m5 Z5 d d( l2 m6 Z6 d d) l2 m7 Z7 d d* l2 m8 Z8 d d+ l2 m9 Z9 d d, l2 m: Z: d d- l2 m; Z; d d. l  m< Z< d d/ l= m> Z> d d0 l? m@ Z@ d d1 lA mB ZB d d2 lA mC ZC d d3 lA mD ZD d d4 lA mE ZE d d5 lA mF ZF d d6 lG mH ZH d d7 lG mI ZI d d8 lG mJ ZJ d d9 lK mL ZL d d: lK mM ZM eN   ZO d; d<   ZP d= d>   ZQ Gd? d@   d@ e4  ZR d S)Az
    flask.app
    ~~~~~~~~~

    This module implements the central WSGI application object.

    :copyright: 2010 Pallets
    :license: BSD-3-Clause
    N)	timedelta)update_wrapper)chain)Lock)Headers)ImmutableDict)
BadRequest)BadRequestKeyError)default_exceptions)HTTPException)InternalServerError)MethodNotAllowed)
BuildError)Map)RequestRedirect)RoutingException)Rule)BaseResponse   )cli)json)integer_types)reraise)string_types)	text_type)Config)ConfigAttribute)_AppCtxGlobals)
AppContext)RequestContext)_request_ctx_stack)g)request)session)_endpoint_from_view_func)_PackageBoundObject)find_package)get_debug_flag)get_env)get_flashed_messages)get_load_dotenv)locked_cached_property)url_for)jsonify)create_logger)SecureCookieSessionInterface)appcontext_tearing_down)got_request_exception)request_finished)request_started)request_tearing_down)_default_template_ctx_processor)DispatchingJinjaLoader)Environment)Request)Responsec             C   s    t  |  t  s t d |   S|  S)Nseconds)
isinstancer   )value r=   */tmp/pip-build-5gj8f0j9/flask/flask/app.py_make_timedeltaL   s    r?   c                s     f d d   } t  |    S)zkWraps a method so that it performs a check in debug mode if the
    first request was already handled.
    c                s.   |  j  r |  j r t d     |  | |  S)Nam  A setup function was called after the first request was handled.  This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.)debug_got_first_requestAssertionError)selfargskwargs)fr=   r>   wrapper_funcW   s    	z!setupmethod.<locals>.wrapper_func)r   )rF   rG   r=   )rF   r>   setupmethodR   s    rH   c            ;   @   sa  e  Z d  Z d Z e Z e Z e Z	 e
 Z e Z e d  Z e d  Z e d  Z e d d e Z e d d e Z e d  Z e j Z e j Z d	 d
 d g i Z e d d d d d d d d d d d d d e d d  d d d d d d d d d d d d d d d d d d d d d d d e d  d!  d" d d# d d$ d d% d& d' d d( d d) d d* d+ d, d d- d. i  Z e Z  e! Z" d Z# d Z$ e%   Z& d Z' d Z( d Z) d d/ d d d d0 d d d d1 d2 	 Z* e+ d3 d4    Z, e- d5 d6    Z. e- d7 d8    Z/ e+ d9 d:    Z0 e+ d; d<    Z1 e- d= d>    Z2 d d? d@  Z3 dA dB   Z4 dC dD dE  Z5 e- dF dG    Z6 e6 j7 dH dG    Z6 dI dJ   Z8 dK dL   Z9 dM dN   Z: dO dP   Z; dQ dR   Z< e d  Z= e- dS dT    Z> e> j7 dU dT    Z> d d d d dV dW  Z? d dX dY  Z@ dZ d[   ZA d\ d]   ZB d^ d_   ZC d` da   ZD eE db dc    ZF dd de   ZG eE d d d df dg   ZH dh di   ZI eE dj dk    ZJ eK dl dm    ZL eE dn do    ZM eE dp dq    ZN eE dr ds    ZO eE d dt du   ZP eE d dv dw   ZQ eE d dx dy   ZR eE d dz d{   ZS eE d d| d}   ZT eE d d~ d   ZU eE d d    ZV eE d d    ZW eE d d    ZX eE d d    ZY eE d d    ZZ eE d d    Z[ eE d d    Z\ eE d d    Z] eE d d    Z^ d d   Z_ d d   Z` d d   Za d d   Zb d d   Zc d d   Zd d d   Ze d d   Zf d d   Zg d d d  Zh d d   Zi d d   Zj d d   Zk d d   Zl d d   Zm d d   Zn d d   Zo d d   Zp d d   Zq er d d  Zs er d d  Zt d d   Zu d d   Zv d d   Zw d d   Zx d d   Zy d d   Zz d S)Flaskag  The flask object implements a WSGI application and acts as the central
    object.  It is passed the name of the module or package of the
    application.  Once it is created it will act as a central registry for
    the view functions, the URL rules, template configuration and much more.

    The name of the package is used to resolve resources from inside the
    package or the folder the module is contained in depending on if the
    package parameter resolves to an actual python package (a folder with
    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).

    For more information about resource loading, see :func:`open_resource`.

    Usually you create a :class:`Flask` instance in your main module or
    in the :file:`__init__.py` file of your package like this::

        from flask import Flask
        app = Flask(__name__)

    .. admonition:: About the First Parameter

        The idea of the first parameter is to give Flask an idea of what
        belongs to your application.  This name is used to find resources
        on the filesystem, can be used by extensions to improve debugging
        information and a lot more.

        So it's important what you provide there.  If you are using a single
        module, `__name__` is always the correct value.  If you however are
        using a package, it's usually recommended to hardcode the name of
        your package there.

        For example if your application is defined in :file:`yourapplication/app.py`
        you should create it with one of the two versions below::

            app = Flask('yourapplication')
            app = Flask(__name__.split('.')[0])

        Why is that?  The application will work even with `__name__`, thanks
        to how resources are looked up.  However it will make debugging more
        painful.  Certain extensions can make assumptions based on the
        import name of your application.  For example the Flask-SQLAlchemy
        extension will look for the code in your application that triggered
        an SQL query in debug mode.  If the import name is not properly set
        up, that debugging information is lost.  (For example it would only
        pick up SQL queries in `yourapplication.app` and not
        `yourapplication.views.frontend`)

    .. versionadded:: 0.7
       The `static_url_path`, `static_folder`, and `template_folder`
       parameters were added.

    .. versionadded:: 0.8
       The `instance_path` and `instance_relative_config` parameters were
       added.

    .. versionadded:: 0.11
       The `root_path` parameter was added.

    .. versionadded:: 1.0
       The ``host_matching`` and ``static_host`` parameters were added.

    .. versionadded:: 1.0
       The ``subdomain_matching`` parameter was added. Subdomain
       matching needs to be enabled manually now. Setting
       :data:`SERVER_NAME` does not implicitly enable it.

    :param import_name: the name of the application package
    :param static_url_path: can be used to specify a different path for the
                            static files on the web.  Defaults to the name
                            of the `static_folder` folder.
    :param static_folder: The folder with static files that is served at
        ``static_url_path``. Relative to the application ``root_path``
        or an absolute path. Defaults to ``'static'``.
    :param static_host: the host to use when adding the static route.
        Defaults to None. Required when using ``host_matching=True``
        with a ``static_folder`` configured.
    :param host_matching: set ``url_map.host_matching`` attribute.
        Defaults to False.
    :param subdomain_matching: consider the subdomain relative to
        :data:`SERVER_NAME` when matching routes. Defaults to False.
    :param template_folder: the folder that contains the templates that should
                            be used by the application.  Defaults to
                            ``'templates'`` folder in the root path of the
                            application.
    :param instance_path: An alternative instance path for the application.
                          By default the folder ``'instance'`` next to the
                          package or module is assumed to be the instance
                          path.
    :param instance_relative_config: if set to ``True`` relative filenames
                                     for loading the config are assumed to
                                     be relative to the instance path instead
                                     of the application root.
    :param root_path: Flask by default will automatically calculate the path
                      to the root of the application.  In certain situations
                      this cannot be achieved (for instance if the package
                      is a Python 3 namespace package) and needs to be
                      manually defined.
    ZTESTINGZ
SECRET_KEYZSESSION_COOKIE_NAMEZPERMANENT_SESSION_LIFETIMEZget_converterZSEND_FILE_MAX_AGE_DEFAULTZUSE_X_SENDFILE
extensionszjinja2.ext.autoescapezjinja2.ext.with_ENVNDEBUGFPROPAGATE_EXCEPTIONSPRESERVE_CONTEXT_ON_EXCEPTIONdays   SERVER_NAMEAPPLICATION_ROOT/r#   ZSESSION_COOKIE_DOMAINZSESSION_COOKIE_PATHZSESSION_COOKIE_HTTPONLYTZSESSION_COOKIE_SECUREZSESSION_COOKIE_SAMESITEZSESSION_REFRESH_EACH_REQUESTZMAX_CONTENT_LENGTHhours   TRAP_BAD_REQUEST_ERRORSTRAP_HTTP_EXCEPTIONSZEXPLAIN_TEMPLATE_LOADINGPREFERRED_URL_SCHEMEhttpZJSON_AS_ASCIIZJSON_SORT_KEYSZJSONIFY_PRETTYPRINT_REGULARZJSONIFY_MIMETYPEzapplication/jsonTEMPLATES_AUTO_RELOADZMAX_COOKIE_SIZEi  staticZ	templatesc             C   s  t  j |  | d | d |
 | |  _ | |  _ | d  k rI |  j   } n t j j |  sg t d   | |  _	 |  j
 |	  |  _ i  |  _ i  |  _ g  |  _ i  |  _ g  |  _ i  |  _ i  |  _ g  |  _ i  |  _ i  |  _ d  t g i |  _ g  |  _ i  |  _ g  |  _ i  |  _ |  j   |  _ | |  j _ | |  _ d |  _  t!   |  _" |  j# rt$ |  | k srt% d   |  j& |  j d d d d	 | d
 |  j' |  j( |  j) _( d  S)Ntemplate_folder	root_pathzWIf an instance path is provided it must be absolute. A relative path was given instead.Fz-Invalid static_host/host_matching combinationz/<path:filename>endpointr[   host	view_func)*r%   __init__static_url_pathstatic_folderauto_find_instance_pathospathisabs
ValueErrorinstance_pathmake_configconfigview_functionserror_handler_specurl_build_error_handlersbefore_request_funcsbefore_first_request_funcsafter_request_funcsteardown_request_funcsteardown_appcontext_funcsurl_value_preprocessorsurl_default_functionsr5   template_context_processorsshell_context_processors
blueprints_blueprint_orderrJ   url_map_classurl_maphost_matchingsubdomain_matchingrA   r   _before_request_lockZhas_static_folderboolrB   add_url_ruleZsend_static_filenamer   )rC   import_namerb   rc   Zstatic_hostr|   r}   r\   ri   Zinstance_relative_configr]   r=   r=   r>   ra     sP    																								
zFlask.__init__c             C   s_   |  j  d k rX t t j d d d  } | d k r8 d St j j t j j |   d S|  j  S)a_  The name of the application.  This is usually the import name
        with the difference that it's guessed from the run file if the
        import name is main.  This name is used as a display name when
        Flask needs the name of the application.  It can be set and overridden
        to change the value.

        .. versionadded:: 0.8
        __main____file__Nr   )r   getattrsysmodulesre   rf   splitextbasename)rC   fnr=   r=   r>   r   d  s    
 z
Flask.namec             C   s-   |  j  d } | d k	 r | S|  j p, |  j S)zReturns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
        value in case it's set, otherwise a sensible default is returned.

        .. versionadded:: 0.7
        rM   N)rk   testingr@   )rC   rvr=   r=   r>   propagate_exceptionsu  s    zFlask.propagate_exceptionsc             C   s$   |  j  d } | d k	 r | S|  j S)zReturns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
        configuration value in case it's set, otherwise a sensible default
        is returned.

        .. versionadded:: 0.7
        rN   N)rk   r@   )rC   r   r=   r=   r>   preserve_context_on_exception  s    z#Flask.preserve_context_on_exceptionc             C   s
   t  |   S)a  A standard Python :class:`~logging.Logger` for the app, with
        the same name as :attr:`name`.

        In debug mode, the logger's :attr:`~logging.Logger.level` will
        be set to :data:`~logging.DEBUG`.

        If there are no handlers configured, a default handler will be
        added. See :doc:`/logging` for more information.

        .. versionchanged:: 1.1.0
            The logger takes the same name as :attr:`name` rather than
            hard-coding ``"flask.app"``.

        .. versionchanged:: 1.0.0
            Behavior was simplified. The logger is always named
            ``"flask.app"``. The level is only set during configuration,
            it doesn't check ``app.debug`` each time. Only one format is
            used, not different ones depending on ``app.debug``. No
            handlers are removed, and a handler is only added if no
            handlers are already configured.

        .. versionadded:: 0.3
        )r.   )rC   r=   r=   r>   logger  s    zFlask.loggerc             C   s
   |  j    S)zThe Jinja environment used to load templates.

        The environment is created the first time this property is
        accessed. Changing :attr:`jinja_options` after that will have no
        effect.
        )create_jinja_environment)rC   r=   r=   r>   	jinja_env  s    zFlask.jinja_envc             C   s   |  j  S)zThis attribute is set to ``True`` if the application started
        handling the first request.

        .. versionadded:: 0.8
        )rA   )rC   r=   r=   r>   got_first_request  s    zFlask.got_first_requestc             C   sQ   |  j  } | r |  j } t |  j  } t   | d <t   | d <|  j | |  S)ad  Used to create the config attribute by the Flask constructor.
        The `instance_relative` parameter is passed in from the constructor
        of Flask (there named `instance_relative_config`) and indicates if
        the config should be relative to the instance path or the root path
        of the application.

        .. versionadded:: 0.8
        rK   rL   )r]   ri   dictdefault_configr(   r'   config_class)rC   Zinstance_relativer]   defaultsr=   r=   r>   rj     s    			zFlask.make_configc             C   sQ   t  |  j  \ } } | d k r4 t j j | d  St j j | d |  j d  S)a  Tries to locate the instance path if it was not provided to the
        constructor of the application class.  It will basically calculate
        the path to a folder named ``instance`` next to your main file or
        the package.

        .. versionadded:: 0.8
        Ninstancevarz	-instance)r&   r   re   rf   joinr   )rC   prefixZpackage_pathr=   r=   r>   rd     s    zFlask.auto_find_instance_pathrbc             C   s   t  t j j |  j |  |  S)a  Opens a resource from the application's instance folder
        (:attr:`instance_path`).  Otherwise works like
        :meth:`open_resource`.  Instance resources can also be opened for
        writing.

        :param resource: the name of the resource.  To access resources within
                         subfolders use forward slashes as separator.
        :param mode: resource file opening mode, default is 'rb'.
        )openre   rf   r   ri   )rC   resourcemoder=   r=   r>   open_instance_resource  s    
zFlask.open_instance_resourcec             C   s$   |  j  d } | d k	 r | S|  j S)am  Reload templates when they are changed. Used by
        :meth:`create_jinja_environment`.

        This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If
        not set, it will be enabled in debug mode.

        .. versionadded:: 1.0
            This property was added but the underlying config and behavior
            already existed.
        rZ   N)rk   r@   )rC   r   r=   r=   r>   templates_auto_reload  s    zFlask.templates_auto_reloadc             C   s   | |  j  d <d  S)NrZ   )rk   )rC   r<   r=   r=   r>   r     s    c             C   s   t  |  j  } d | k r( |  j | d <d | k rA |  j | d <|  j |  |  } | j j d t d t d |  j	 d t
 d t d t  t j | j d	 <| S)
a  Create the Jinja environment based on :attr:`jinja_options`
        and the various Jinja-related methods of the app. Changing
        :attr:`jinja_options` after this will have no effect. Also adds
        Flask-related globals and filters to the environment.

        .. versionchanged:: 0.11
           ``Environment.auto_reload`` set in accordance with
           ``TEMPLATES_AUTO_RELOAD`` configuration option.

        .. versionadded:: 0.5
        Z
autoescapeauto_reloadr,   r)   rk   r"   r#   r!   Ztojson)r   jinja_optionsselect_jinja_autoescaper   jinja_environmentglobalsupdater,   r)   rk   r"   r#   r!   r   Ztojson_filterfilters)rC   optionsr   r=   r=   r>   r     s    	zFlask.create_jinja_environmentc             C   s
   t  |   S)a  Creates the loader for the Jinja2 environment.  Can be used to
        override just the loader and keeping the rest unchanged.  It's
        discouraged to override this function.  Instead one should override
        the :meth:`jinja_loader` function instead.

        The global loader dispatches between the loaders of the application
        and the individual blueprints.

        .. versionadded:: 0.7
        )r6   )rC   r=   r=   r>   create_global_jinja_loader  s    z Flask.create_global_jinja_loaderc             C   s   | d k r d S| j  d  S)zReturns ``True`` if autoescaping should be active for the given
        template name. If no template name is given, returns `True`.

        .. versionadded:: 0.5
        NT.html.htm.xml.xhtml)r   r   r   r   )endswith)rC   filenamer=   r=   r>   r   )  s    zFlask.select_jinja_autoescapec             C   s   |  j  d } t j } | d k	 r_ | j j } | d k	 r_ | |  j  k r_ t | |  j  |  } | j   } x | D] } | j |    qr W| j |  d S)a  Update the template context with some commonly used variables.
        This injects request, session, config and g into the template
        context as well as everything template context processors want
        to inject.  Note that the as of Flask 0.6, the original values
        in the context will not be overridden if a context processor
        decides to return a value with the same key.

        :param context: the context as a dictionary that is updated in place
                        to add extra variables.
        N)rv   r    topr"   	blueprintr   copyr   )rC   contextfuncsZreqctxbpZorig_ctxfuncr=   r=   r>   update_template_context3  s    	zFlask.update_template_contextc             C   s:   d |  d t  i } x! |  j D] } | j |    q W| S)zReturns the shell context for an interactive shell for this
        application.  This runs all the registered shell context
        processors.

        .. versionadded:: 0.11
        Zappr!   )r!   rw   r   )rC   r   	processorr=   r=   r>   make_shell_contextL  s    zFlask.make_shell_contextc             C   s   |  j  d S)av  Whether debug mode is enabled. When using ``flask run`` to start
        the development server, an interactive debugger will be shown for
        unhandled exceptions, and the server will be reloaded when code
        changes. This maps to the :data:`DEBUG` config key. This is
        enabled when :attr:`env` is ``'development'`` and is overridden
        by the ``FLASK_DEBUG`` environment variable. It may not behave as
        expected if set in code.

        **Do not enable debug mode when deploying in production.**

        Default: ``True`` if :attr:`env` is ``'development'``, or
        ``False`` otherwise.
        rL   )rk   )rC   r=   r=   r>   r@   c  s    zFlask.debugc             C   s    | |  j  d <|  j |  j _ d  S)NrL   )rk   r   r   r   )rC   r<   r=   r=   r>   r@   t  s    c             K   s  t  j j d  d k r3 d d l m } |   d St |  r t j   d t  j k rs t   |  _	 t
   |  _ n d t  j k r t
   |  _ | d k	 r t |  |  _ d } d	 } |  j j d
  }	 d \ }
 } |	 r |	 j d  \ }
 } } | p |
 p | } t t d d   | | f D |   } | j d |  j  | j d |  j  | j d d  t j |  j	 |  j |  j d  d d l m } z | | | |  |  Wd d |  _ Xd S)a  Runs the application on a local development server.

        Do not use ``run()`` in a production setting. It is not intended to
        meet security and performance requirements for a production server.
        Instead, see :ref:`deployment` for WSGI server recommendations.

        If the :attr:`debug` flag is set the server will automatically reload
        for code changes and show a debugger in case an exception happened.

        If you want to run the application in debug mode, but disable the
        code execution on the interactive debugger, you can pass
        ``use_evalex=False`` as parameter.  This will keep the debugger's
        traceback screen active, but disable code execution.

        It is not recommended to use this function for development with
        automatic reloading as this is badly supported.  Instead you should
        be using the :command:`flask` command line script's ``run`` support.

        .. admonition:: Keep in Mind

           Flask will suppress any server error with a generic error page
           unless it is in debug mode.  As such to enable just the
           interactive debugger without the code reloading, you have to
           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
           Setting ``use_debugger`` to ``True`` without being in debug mode
           won't catch any exceptions because there won't be any to
           catch.

        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
            have the server available externally as well. Defaults to
            ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
            if present.
        :param port: the port of the webserver. Defaults to ``5000`` or the
            port defined in the ``SERVER_NAME`` config variable if present.
        :param debug: if given, enable or disable debug mode. See
            :attr:`debug`.
        :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
            files to set environment variables. Will also change the working
            directory to the directory containing the first file found.
        :param options: the options to be forwarded to the underlying Werkzeug
            server. See :func:`werkzeug.serving.run_simple` for more
            information.

        .. versionchanged:: 1.0
            If installed, python-dotenv will be used to load environment
            variables from :file:`.env` and :file:`.flaskenv` files.

            If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`
            environment variables will override :attr:`env` and
            :attr:`debug`.

            Threaded mode is enabled by default.

        .. versionchanged:: 0.10
            The default port is now picked from the ``SERVER_NAME``
            variable.
        ZFLASK_RUN_FROM_CLItruer   )explain_ignored_app_runNZ	FLASK_ENVZFLASK_DEBUGz	127.0.0.1i  rQ   :c             s   s!   |  ] } | d  k	 r | Vq d  S)Nr=   ).0pr=   r=   r>   	<genexpr>  s    zFlask.run.<locals>.<genexpr>Zuse_reloaderZuse_debuggerthreadedTFr   )
run_simple)NN)re   environgetdebughelpersr   r*   r   load_dotenvr(   envr'   r@   r   rk   	partitionintnext
setdefaultZshow_server_bannerr   Zwerkzeug.servingr   rA   )rC   r_   portr@   r   r   r   _hostZ_portserver_nameZsn_hostZsn_port_r   r=   r=   r>   runy  s:    <
(z	Flask.runc             K   s>   |  j  } | d k r% d d l m } | |  |  j d | | S)a  Creates a test client for this application.  For information
        about unit testing head over to :ref:`testing`.

        Note that if you are testing for assertions or exceptions in your
        application code, you must set ``app.testing = True`` in order for the
        exceptions to propagate to the test client.  Otherwise, the exception
        will be handled by the application (not visible to the test client) and
        the only indication of an AssertionError or other exception will be a
        500 status code response to the test client.  See the :attr:`testing`
        attribute.  For example::

            app.testing = True
            client = app.test_client()

        The test client can be used in a ``with`` block to defer the closing down
        of the context until the end of the ``with`` block.  This is useful if
        you want to access the context locals for testing::

            with app.test_client() as c:
                rv = c.get('/?vodka=42')
                assert request.args['vodka'] == '42'

        Additionally, you may pass optional keyword arguments that will then
        be passed to the application's :attr:`test_client_class` constructor.
        For example::

            from flask.testing import FlaskClient

            class CustomClient(FlaskClient):
                def __init__(self, *args, **kwargs):
                    self._authentication = kwargs.pop("authentication")
                    super(CustomClient,self).__init__( *args, **kwargs)

            app.test_client_class = CustomClient
            client = app.test_client(authentication='Basic ....')

        See :class:`~flask.testing.FlaskClient` for more information.

        .. versionchanged:: 0.4
           added support for ``with`` block usage for the client.

        .. versionadded:: 0.7
           The `use_cookies` parameter was added as well as the ability
           to override the client to be used by setting the
           :attr:`test_client_class` attribute.

        .. versionchanged:: 0.11
           Added `**kwargs` to support passing additional keyword arguments to
           the constructor of :attr:`test_client_class`.
        Nr   )FlaskClientuse_cookies)test_client_classr   r   response_class)rC   r   rE   clsr=   r=   r>   test_client  s    3	zFlask.test_clientc             K   s2   |  j  } | d k r% d d l m } | |  |  S)a-  Create a CLI runner for testing CLI commands.
        See :ref:`testing-cli`.

        Returns an instance of :attr:`test_cli_runner_class`, by default
        :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
        passed as the first argument.

        .. versionadded:: 1.0
        Nr   )FlaskCliRunner)test_cli_runner_classr   r   )rC   rE   r   r=   r=   r>   test_cli_runner  s    
	zFlask.test_cli_runnerc             C   s&   t  j t d   |  j j |  |  S)a  Creates or opens a new session.  Default implementation stores all
        session data in a signed cookie.  This requires that the
        :attr:`secret_key` is set.  Instead of overriding this method
        we recommend replacing the :class:`session_interface`.

        .. deprecated: 1.0
            Will be removed in 2.0. Use
            ``session_interface.open_session`` instead.

        :param request: an instance of :attr:`request_class`.
        zf"open_session" is deprecated and will be removed in 2.0. Use "session_interface.open_session" instead.)warningswarnDeprecationWarningsession_interfaceopen_session)rC   r"   r=   r=   r>   r   .  s    
zFlask.open_sessionc             C   s)   t  j t d   |  j j |  | |  S)a2  Saves the session if it needs updates.  For the default
        implementation, check :meth:`open_session`.  Instead of overriding this
        method we recommend replacing the :class:`session_interface`.

        .. deprecated: 1.0
            Will be removed in 2.0. Use
            ``session_interface.save_session`` instead.

        :param session: the session to be saved (a
                        :class:`~werkzeug.contrib.securecookie.SecureCookie`
                        object)
        :param response: an instance of :attr:`response_class`
        zf"save_session" is deprecated and will be removed in 2.0. Use "session_interface.save_session" instead.)r   r   r   r   save_session)rC   r#   responser=   r=   r>   r   C  s    
zFlask.save_sessionc             C   s#   t  j t d   |  j j |   S)a7  Creates a new instance of a missing session.  Instead of overriding
        this method we recommend replacing the :class:`session_interface`.

        .. deprecated: 1.0
            Will be removed in 2.0. Use
            ``session_interface.make_null_session`` instead.

        .. versionadded:: 0.7
        zp"make_null_session" is deprecated and will be removed in 2.0. Use "session_interface.make_null_session" instead.)r   r   r   r   make_null_session)rC   r=   r=   r>   r   Z  s    
zFlask.make_null_sessionc             K   s   d } | j  |  j k rW |  j | j  | k s} t d | |  j | j  | j  f   n& | |  j | j  <|  j j |  d } | j |  | |  d S)aa  Register a :class:`~flask.Blueprint` on the application. Keyword
        arguments passed to this method will override the defaults set on the
        blueprint.

        Calls the blueprint's :meth:`~flask.Blueprint.register` method after
        recording the blueprint in the application's :attr:`blueprints`.

        :param blueprint: The blueprint to register.
        :param url_prefix: Blueprint routes will be prefixed with this.
        :param subdomain: Blueprint routes will match on this subdomain.
        :param url_defaults: Blueprint routes will use these default values for
            view arguments.
        :param options: Additional keyword arguments are passed to
            :class:`~flask.blueprints.BlueprintSetupState`. They can be
            accessed in :meth:`~flask.Blueprint.record` callbacks.

        .. versionadded:: 0.7
        FzA name collision occurred between blueprints %r and %r. Both share the same name "%s". Blueprints that are created on the fly need unique names.TN)r   rx   rB   ry   appendregister)rC   r   r   Zfirst_registrationr=   r=   r>   register_blueprintn  s    #zFlask.register_blueprintc             C   s   t  |  j  S)zhIterates over all blueprints by the order they were registered.

        .. versionadded:: 0.11
        )iterry   )rC   r=   r=   r>   iter_blueprints  s    zFlask.iter_blueprintsc       	      K   s  | d k r t  |  } | | d <| j d d  } | d k rX t | d d  pU d } t | t  rs t d   t d d   | D  } t t | d f    } | d k r t | d	 d  } | d k r d
 | k r d } | j d
  n d } | | O} |  j | d | | } | | _	 |  j
 j |  | d k	 r|  j j |  } | d k	 rw| | k rwt d |   | |  j | <d S)a  Connects a URL rule.  Works exactly like the :meth:`route`
        decorator.  If a view_func is provided it will be registered with the
        endpoint.

        Basically this example::

            @app.route('/')
            def index():
                pass

        Is equivalent to the following::

            def index():
                pass
            app.add_url_rule('/', 'index', index)

        If the view_func is not provided you will need to connect the endpoint
        to a view function like so::

            app.view_functions['index'] = index

        Internally :meth:`route` invokes :meth:`add_url_rule` so if you want
        to customize the behavior via subclassing you only need to change
        this method.

        For more information refer to :ref:`url-route-registrations`.

        .. versionchanged:: 0.2
           `view_func` parameter added.

        .. versionchanged:: 0.6
           ``OPTIONS`` is added automatically as method.

        :param rule: the URL rule as string
        :param endpoint: the endpoint for the registered URL rule.  Flask
                         itself assumes the name of the view function as
                         endpoint
        :param view_func: the function to call when serving a request to the
                          provided endpoint
        :param provide_automatic_options: controls whether the ``OPTIONS``
            method should be added automatically. This can also be controlled
            by setting the ``view_func.provide_automatic_options = False``
            before adding the rule.
        :param options: the options to be forwarded to the underlying
                        :class:`~werkzeug.routing.Rule` object.  A change
                        to Werkzeug is handling of method options.  methods
                        is a list of methods this rule should be limited
                        to (``GET``, ``POST`` etc.).  By default a rule
                        just listens for ``GET`` (and implicitly ``HEAD``).
                        Starting with Flask 0.6, ``OPTIONS`` is implicitly
                        added and handled by the standard request handling.
        Nr^   methodsGETz_Allowed methods have to be iterables of strings, for example: @app.route(..., methods=["POST"])c             s   s   |  ] } | j    Vq d  S)N)upper)r   itemr=   r=   r>   r     s    z%Flask.add_url_rule.<locals>.<genexpr>required_methodsprovide_automatic_optionsOPTIONSTFzFView function mapping is overwriting an existing endpoint function: %s)r   )r$   popr   r;   r   	TypeErrorsetaddurl_rule_classr   r{   rl   r   rB   )	rC   ruler^   r`   r   r   r   r   Zold_funcr=   r=   r>   r     s<    =
	
	
zFlask.add_url_rulec                s       f d d   } | S)a  A decorator that is used to register a view function for a
        given URL rule.  This does the same thing as :meth:`add_url_rule`
        but is intended for decorator usage::

            @app.route('/')
            def index():
                return 'Hello World'

        For more information refer to :ref:`url-route-registrations`.

        :param rule: the URL rule as string
        :param endpoint: the endpoint for the registered URL rule.  Flask
                         itself assumes the name of the view function as
                         endpoint
        :param options: the options to be forwarded to the underlying
                        :class:`~werkzeug.routing.Rule` object.  A change
                        to Werkzeug is handling of method options.  methods
                        is a list of methods this rule should be limited
                        to (``GET``, ``POST`` etc.).  By default a rule
                        just listens for ``GET`` (and implicitly ``HEAD``).
                        Starting with Flask 0.6, ``OPTIONS`` is implicitly
                        added and handled by the standard request handling.
        c                s,     j  d d   }  j  | |     |  S)Nr^   )r   r   )rF   r^   )r   r   rC   r=   r>   	decorator!  s    zFlask.route.<locals>.decoratorr=   )rC   r   r   r   r=   )r   r   rC   r>   route  s    zFlask.routec                s      f d d   } | S)zA decorator to register a function as an endpoint.
        Example::

            @app.endpoint('example.endpoint')
            def example():
                return "example"

        :param endpoint: the name of the endpoint
        c                s   |   j    <|  S)N)rl   )rF   )r^   rC   r=   r>   r   4  s    z!Flask.endpoint.<locals>.decoratorr=   )rC   r^   r   r=   )r^   rC   r>   r^   (  s    zFlask.endpointc             C   sa   t  |  t  r t |  } n |  } t | t  s7 t  t | t  rS | | j f S| d f Sd S)a  Get the exception class being handled. For HTTP status codes
        or ``HTTPException`` subclasses, return both the exception and
        status code.

        :param exc_class_or_code: Any exception class, or an HTTP status
            code as an integer.
        N)r;   r   r
   
issubclass	ExceptionrB   r   code)Zexc_class_or_code	exc_classr=   r=   r>   _get_exc_class_and_code:  s    	zFlask._get_exc_class_and_codec                s      f d d   } | S)a7  Register a function to handle errors by code or exception class.

        A decorator that is used to register a function given an
        error code.  Example::

            @app.errorhandler(404)
            def page_not_found(error):
                return 'This page does not exist', 404

        You can also register handlers for arbitrary exceptions::

            @app.errorhandler(DatabaseError)
            def special_exception_handler(error):
                return 'Database connection failed', 500

        .. versionadded:: 0.7
            Use :meth:`register_error_handler` instead of modifying
            :attr:`error_handler_spec` directly, for application wide error
            handlers.

        .. versionadded:: 0.7
           One can now additionally also register custom exception types
           that do not necessarily have to be a subclass of the
           :class:`~werkzeug.exceptions.HTTPException` class.

        :param code_or_exception: the code as integer for the handler, or
                                  an arbitrary exception
        c                s    j  d    |   |  S)N)_register_error_handler)rF   )code_or_exceptionrC   r=   r>   r   n  s    z%Flask.errorhandler.<locals>.decoratorr=   )rC   r   r   r=   )r   rC   r>   errorhandlerO  s    zFlask.errorhandlerc             C   s   |  j  d | |  d S)zAlternative error attach function to the :meth:`errorhandler`
        decorator that is more straightforward to use for non decorator
        usage.

        .. versionadded:: 0.7
        N)r   )rC   r   rF   r=   r=   r>   register_error_handlert  s    zFlask.register_error_handlerc             C   s   t  | t  r$ t d j |    y |  j |  \ } } Wn' t k
 rf t d j |    Yn X|  j j | i   j | i   } | | | <d S)zq
        :type key: None|str
        :type code_or_exception: int|T<=Exception
        :type f: callable
        zTried to register a handler for an exception instance {0!r}. Handlers can only be registered for exception classes or HTTP error codes.zb'{0}' is not a recognized HTTP error code. Use a subclass of HTTPException with that code instead.N)r;   r   rh   formatr   KeyErrorrm   r   )rC   keyr   rF   r   r   handlersr=   r=   r>   r   ~  s    !zFlask._register_error_handlerc                s      f d d   } | S)a  A decorator that is used to register custom template filter.
        You can specify a name for the filter, otherwise the function
        name will be used. Example::

          @app.template_filter()
          def reverse(s):
              return s[::-1]

        :param name: the optional name of the filter, otherwise the
                     function name will be used.
        c                s    j  |  d   |  S)Nr   )add_template_filter)rF   )r   rC   r=   r>   r     s    z(Flask.template_filter.<locals>.decoratorr=   )rC   r   r   r=   )r   rC   r>   template_filter  s    zFlask.template_filterc             C   s   | |  j  j | p | j <d S)zRegister a custom template filter.  Works exactly like the
        :meth:`template_filter` decorator.

        :param name: the optional name of the filter, otherwise the
                     function name will be used.
        N)r   r   __name__)rC   rF   r   r=   r=   r>   r    s    zFlask.add_template_filterc                s      f d d   } | S)aS  A decorator that is used to register custom template test.
        You can specify a name for the test, otherwise the function
        name will be used. Example::

          @app.template_test()
          def is_prime(n):
              if n == 2:
                  return True
              for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
                  if n % i == 0:
                      return False
              return True

        .. versionadded:: 0.10

        :param name: the optional name of the test, otherwise the
                     function name will be used.
        c                s    j  |  d   |  S)Nr   )add_template_test)rF   )r   rC   r=   r>   r     s    z&Flask.template_test.<locals>.decoratorr=   )rC   r   r   r=   )r   rC   r>   template_test  s    zFlask.template_testc             C   s   | |  j  j | p | j <d S)zRegister a custom template test.  Works exactly like the
        :meth:`template_test` decorator.

        .. versionadded:: 0.10

        :param name: the optional name of the test, otherwise the
                     function name will be used.
        N)r   testsr  )rC   rF   r   r=   r=   r>   r    s    
zFlask.add_template_testc                s      f d d   } | S)a  A decorator that is used to register a custom template global function.
        You can specify a name for the global function, otherwise the function
        name will be used. Example::

            @app.template_global()
            def double(n):
                return 2 * n

        .. versionadded:: 0.10

        :param name: the optional name of the global function, otherwise the
                     function name will be used.
        c                s    j  |  d   |  S)Nr   )add_template_global)rF   )r   rC   r=   r>   r     s    z(Flask.template_global.<locals>.decoratorr=   )rC   r   r   r=   )r   rC   r>   template_global  s    zFlask.template_globalc             C   s   | |  j  j | p | j <d S)a  Register a custom template global function. Works exactly like the
        :meth:`template_global` decorator.

        .. versionadded:: 0.10

        :param name: the optional name of the global function, otherwise the
                     function name will be used.
        N)r   r   r  )rC   rF   r   r=   r=   r>   r    s    
zFlask.add_template_globalc             C   s    |  j  j d g   j |  | S)a  Registers a function to run before each request.

        For example, this can be used to open a database connection, or to load
        the logged in user from the session.

        The function will be called without any arguments. If it returns a
        non-None value, the value is handled as if it was the return value from
        the view, and further request handling is stopped.
        N)ro   r   r   )rC   rF   r=   r=   r>   before_request  s    zFlask.before_requestc             C   s   |  j  j |  | S)zRegisters a function to be run before the first request to this
        instance of the application.

        The function will be called without any arguments and its return
        value is ignored.

        .. versionadded:: 0.8
        )rp   r   )rC   rF   r=   r=   r>   before_first_request  s    
zFlask.before_first_requestc             C   s    |  j  j d g   j |  | S)au  Register a function to be run after each request.

        Your function must take one parameter, an instance of
        :attr:`response_class` and return a new response object or the
        same (see :meth:`process_response`).

        As of Flask 0.7 this function might not be executed at the end of the
        request in case an unhandled exception occurred.
        N)rq   r   r   )rC   rF   r=   r=   r>   after_request  s    zFlask.after_requestc             C   s    |  j  j d g   j |  | S)a  Register a function to be run at the end of each request,
        regardless of whether there was an exception or not.  These functions
        are executed when the request context is popped, even if not an
        actual request was performed.

        Example::

            ctx = app.test_request_context()
            ctx.push()
            ...
            ctx.pop()

        When ``ctx.pop()`` is executed in the above example, the teardown
        functions are called just before the request context moves from the
        stack of active contexts.  This becomes relevant if you are using
        such constructs in tests.

        Generally teardown functions must take every necessary step to avoid
        that they will fail.  If they do execute code that might fail they
        will have to surround the execution of these code by try/except
        statements and log occurring errors.

        When a teardown function was called because of an exception it will
        be passed an error object.

        The return values of teardown functions are ignored.

        .. admonition:: Debug Note

           In debug mode Flask will not tear down a request on an exception
           immediately.  Instead it will keep it alive so that the interactive
           debugger can still access it.  This behavior can be controlled
           by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
        N)rr   r   r   )rC   rF   r=   r=   r>   teardown_request'  s    $zFlask.teardown_requestc             C   s   |  j  j |  | S)a  Registers a function to be called when the application context
        ends.  These functions are typically also called when the request
        context is popped.

        Example::

            ctx = app.app_context()
            ctx.push()
            ...
            ctx.pop()

        When ``ctx.pop()`` is executed in the above example, the teardown
        functions are called just before the app context moves from the
        stack of active contexts.  This becomes relevant if you are using
        such constructs in tests.

        Since a request context typically also manages an application
        context it would also be called when you pop a request context.

        When a teardown function was called because of an unhandled exception
        it will be passed an error object. If an :meth:`errorhandler` is
        registered, it will handle the exception and the teardown will not
        receive it.

        The return values of teardown functions are ignored.

        .. versionadded:: 0.9
        )rs   r   )rC   rF   r=   r=   r>   teardown_appcontextN  s    zFlask.teardown_appcontextc             C   s   |  j  d j |  | S)z0Registers a template context processor function.N)rv   r   )rC   rF   r=   r=   r>   context_processoro  s    zFlask.context_processorc             C   s   |  j  j |  | S)zVRegisters a shell context processor function.

        .. versionadded:: 0.11
        )rw   r   )rC   rF   r=   r=   r>   shell_context_processoru  s    zFlask.shell_context_processorc             C   s    |  j  j d g   j |  | S)a#  Register a URL value preprocessor function for all view
        functions in the application. These functions will be called before the
        :meth:`before_request` functions.

        The function can modify the values captured from the matched url before
        they are passed to the view. For example, this can be used to pop a
        common language code value and place it in ``g`` rather than pass it to
        every view.

        The function is passed the endpoint name and values dict. The return
        value is ignored.
        N)rt   r   r   )rC   rF   r=   r=   r>   url_value_preprocessor~  s    zFlask.url_value_preprocessorc             C   s    |  j  j d g   j |  | S)zCallback function for URL defaults for all view functions of the
        application.  It's called with the endpoint and values and should
        update the values passed in place.
        N)ru   r   r   )rC   rF   r=   r=   r>   url_defaults  s    zFlask.url_defaultsc       	      C   s   |  j  t |   \ } } x t j | f d | f t j d f d f D]f \ } } |  j j | i   j |  } | sy qF x0 | j D]% } | j |  } | d k	 r | Sq WqF Wd S)a(  Return a registered error handler for an exception in this order:
        blueprint handler for a specific code, app handler for a specific code,
        blueprint handler for an exception class, app handler for an exception
        class, or ``None`` if a suitable handler is not found.
        N)NN)r   typer"   r   rm   r   r   __mro__)	rC   er   r   r   cZhandler_mapr   handlerr=   r=   r>   _find_error_handler  s    	zFlask._find_error_handlerc             C   sO   | j  d k r | St | t  r& | S|  j |  } | d k rE | S| |  S)ac  Handles an HTTP exception.  By default this will invoke the
        registered error handlers and fall back to returning the
        exception as response.

        .. versionchanged:: 1.0.3
            ``RoutingException``, used internally for actions such as
             slash redirects during routing, is not passed to error
             handlers.

        .. versionchanged:: 1.0
            Exceptions are looked up by code *and* by MRO, so
            ``HTTPExcpetion`` subclasses can be handled with a catch-all
            handler for the base ``HTTPException``.

        .. versionadded:: 0.3
        N)r   r;   r   r  )rC   r  r  r=   r=   r>   handle_http_exception  s    zFlask.handle_http_exceptionc             C   s]   |  j  d r d S|  j  d } | d k rF |  j rF t | t  rF d S| rY t | t  Sd S)a  Checks if an HTTP exception should be trapped or not.  By default
        this will return ``False`` for all exceptions except for a bad request
        key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``.  It
        also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.

        This is called for all HTTP exceptions raised by a view function.
        If it returns ``True`` for any exception the error handler for this
        exception is not called and it shows up as regular exception in the
        traceback.  This is helpful for debugging implicitly raised HTTP
        exceptions.

        .. versionchanged:: 1.0
            Bad request errors are not trapped by default in debug mode.

        .. versionadded:: 0.8
        rW   TrV   NF)rk   r@   r;   r	   r   )rC   r  Ztrap_bad_requestr=   r=   r>   trap_http_exception  s    	zFlask.trap_http_exceptionc             C   s   t  j   \ } } } | | k s' t  t | t  r |  j sL |  j d r d | _ | j d | j	   k r d j
 | j   | _ n t t d  s f  | _ t | t  r |  j |  r |  j |  S|  j |  } | d k r t | | |  | |  S)a>  This method is called whenever an exception occurs that
        should be handled. A special case is :class:`~werkzeug
        .exceptions.HTTPException` which is forwarded to the
        :meth:`handle_http_exception` method. This function will either
        return a response value or reraise the exception with the same
        traceback.

        .. versionchanged:: 1.0
            Key errors raised from request data like ``form`` show the
            bad key in debug mode rather than a generic bad request
            message.

        .. versionadded:: 0.7
        rV   Tr   zKeyError: '{}'show_exceptionN)r   exc_inforB   r;   r	   r@   rk   r  rD   get_descriptionr   descriptionhasattrr   r  r  r  r   )rC   r  exc_type	exc_valuetbr  r=   r=   r>   handle_user_exception  s    		zFlask.handle_user_exceptionc             C   s   t  j   \ } } } t j |  d | |  j rV | | k rP t | | |  n |  |  j | | | f  t   } | | _ |  j	 |  } | d k	 r | |  } |  j
 | d d S)a  Handle an exception that did not have an error handler
        associated with it, or that was raised from an error handler.
        This always causes a 500 ``InternalServerError``.

        Always sends the :data:`got_request_exception` signal.

        If :attr:`propagate_exceptions` is ``True``, such as in debug
        mode, the error will be re-raised so that the debugger can
        display it. Otherwise, the original exception is logged, and
        an :exc:`~werkzeug.exceptions.InternalServerError` is returned.

        If an error handler is registered for ``InternalServerError`` or
        ``500``, it will be used. For consistency, the handler will
        always receive the ``InternalServerError``. The original
        unhandled exception is available as ``e.original_exception``.

        .. note::
            Prior to Werkzeug 1.0.0, ``InternalServerError`` will not
            always have an ``original_exception`` attribute. Use
            ``getattr(e, "original_exception", None)`` to simulate the
            behavior for compatibility.

        .. versionchanged:: 1.1.0
            Always passes the ``InternalServerError`` instance to the
            handler, setting ``original_exception`` to the unhandled
            error.

        .. versionchanged:: 1.1.0
            ``after_request`` functions and other finalization is done
            even for the default 500 response when there is no handler.

        .. versionadded:: 0.3
        	exceptionNfrom_error_handlerT)r   r  r1   sendr   r   log_exceptionr   Zoriginal_exceptionr  finalize_request)rC   r  r   r!  r"  server_errorr  r=   r=   r>   handle_exception   s    "			zFlask.handle_exceptionc             C   s*   |  j  j d t j t j f d | d S)a  Logs an exception.  This is called by :meth:`handle_exception`
        if debugging is disabled and right before the handler is called.
        The default implementation logs the exception as error on the
        :attr:`logger`.

        .. versionadded:: 0.8
        zException on %s [%s]r  N)r   errorr"   rf   method)rC   r  r=   r=   r>   r'  [  s    	zFlask.log_exceptionc             C   sU   |  j  s, t | j t  s, | j d k r5 | j  d d l m } | |   d S)a.  Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        r   HEADr   r   )FormDataRoutingRedirectN)r   r-  r   )r@   r;   routing_exceptionr   r,  r   r.  )rC   r"   r.  r=   r=   r>   raise_routing_exceptiong  s    	
	zFlask.raise_routing_exceptionc             C   ss   t  j j } | j d k	 r( |  j |  | j } t | d d  r\ | j d k r\ |  j   S|  j	 | j
 | j   S)a  Does the request dispatching.  Matches the URL and returns the
        return value of the view or error handler.  This does not have to
        be a response object.  In order to convert the return value to a
        proper response object, call :func:`make_response`.

        .. versionchanged:: 0.7
           This no longer does the exception handling, this code was
           moved to the new :meth:`full_dispatch_request`.
        Nr   Fr   )r    r   r"   r/  r0  Zurl_ruler   r,  make_default_options_responserl   r^   	view_args)rC   reqr   r=   r=   r>   dispatch_requestz  s    
	
zFlask.dispatch_requestc             C   s   |  j    y5 t j |   |  j   } | d k r> |  j   } Wn4 t k
 ru } z |  j |  } WYd d } ~ Xn X|  j |  S)zDispatches the request and on top of that performs request
        pre and postprocessing as well as HTTP exception catching and
        error handling.

        .. versionadded:: 0.7
        N)*try_trigger_before_first_request_functionsr3   r&  preprocess_requestr4  r   r#  r(  )rC   r   r  r=   r=   r>   full_dispatch_request  s    
"zFlask.full_dispatch_requestc             C   sg   |  j  |  } y& |  j |  } t j |  d | Wn+ t k
 rb | sN   |  j j d  Yn X| S)a)  Given the return value from a view function this finalizes
        the request by converting it into a response and invoking the
        postprocessing functions.  This is invoked for both normal
        request dispatching as well as error handlers.

        Because this means that it might be called as a result of a
        failure a special safe mode is available which can be enabled
        with the `from_error_handler` flag.  If enabled, failures in
        response processing will be logged and otherwise ignored.

        :internal:
        r   z?Request finalizing failed with an error while handling an error)make_responseprocess_responser2   r&  r   r   r$  )rC   r   r%  r   r=   r=   r>   r(    s    	zFlask.finalize_requestc          	   C   sS   |  j  r d S|  j 6 |  j  r$ d Sx |  j D] } |   q. Wd |  _  Wd QRXd S)zCalled before each request and will ensure that it triggers
        the :attr:`before_first_request_funcs` and only exactly once per
        application instance (which means process usually).

        :internal:
        NT)rA   r~   rp   )rC   r   r=   r=   r>   r5    s    	
	z0Flask.try_trigger_before_first_request_functionsc             C   s   t  j j } t | d  r* | j   } n\ g  } y | j d d  Wn? t k
 rt } z | j } WYd d } ~ Xn t k
 r Yn X|  j	   } | j
 j |  | S)zThis method is called to create the default ``OPTIONS`` response.
        This can be changed through subclassing to change the default
        behavior of ``OPTIONS`` responses.

        .. versionadded:: 0.7
        allowed_methodsr,  z--N)r    r   Zurl_adapterr  r:  matchr   Zvalid_methodsr   r   Zallowr   )rC   adapterr   r  r   r=   r=   r>   r1    s    z#Flask.make_default_options_responsec             C   s   d S)a
  This is called to figure out if an error should be ignored
        or not as far as the teardown system is concerned.  If this
        function returns ``True`` then the teardown handlers will not be
        passed the error.

        .. versionadded:: 0.10
        Fr=   )rC   r+  r=   r=   r>   should_ignore_error  s    zFlask.should_ignore_errorc             C   s%  d } } t  | t  r t |  } | d k rC | \ } } } nU | d k r t  | d t t t t f  r} | \ } } q | \ } } n t d   | d k r t d   t  | |  j  st  | t t	 t
 f  r|  j | d | d | } d } } n t  | t  r t |  } n t  | t  s;t |  ry |  j j | t j  } Wqt k
 r} z= t d	 j d
 | d |   } t t | t j   d  WYd d } ~ XqXn t d j d |    | d k	 rt  | t t	 t
 f  r| | _ n	 | | _ | r!| j j |  | S)a  Convert the return value from a view function to an instance of
        :attr:`response_class`.

        :param rv: the return value from the view function. The view function
            must return a response. Returning ``None``, or the view ending
            without returning, is not allowed. The following types are allowed
            for ``view_rv``:

            ``str`` (``unicode`` in Python 2)
                A response object is created with the string encoded to UTF-8
                as the body.

            ``bytes`` (``str`` in Python 2)
                A response object is created with the bytes as the body.

            ``dict``
                A dictionary that will be jsonify'd before being returned.

            ``tuple``
                Either ``(body, status, headers)``, ``(body, status)``, or
                ``(body, headers)``, where ``body`` is any of the other types
                allowed here, ``status`` is a string or an integer, and
                ``headers`` is a dictionary or a list of ``(key, value)``
                tuples. If ``body`` is a :attr:`response_class` instance,
                ``status`` overwrites the exiting value and ``headers`` are
                extended.

            :attr:`response_class`
                The object is returned unchanged.

            other :class:`~werkzeug.wrappers.Response` class
                The object is coerced to :attr:`response_class`.

            :func:`callable`
                The function is called as a WSGI application. The result is
                used to create a response object.

        .. versionchanged:: 0.9
           Previously a tuple was interpreted as the arguments for the
           response object.
        N      r   zThe view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).zyThe view function did not return a valid response. The function either returned None or ended without a return statement.statusheadersz{e}
The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a {rv.__class__.__name__}.r  r   zThe view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a {rv.__class__.__name__}.)r;   tuplelenr   r   listr   r   r   bytes	bytearrayr-   r   callableZ
force_typer"   r   r   r   r   r  r@  status_coderA  extend)rC   r   r@  rA  Zlen_rvr  Z	new_errorr=   r=   r>   r8    sL    +
			0		zFlask.make_responsec             C   s   | d k	 rS |  j  s' |  j j p* d n d } |  j j | j d |  j d d | S|  j d d k	 r |  j j |  j d d |  j d d |  j d Sd S)	a*  Creates a URL adapter for the given request. The URL adapter
        is created at a point where the request context is not yet set
        up so the request is passed explicitly.

        .. versionadded:: 0.6

        .. versionchanged:: 0.9
           This can now also be called without a request object when the
           URL adapter is created for the application context.

        .. versionchanged:: 1.0
            :data:`SERVER_NAME` no longer implicitly enables subdomain
            matching. Use :attr:`subdomain_matching` instead.
        Nr   rQ   	subdomainscript_namerR   Z
url_schemerX   )r}   r{   Zdefault_subdomainZbind_to_environr   rk   bind)rC   r"   rJ  r=   r=   r>   create_url_adapterc  s    			zFlask.create_url_adapterc             C   sw   |  j  j d f   } d | k rU | j d d  d } t | |  j  j | f    } x | D] } | | |  q\ Wd S)zInjects the URL defaults for the given endpoint directly into
        the values dictionary passed.  This is used internally and
        automatically called on URL building.

        .. versionadded:: 0.7
        N.r   r   )ru   r   rsplitr   )rC   r^   valuesr   r   r   r=   r=   r>   inject_url_defaults  s    zFlask.inject_url_defaultsc       
      C   s   t  j   \ } } } xe |  j D]Z } y& | | | |  } | d k	 rJ | SWq t k
 rx }	 z |	 } WYd d }	 ~	 Xq Xq W| | k r t | | |  |  d S)zIHandle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
        N)r   r  rn   r   r   )
rC   r+  r^   rP  r   r!  r"  r  r   r  r=   r=   r>   handle_url_build_error  s    zFlask.handle_url_build_errorc             C   s   t  j j j } |  j j d f   } | d k	 rU | |  j k rU t | |  j |  } x! | D] } | t j t j  q\ W|  j	 j d f   } | d k	 r | |  j	 k r t | |  j	 |  } x' | D] } |   } | d k	 r | Sq Wd S)a  Called before the request is dispatched. Calls
        :attr:`url_value_preprocessors` registered with the app and the
        current blueprint (if any). Then calls :attr:`before_request_funcs`
        registered with the app and the blueprint.

        If any :meth:`before_request` handler returns a non-None value, the
        value is handled as if it was the return value from the view, and
        further request handling is stopped.
        N)
r    r   r"   r   rt   r   r   r^   r2  ro   )rC   r   r   r   r   r=   r=   r>   r6    s    	zFlask.preprocess_requestc             C   s   t  j } | j j } | j } | d k	 rU | |  j k rU t | t |  j |   } d |  j k r t | t |  j d   } x | D] } | |  } q W|  j j	 | j
  s |  j j |  | j
 |  | S)a  Can be overridden in order to modify the response object
        before it's sent to the WSGI server.  By default this will
        call all the :meth:`after_request` decorated functions.

        .. versionchanged:: 0.5
           As of Flask 0.5 the functions registered for after request
           execution are called in reverse order of registration.

        :param response: a :attr:`response_class` object.
        :return: a new response object or the same, has to be an
                 instance of :attr:`response_class`.
        N)r    r   r"   r   Z_after_request_functionsrq   r   reversedr   Zis_null_sessionr#   r   )rC   r   ctxr   r   r  r=   r=   r>   r9    s    		zFlask.process_responsec             C   s   | t  k r t j   d } t |  j j d f    } t j j j	 } | d k	 r} | |  j k r} t
 | t |  j |   } x | D] } | |  q Wt j |  d | d S)a2  Called after the request is dispatched and the response is
        returned, right before the request context is popped.

        This calls all functions decorated with
        :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
        if a blueprint handled the request. Finally, the
        :data:`request_tearing_down` signal is sent.

        This is called by
        :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
        which may be delayed during testing to maintain access to
        resources.

        :param exc: An unhandled exception raised while dispatching the
            request. Detected from the current exception information if
            not passed. Passed to each teardown function.

        .. versionchanged:: 0.9
            Added the ``exc`` argument.
        r   Nexc)	_sentinelr   r  rS  rr   r   r    r   r"   r   r   r4   r&  )rC   rU  r   r   r   r=   r=   r>   do_teardown_request  s    zFlask.do_teardown_requestc             C   sW   | t  k r t j   d } x! t |  j  D] } | |  q, Wt j |  d | d S)a  Called right before the application context is popped.

        When handling a request, the application context is popped
        after the request context. See :meth:`do_teardown_request`.

        This calls all functions decorated with
        :meth:`teardown_appcontext`. Then the
        :data:`appcontext_tearing_down` signal is sent.

        This is called by
        :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.

        .. versionadded:: 0.9
        r   rU  N)rV  r   r  rS  rs   r0   r&  )rC   rU  r   r=   r=   r>   do_teardown_appcontext  s
    zFlask.do_teardown_appcontextc             C   s
   t  |   S)aF  Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
        block to push the context, which will make :data:`current_app`
        point at this application.

        An application context is automatically pushed by
        :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
        when handling a request, and when running a CLI command. Use
        this to manually create a context outside of these situations.

        ::

            with app.app_context():
                init_db()

        See :doc:`/appcontext`.

        .. versionadded:: 0.9
        )r   )rC   r=   r=   r>   app_context	  s    zFlask.app_contextc             C   s   t  |  |  S)a$  Create a :class:`~flask.ctx.RequestContext` representing a
        WSGI environment. Use a ``with`` block to push the context,
        which will make :data:`request` point at this request.

        See :doc:`/reqcontext`.

        Typically you should not call this from your own code. A request
        context is automatically pushed by the :meth:`wsgi_app` when
        handling a request. Use :meth:`test_request_context` to create
        an environment and context instead of this method.

        :param environ: a WSGI environment
        )r   )rC   r   r=   r=   r>   request_context)	  s    zFlask.request_contextc          
   O   sK   d d l  m } | |  | |  } z |  j | j    SWd | j   Xd S)a  Create a :class:`~flask.ctx.RequestContext` for a WSGI
        environment created from the given values. This is mostly useful
        during testing, where you may want to run a function that uses
        request data without dispatching a full request.

        See :doc:`/reqcontext`.

        Use a ``with`` block to push the context, which will make
        :data:`request` point at the request for the created
        environment. ::

            with test_request_context(...):
                generate_report()

        When using the shell, it may be easier to push and pop the
        context manually to avoid indentation. ::

            ctx = app.test_request_context(...)
            ctx.push()
            ...
            ctx.pop()

        Takes the same arguments as Werkzeug's
        :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
        the application. See the linked Werkzeug docs for most of the
        available arguments. Flask-specific behavior is listed here.

        :param path: URL path being requested.
        :param base_url: Base URL where the app is being served, which
            ``path`` is relative to. If not given, built from
            :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
            :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
        :param subdomain: Subdomain name to append to
            :data:`SERVER_NAME`.
        :param url_scheme: Scheme to use instead of
            :data:`PREFERRED_URL_SCHEME`.
        :param data: The request body, either as a string or a dict of
            form keys and values.
        :param json: If given, this is serialized as JSON and passed as
            ``data``. Also defaults ``content_type`` to
            ``application/json``.
        :param args: other positional arguments passed to
            :class:`~werkzeug.test.EnvironBuilder`.
        :param kwargs: other keyword arguments passed to
            :class:`~werkzeug.test.EnvironBuilder`.
        r   )EnvironBuilderN)r   r[  rZ  Zget_environclose)rC   rD   rE   r[  Zbuilderr=   r=   r>   test_request_context9	  s
    /zFlask.test_request_contextc             C   s   |  j  |  } d } z y | j   |  j   } WnT t k
 rn } z | } |  j |  } WYd d } ~ Xn t j   d }   Yn X| | |  SWd |  j |  r d } | j |  Xd S)a  The actual WSGI application. This is not implemented in
        :meth:`__call__` so that middlewares can be applied without
        losing a reference to the app object. Instead of doing this::

            app = MyMiddleware(app)

        It's a better idea to do this instead::

            app.wsgi_app = MyMiddleware(app.wsgi_app)

        Then you still have the original application object around and
        can continue to call methods on it.

        .. versionchanged:: 0.7
            Teardown events for the request and app contexts are called
            even if an unhandled error occurs. Other events may not be
            called depending on when an error occurs during dispatch.
            See :ref:`callbacks-and-errors`.

        :param environ: A WSGI environment.
        :param start_response: A callable accepting a status code,
            a list of headers, and an optional exception context to
            start the response.
        Nr   )	rZ  pushr7  r   r*  r   r  r=  Zauto_pop)rC   r   start_responserT  r+  r   r  r=   r=   r>   wsgi_appq	  s     
!zFlask.wsgi_appc             C   s   |  j  | |  S)zThe WSGI server calls the Flask application object as the
        WSGI application. This calls :meth:`wsgi_app` which can be
        wrapped to applying middleware.)r`  )rC   r   r_  r=   r=   r>   __call__	  s    zFlask.__call__c             C   s   d |  j  j |  j f S)Nz<%s %r>)	__class__r  r   )rC   r=   r=   r>   __repr__	  s    zFlask.__repr__){r  
__module____qualname____doc__r8   Zrequest_classr9   r   r7   r   r   Zapp_ctx_globals_classr   r   r   r   Z
secret_keyZsession_cookie_namer?   Zpermanent_session_lifetimeZsend_file_max_age_defaultZuse_x_sendfiler   JSONEncoderZjson_encoderJSONDecoderZjson_decoderr   r   r   r   r   r   r   rz   r   r   r/   r   r   r\   r]   ra   r+   r   propertyr   r   r   r   r   rj   rd   r   r   setterr   r   r   r   r   r   r@   r   r   r   r   r   r   rH   r   r   r   r   r^   staticmethodr   r   r   r   r  r  r  r  r	  r  r
  r  r  r  r  r  r  r  r  r  r  r  r#  r*  r'  r0  r4  r7  r(  r5  r1  r=  r8  rM  rQ  rR  r6  r9  rV  rW  rX  rY  rZ  r]  r`  ra  rc  r=   r=   r=   r>   rI   g   s*  a	
			
	#
l8$i %
	'!		!#+;
v&8+rI   )Srf  re   r   r   datetimer   	functoolsr   	itertoolsr   	threadingr   Zwerkzeug.datastructuresr   r   Zwerkzeug.exceptionsr   r	   r
   r   r   r   Zwerkzeug.routingr   r   r   r   r   Zwerkzeug.wrappersr    r   r   _compatr   r   r   r   rk   r   r   rT  r   r   r   r   r    r!   r"   r#   helpersr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   loggingr.   sessionsr/   Zsignalsr0   r1   r2   r3   r4   Z
templatingr5   r6   r7   Zwrappersr8   r9   objectrV  r?   rH   rI   r=   r=   r=   r>   <module>
   s|   	