U
    Ha~                     @   s  d dl Zd dl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$ ej%r8d	dl&m'Z' e( Z)ej*dej+dej,f dZ-e-e-dddZ.G dd  d Z/ej+e0d!d"d#Z1d$d% Z2d&d' Z3e0d(d)d*Z4dS )+    N)defaultdict)update_wrapper)JSONDecoder)JSONEncoder)FileSystemLoader)default_exceptions)HTTPException   )AppGroup)current_app)get_root_path)locked_cached_property)send_from_directory)_default_template_ctx_processor)AfterRequestCallable)AppOrBlueprintKey)BeforeRequestCallableErrorHandlerCallable)TeardownCallable) TemplateContextProcessorCallable)URLDefaultCallable)URLValuePreprocessorCallable)ResponseF.)boundfreturnc                    s.   t jt jt jd fdd}t tt| S )zkWraps a method so that it performs a check in debug mode if the
    first request was already handled.
    )argskwargsr   c                    s    |   rtd | f||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.)_is_setup_finishedAssertionError)selfr   r    r    2/tmp/pip-unpacked-wheel-99zf6fhi/flask/scaffold.pywrapper_func,   s
    
z!setupmethod.<locals>.wrapper_func)tAnycastr   r   )r   r'   r%   r$   r&   setupmethod'   s    r+   c                	   @   s|  e Zd ZU dZeed< dZeje ed< dZ	eje ed< dZ
ejeje  ed< dZejeje  ed< dQeeje eje eje eje dd	d
ZedddZedddZeeje dddZejeje ddddZeedddZeeje dddZejeje ddddZeje eje dddZeddddZeeje ddd ZdReeejej d"d#d$Z eee!ej"d%d&d'Z#eej$ej"d(d)d*Z%eej$ej"d(d+d,Z&eej$ej"d(d-d.Z'eej$ej"d(d/d0Z(eej$ej"d(d1d2Z)eej$ej"d(d3d4Z*e+dSeeje ejej" eje ej$dd5d6d7Z,eej"d8d9d:Z-e+e.e.d;d<d=Z/e+e0e0d;d>d?Z1e+e2e2d;d@dAZ3e+e4e4d;dBdCZ5e+e6e6d;dDdEZ7e+e8e8d;dFdGZ9e+ej:eje; ef ej"e<ge<f dHdIdJZ=e+ej:eje; ef e<ddKdLdMZ>e?ej:eje; ef ej@eje; eje f dNdOdPZAdS )TScaffolda  Common behavior shared between :class:`~flask.Flask` and
    :class:`~flask.blueprints.Blueprint`.

    :param import_name: The import name of the module where this object
        is defined. Usually :attr:`__name__` should be used.
    :param static_folder: Path to a folder of static files to serve.
        If this is set, a static route will be added.
    :param static_url_path: URL prefix for the static route.
    :param template_folder: Path to a folder containing template files.
        for rendering. If this is set, a Jinja loader will be added.
    :param root_path: The path that static, template, and resource files
        are relative to. Typically not set, it is discovered based on
        the ``import_name``.

    .. versionadded:: 2.0
    nameN_static_folder_static_url_pathjson_encoderjson_decoder)import_namestatic_folderstatic_url_pathtemplate_folder	root_pathc                 C   s   || _ || _|| _|| _|d kr*t| j }|| _t | _i | _t	dd | _
t	t| _t	t| _t	t| _t	td tgi| _t	t| _t	t| _d S )Nc                   S   s   t tS N)r   dictr%   r%   r%   r&   <lambda>       z#Scaffold.__init__.<locals>.<lambda>)r2   r3   r4   r5   r   r6   r
   cliview_functionsr   error_handler_speclistbefore_request_funcsafter_request_funcsteardown_request_funcsr   template_context_processorsurl_value_preprocessorsurl_default_functions)r#   r2   r3   r4   r5   r6   r%   r%   r&   __init__[   s.    


zScaffold.__init__)r   c                 C   s   dt | j d| jdS )N< >)type__name__r-   r#   r%   r%   r&   __repr__   s    zScaffold.__repr__c                 C   s   t d S r7   NotImplementedErrorrK   r%   r%   r&   r!      s    zScaffold._is_setup_finishedc                 C   s$   | j dk	rtj| j| j S dS dS )zhThe absolute path to the configured static folder. ``None``
        if no static folder is set.
        N)r.   ospathjoinr6   rK   r%   r%   r&   r3      s    
zScaffold.static_folder)valuer   c                 C   s"   |d k	rt |d}|| _d S )Nz\/)rO   fspathrstripr.   r#   rR   r%   r%   r&   r3      s    c                 C   s
   | j dk	S )zQ``True`` if :attr:`static_folder` is set.

        .. versionadded:: 0.5
        N)r3   rK   r%   r%   r&   has_static_folder  s    zScaffold.has_static_folderc                 C   s<   | j dk	r| j S | jdk	r8tj| j}d| dS dS )zThe URL prefix that the static route will be accessible from.

        If it was not configured during init, it is derived from
        :attr:`static_folder`.
        N/)r/   r3   rO   rP   basenamerT   )r#   rX   r%   r%   r&   r4     s    

zScaffold.static_url_pathc                 C   s   |d k	r| d}|| _d S )NrW   )rT   r/   rU   r%   r%   r&   r4     s    
)filenamer   c                 C   s   t j}|dkrdS t| S )a  Used by :func:`send_file` to determine the ``max_age`` cache
        value for a given file path if it wasn't passed.

        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
        the configuration of :data:`~flask.current_app`. This defaults
        to ``None``, which tells the browser to use conditional requests
        instead of a timed cache, which is usually preferable.

        .. versionchanged:: 2.0
            The default configuration is ``None`` instead of 12 hours.

        .. versionadded:: 0.9
        N)r   Zsend_file_max_age_defaultinttotal_seconds)r#   rY   rR   r%   r%   r&   get_send_file_max_age%  s    zScaffold.get_send_file_max_ager   c                 C   s0   | j std| |}ttt| j||dS )zThe view function used to serve files from
        :attr:`static_folder`. A route is automatically registered for
        this view at :attr:`static_url_path` if :attr:`static_folder` is
        set.

        .. versionadded:: 0.5
        z2'static_folder' must be set to serve static_files.)max_age)rV   RuntimeErrorr\   r   r(   r*   strr3   )r#   rY   r]   r%   r%   r&   send_static_file:  s    
  zScaffold.send_static_filec                 C   s(   | j dk	r ttj| j| j S dS dS )zThe Jinja loader for this object's templates. By default this
        is a class :class:`jinja2.loaders.FileSystemLoader` to
        :attr:`template_folder` if it is set.

        .. versionadded:: 0.5
        N)r5   r   rO   rP   rQ   r6   rK   r%   r%   r&   jinja_loaderL  s    
zScaffold.jinja_loaderrb)resourcemoder   c                 C   s&   |dkrt dttj| j||S )aK  Open a resource file relative to :attr:`root_path` for
        reading.

        For example, if the file ``schema.sql`` is next to the file
        ``app.py`` where the ``Flask`` app is defined, it can be opened
        with:

        .. code-block:: python

            with app.open_resource("schema.sql") as f:
                conn.executescript(f.read())

        :param resource: Path to the resource relative to
            :attr:`root_path`.
        :param mode: Open the file in this mode. Only reading is
            supported, valid values are "r" (or "rt") and "rb".
        >   rrb   rtz)Resources can only be opened for reading.)
ValueErroropenrO   rP   rQ   r6   )r#   rc   rd   r%   r%   r&   open_resourceY  s    zScaffold.open_resource)methodruleoptionsr   c                 C   s(   d|krt d| j|fd|gi|S )Nmethodsz8Use the 'route' decorator to use the 'methods' argument.)	TypeErrorroute)r#   rj   rk   rl   r%   r%   r&   _method_routep  s    zScaffold._method_route)rk   rl   r   c                 K   s   |  d||S )z\Shortcut for :meth:`route` with ``methods=["GET"]``.

        .. versionadded:: 2.0
        GETrp   r#   rk   rl   r%   r%   r&   getv  s    zScaffold.getc                 K   s   |  d||S )z]Shortcut for :meth:`route` with ``methods=["POST"]``.

        .. versionadded:: 2.0
        POSTrr   rs   r%   r%   r&   post}  s    zScaffold.postc                 K   s   |  d||S )z\Shortcut for :meth:`route` with ``methods=["PUT"]``.

        .. versionadded:: 2.0
        PUTrr   rs   r%   r%   r&   put  s    zScaffold.putc                 K   s   |  d||S )z_Shortcut for :meth:`route` with ``methods=["DELETE"]``.

        .. versionadded:: 2.0
        DELETErr   rs   r%   r%   r&   delete  s    zScaffold.deletec                 K   s   |  d||S )z^Shortcut for :meth:`route` with ``methods=["PATCH"]``.

        .. versionadded:: 2.0
        PATCHrr   rs   r%   r%   r&   patch  s    zScaffold.patchc                    s    t jt jd fdd}|S )a  Decorate a view function to register it with the given URL
        rule and options. Calls :meth:`add_url_rule`, which has more
        details about the implementation.

        .. code-block:: python

            @app.route("/")
            def index():
                return "Hello, World!"

        See :ref:`url-route-registrations`.

        The endpoint name for the route defaults to the name of the view
        function if the ``endpoint`` parameter isn't passed.

        The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
        ``OPTIONS`` are added automatically.

        :param rule: The URL rule string.
        :param options: Extra options passed to the
            :class:`~werkzeug.routing.Rule` object.
        r   c                    s"     dd }j|| f  | S )Nendpoint)popadd_url_rule)r   r}   rl   rk   r#   r%   r&   	decorator  s    z!Scaffold.route.<locals>.decorator)r(   Callable)r#   rk   rl   r   r%   r   r&   ro     s    zScaffold.route)rk   r}   	view_funcprovide_automatic_optionsrl   r   c                 K   s   t dS )a;  Register a rule for routing incoming requests and building
        URLs. The :meth:`route` decorator is a shortcut to call this
        with the ``view_func`` argument. These are equivalent:

        .. code-block:: python

            @app.route("/")
            def index():
                ...

        .. code-block:: python

            def index():
                ...

            app.add_url_rule("/", view_func=index)

        See :ref:`url-route-registrations`.

        The endpoint name for the route defaults to the name of the view
        function if the ``endpoint`` parameter isn't passed. An error
        will be raised if a function has already been registered for the
        endpoint.

        The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
        always added automatically, and ``OPTIONS`` is added
        automatically by default.

        ``view_func`` does not necessarily need to be passed, but if the
        rule should participate in routing an endpoint name must be
        associated with a view function at some point with the
        :meth:`endpoint` decorator.

        .. code-block:: python

            app.add_url_rule("/", endpoint="index")

            @app.endpoint("index")
            def index():
                ...

        If ``view_func`` has a ``required_methods`` attribute, those
        methods are added to the passed and automatic methods. If it
        has a ``provide_automatic_methods`` attribute, it is used as the
        default if the parameter is not passed.

        :param rule: The URL rule string.
        :param endpoint: The endpoint name to associate with the rule
            and view function. Used when routing and building URLs.
            Defaults to ``view_func.__name__``.
        :param view_func: The view function to associate with the
            endpoint name.
        :param provide_automatic_options: Add the ``OPTIONS`` method and
            respond to ``OPTIONS`` requests automatically.
        :param options: Extra options passed to the
            :class:`~werkzeug.routing.Rule` object.
        NrM   )r#   rk   r}   r   r   rl   r%   r%   r&   r     s    BzScaffold.add_url_rule)r}   r   c                    s    fdd}|S )a  Decorate a view function to register it for the given
        endpoint. Used if a rule is added without a ``view_func`` with
        :meth:`add_url_rule`.

        .. code-block:: python

            app.add_url_rule("/ex", endpoint="example")

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

        :param endpoint: The endpoint name to associate with the view
            function.
        c                    s   | j  < | S r7   )r<   r$   r}   r#   r%   r&   r     s    
z$Scaffold.endpoint.<locals>.decoratorr%   )r#   r}   r   r%   r   r&   r}     s    zScaffold.endpointr   c                 C   s   | j dg | |S )a`  Register 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.

        .. code-block:: python

            @app.before_request
            def load_user():
                if "user_id" in session:
                    g.user = db.session.get(session["user_id"])

        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)r?   
setdefaultappendr#   r   r%   r%   r&   before_request  s    zScaffold.before_requestc                 C   s   | j dg | |S )a	  Register a function to run after each request to this object.

        The function is called with the response object, and must return
        a response object. This allows the functions to modify or
        replace the response before it is sent.

        If a function raises an exception, any remaining
        ``after_request`` functions will not be called. Therefore, this
        should not be used for actions that must execute, such as to
        close resources. Use :meth:`teardown_request` for that.
        N)r@   r   r   r   r%   r%   r&   after_request)  s    zScaffold.after_requestc                 C   s   | j dg | |S )ar  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.

        Teardown functions must avoid raising exceptions, since they . If they
        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)rA   r   r   r   r%   r%   r&   teardown_request9  s    $zScaffold.teardown_requestc                 C   s   | j d | |S )z0Registers a template context processor function.N)rB   r   r   r%   r%   r&   context_processor`  s    zScaffold.context_processorc                 C   s   | j d | |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)rC   r   r   r%   r%   r&   url_value_preprocessorh  s    zScaffold.url_value_preprocessorc                 C   s   | j d | |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)rD   r   r   r%   r%   r&   url_defaults{  s    zScaffold.url_defaults)code_or_exceptionr   c                    s   t t d 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
        r   c                    s     |  | S r7   )register_error_handlerr$   r   r#   r%   r&   r     s    z(Scaffold.errorhandler.<locals>.decoratorr   )r#   r   r   r%   r   r&   errorhandler  s    !zScaffold.errorhandler)r   r   r   c                 C   sh   t |trtd|dz| |\}}W n$ tk
rP   td| dY nX || 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
        z6Tried to register a handler for an exception instance zL. Handlers can only be registered for exception classes or HTTP error codes.'z^' is not a recognized HTTP error code. Use a subclass of HTTPException with that code instead.N)
isinstancer   rg   _get_exc_class_and_codeKeyErrorr=   )r#   r   r   	exc_classcoder%   r%   r&   r     s    



zScaffold.register_error_handler)exc_class_or_coder   c                 C   sJ   t | trt|  }n| }t|ts*tdt|tr>||jfS |dfS d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.
        z2Custom exceptions must be subclasses of Exception.N)r   rZ   r   
issubclass	Exceptionr"   r   r   )r   r   r%   r%   r&   r     s    

 

z Scaffold._get_exc_class_and_code)NNNN)rb   )NNN)BrJ   
__module____qualname____doc__r_   __annotations__r.   r(   Optionalr/   r0   Typer   r1   r   rE   rL   boolr!   propertyr3   setterrV   r4   rZ   r\   r`   r   r   ra   IOAnyStrri   r8   r   rp   r)   rt   rv   rx   rz   r|   ro   r+   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   Unionr   r   r   r   staticmethodTupler   r%   r%   r%   r&   r,   =   s   
     	   
C&&r,   )r   r   c                 C   s   | dk	st d| jS )zsInternal helper that returns the default endpoint for a given
    function.  This always is the function name.
    Nz/expected view func if endpoint is not provided.)r"   rJ   )r   r%   r%   r&   _endpoint_from_view_func  s    r   c                 C   sJ   t | dr| |S t| }|jdkr4|jdkr4dS td|j ddS )zAttempt to figure out if the given name is a package or a module.

    :param: loader: The loader that handled the name.
    :param mod_name: The name of the package or module.
    
is_package_frozen_importlibZNamespaceLoaderTr   z<.is_package()' must be implemented for PEP 302 import hooks.N)hasattrr   rI   r   rJ   AttributeError)loadermod_nameclsr%   r%   r&   )_matching_loader_thinks_module_is_package  s    

r   c              	   C   s
  z t j| }|dkrtdW n ttfk
r8   Y nLX |jdkrZtjt	t
|jS |jrvtjtj|jS tj|jS t| }|dks| dkrt S t|dr|| }nt|dr|j}nt | j}tjtj|}t|| rtj|}|S )z2Find the path that contains the package or module.Nz	not found>   N	namespace__main__get_filenamearchive)	importlibutil	find_specrg   ImportErrororiginrO   rP   dirnamenextitersubmodule_search_locationspkgutil
get_loadergetcwdr   r   r   import_module__file__abspathr   )root_mod_namespecr   rY   package_pathr%   r%   r&   _find_package_path  s.    



r   )r2   c           	      C   s   |  d\}}}t|}tjtj}||r8||fS tj|\}}|	 dkrtj|\}}|	 dkrx||fS tj
|	 dkrtj||fS ||fS d|fS )a  Find the prefix that a package is installed under, and the path
    that it would be imported from.

    The prefix is the directory containing the standard directory
    hierarchy (lib, bin, etc.). If the package is not installed to the
    system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
    ``None`` is returned.

    The path is the entry in :attr:`sys.path` that contains the package
    for import. If the package is not installed, it's assumed that the
    package was imported from the current working directory.
    .zsite-packageslibN)	partitionr   rO   rP   r   sysprefix
startswithsplitlowerrX   r   )	r2   r   _r   Z	py_prefixZsite_parentZsite_folderparentfolderr%   r%   r&   find_package9  s    
r   )5importlib.utilr   rO   r   r   typingr(   collectionsr   	functoolsr   jsonr   r   Zjinja2r   Zwerkzeug.exceptionsr   r   r;   r
   globalsr   Zhelpersr   r   r   Z
templatingr   r   r   r   r   r   r   r   r   TYPE_CHECKINGwrappersr   object	_sentinelTypeVarr   r)   r   r+   r,   r_   r   r   r   r   r%   r%   r%   r&   <module>   sP        ,4