
_B              	   @   s/  d  Z  d d l Z d d l Z d d l Z 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( d d l) m* Z* e+   Z, e- d d   e j. j/ e j. j0 g D  Z1 d d   Z2 d d   Z3 d  d! d"  Z4 d# d$   Z5 d% d&   Z6 d' d(   Z7 d) d*   Z8 d+ d,   Z9 d- d. d/  Z: d0 f  d1 d2  Z; d d0 d d  d d0 d d3 d4  Z< d5 d6   Z= d7 d8   Z> d9 d:   Z? d; d<   Z@ d= d>   ZA d? d@   ZB GdA dB   dB e+  ZC GdC dD   dD e+  ZD dE dF   ZE dG dH   ZF d S)Iz
    flask.helpers
    ~~~~~~~~~~~~~

    Implements various helpers.

    :copyright: 2010 Pallets
    :license: BSD-3-Clause
    N)update_wrapper)RLock)time)adler32)FileSystemLoader)Headers)
BadRequest)NotFound)RequestedRangeNotSatisfiable)
BuildError)	url_quote)	wrap_file   )fspath)PY2)string_types)	text_type)_app_ctx_stack)_request_ctx_stack)current_app)request)session)message_flashedc             c   s!   |  ] } | d k r | Vq d  S)N/)Nr    ).0sepr   r   ./tmp/pip-build-5gj8f0j9/flask/flask/helpers.py	<genexpr>4   s    r   c               C   s   t  j j d  p d S)zGet the environment the app is running in, indicated by the
    :envvar:`FLASK_ENV` environment variable. The default is
    ``'production'``.
    Z	FLASK_ENV
production)osenvirongetr   r   r   r   get_env8   s    r#   c              C   s5   t  j j d  }  |  s% t   d k S|  j   d k S)zGet whether debug mode should be enabled for the app, indicated
    by the :envvar:`FLASK_DEBUG` environment variable. The default is
    ``True`` if :func:`.get_env` returns ``'development'``, or ``False``
    otherwise.
    ZFLASK_DEBUGZdevelopment0falseno)r$   r%   r&   )r    r!   r"   r#   lower)valr   r   r   get_debug_flag@   s    r)   Tc             C   s,   t  j j d  } | s |  S| j   d k S)zGet whether the user has disabled loading dotenv files by setting
    :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the
    files.

    :param default: What to return if the env var isn't set.
    ZFLASK_SKIP_DOTENVr$   r%   r&   )r$   r%   r&   )r    r!   r"   r'   )defaultr(   r   r   r   get_load_dotenvN   s    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.)AssertionError__name__)Z	view_funcr   r   r   _endpoint_from_view_func]   s    r.   c                sm   y t      Wn1 t k
 rC  f d d   } t |   SYn X  f d d   } |   } t |  | S)a  Request contexts disappear when the response is started on the server.
    This is done for efficiency reasons and to make it less likely to encounter
    memory leaks with badly written WSGI middlewares.  The downside is that if
    you are using streamed responses, the generator cannot access request bound
    information any more.

    This function however can help you keep the context around for longer::

        from flask import stream_with_context, request, Response

        @app.route('/stream')
        def streamed_response():
            @stream_with_context
            def generate():
                yield 'Hello '
                yield request.args['name']
                yield '!'
            return Response(generate())

    Alternatively it can also be used around a specific generator::

        from flask import stream_with_context, request, Response

        @app.route('/stream')
        def streamed_response():
            def generate():
                yield 'Hello '
                yield request.args['name']
                yield '!'
            return Response(stream_with_context(generate()))

    .. versionadded:: 0.9
    c                 s     |  |   } t  |  S)N)stream_with_context)argskwargsgen)generator_or_functionr   r   	decorator   s    z&stream_with_context.<locals>.decoratorc              3   so   t  j }  |  d  k r! t d   |  A d  Vz x   D] } | Vq7 WWd  t   d  rc   j   XWd  QRXd  S)Nz\Attempted to stream with context but there was no context in the first place to keep around.close)r   topRuntimeErrorhasattrr5   )ctxitem)r2   r   r   	generator   s    		z&stream_with_context.<locals>.generator)iter	TypeErrorr   next)r3   r4   r;   Z	wrapped_gr   )r2   r3   r   r/   e   s    "	
r/   c              G   s9   |  s t  j   St |   d k r, |  d }  t  j |   S)ay  Sometimes it is necessary to set additional headers in a view.  Because
    views do not have to return response objects but can return a value that
    is converted into a response object by Flask itself, it becomes tricky to
    add headers to it.  This function can be called instead of using a return
    and you will get a response object which you can use to attach headers.

    If view looked like this and you want to add a new header::

        def index():
            return render_template('index.html', foo=42)

    You can now do something like this::

        def index():
            response = make_response(render_template('index.html', foo=42))
            response.headers['X-Parachutes'] = 'parachutes are cool'
            return response

    This function accepts the very same arguments you can return from a
    view function.  This for example creates a response with a 404 error
    code::

        response = make_response(render_template('not_found.html'), 404)

    The other use case of this function is to force the return value of a
    view function into a response which is helpful with view
    decorators::

        response = make_response(view_function())
        response.headers['X-Parachutes'] = 'parachutes are cool'

    Internally this function does the following things:

    -   if no arguments are passed, it creates a new response argument
    -   if one argument is passed, :meth:`flask.Flask.make_response`
        is invoked with it.
    -   if more than one argument is passed, the arguments are passed
        to the :meth:`flask.Flask.make_response` function as tuple.

    .. versionadded:: 0.6
    r   r   )r   response_classlenmake_response)r0   r   r   r   rA      s
    *

rA   c             K   s  t  j } t j } | d k r* t d   | d k	 r | j } t j } |  d d  d k r | d k	 rw | |  }  n |  d d  }  | j d d  } n3 | j } | d k r t d   | j d d  } | j d	 d  } | j d
 d  } | j d d  }	 | j j	 |  |  d }
 |	 d k	 rN| s<t
 d   | j }
 |	 | _ y? z" | j |  | d | d | } Wd |
 d k	 r|
 | _ XWnc t k
 r} zC | | d <| | d	 <| | d
 <|	 | d <| j j | |  |  SWYd d } ~ Xn X| d k	 r| d t |  7} | S)a  Generates a URL to the given endpoint with the method provided.

    Variable arguments that are unknown to the target endpoint are appended
    to the generated URL as query arguments.  If the value of a query argument
    is ``None``, the whole pair is skipped.  In case blueprints are active
    you can shortcut references to the same blueprint by prefixing the
    local endpoint with a dot (``.``).

    This will reference the index function local to the current blueprint::

        url_for('.index')

    For more information, head over to the :ref:`Quickstart <url-building>`.

    Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when
    generating URLs outside of a request context.

    To integrate applications, :class:`Flask` has a hook to intercept URL build
    errors through :attr:`Flask.url_build_error_handlers`.  The `url_for`
    function results in a :exc:`~werkzeug.routing.BuildError` when the current
    app does not have a URL for the given endpoint and values.  When it does, the
    :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
    it is not ``None``, which can return a string to use as the result of
    `url_for` (instead of `url_for`'s default to raise the
    :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
    An example::

        def external_url_handler(error, endpoint, values):
            "Looks up an external URL when `url_for` cannot build a URL."
            # This is an example of hooking the build_error_handler.
            # Here, lookup_url is some utility function you've built
            # which looks up the endpoint in some external URL registry.
            url = lookup_url(endpoint, **values)
            if url is None:
                # External lookup did not have a URL.
                # Re-raise the BuildError, in context of original traceback.
                exc_type, exc_value, tb = sys.exc_info()
                if exc_value is error:
                    raise exc_type, exc_value, tb
                else:
                    raise error
            # url_for will use this result, instead of raising BuildError.
            return url

        app.url_build_error_handlers.append(external_url_handler)

    Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
    `endpoint` and `values` are the arguments passed into `url_for`.  Note
    that this is for building URLs outside the current application, and not for
    handling 404 NotFound errors.

    .. versionadded:: 0.10
       The `_scheme` parameter was added.

    .. versionadded:: 0.9
       The `_anchor` and `_method` parameters were added.

    .. versionadded:: 0.9
       Calls :meth:`Flask.handle_build_error` on
       :exc:`~werkzeug.routing.BuildError`.

    :param endpoint: the endpoint of the URL (name of the function)
    :param values: the variable arguments of the URL rule
    :param _external: if set to ``True``, an absolute URL is generated. Server
      address can be changed via ``SERVER_NAME`` configuration variable which
      falls back to the `Host` header, then to the IP and port of the request.
    :param _scheme: a string specifying the desired URL scheme. The `_external`
      parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
      behavior uses the same scheme as the current request, or
      ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
      request context is available. As of Werkzeug 0.10, this also can be set
      to an empty string to build protocol-relative URLs.
    :param _anchor: if provided this is added as anchor to the URL.
    :param _method: if provided this explicitly specifies an HTTP method.
    NzAttempted to generate a URL without the application context being pushed. This has to be executed when application context is available.r   .Z	_externalFzApplication was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.TZ_anchor_method_schemez/When specifying _scheme, _external must be TruemethodZforce_external#)r   r6   r   r7   url_adapterr   Z	blueprintpopZappZinject_url_defaults
ValueErrorZ
url_schemebuildr   Zhandle_url_build_errorr   )ZendpointvaluesZappctxZreqctxrG   Zblueprint_nameZexternalanchorrE   schemeZ
old_schemerverrorr   r   r   url_for   sV    L									



)rP   c             C   s   t  t j j |   j |  S)aX  Loads a macro (or variable) a template exports.  This can be used to
    invoke a macro from within Python code.  If you for example have a
    template named :file:`_cider.html` with the following contents:

    .. sourcecode:: html+jinja

       {% macro hello(name) %}Hello {{ name }}!{% endmacro %}

    You can access this from Python code like this::

        hello = get_template_attribute('_cider.html', 'hello')
        return hello('World')

    .. versionadded:: 0.2

    :param template_name: the name of the template
    :param attribute: the name of the variable of macro to access
    )getattrr   Z	jinja_envZget_templatemodule)Ztemplate_name	attributer   r   r   get_template_attributey  s    rT   messagec             C   sR   t  j d g   } | j | |  f  | t  d <t j t j   d |  d | d S)a  Flashes a message to the next request.  In order to remove the
    flashed message from the session and to display it to the user,
    the template has to call :func:`get_flashed_messages`.

    .. versionchanged:: 0.3
       `category` parameter added.

    :param message: the message to be flashed.
    :param category: the category for the message.  The following values
                     are recommended: ``'message'`` for any kind of message,
                     ``'error'`` for errors, ``'info'`` for information
                     messages and ``'warning'`` for warnings.  However any
                     kind of string can be used as category.
    _flashesrU   categoryN)r   r"   appendr   sendr   Z_get_current_object)rU   rW   flashesr   r   r   flash  s
    
r[   Fc                s   t  j j } | d k rC d t k r3 t j d  n g  t  j _ }   rj t t   f d d   |   } |  s d d   | D S| S)a  Pulls all flashed messages from the session and returns them.
    Further calls in the same request to the function will return
    the same messages.  By default just the messages are returned,
    but when `with_categories` is set to ``True``, the return value will
    be a list of tuples in the form ``(category, message)`` instead.

    Filter the flashed messages to one or more categories by providing those
    categories in `category_filter`.  This allows rendering categories in
    separate html blocks.  The `with_categories` and `category_filter`
    arguments are distinct:

    * `with_categories` controls whether categories are returned with message
      text (``True`` gives a tuple, where ``False`` gives just the message text).
    * `category_filter` filters the messages down to only those matching the
      provided categories.

    See :ref:`message-flashing-pattern` for examples.

    .. versionchanged:: 0.3
       `with_categories` parameter added.

    .. versionchanged:: 0.9
        `category_filter` parameter added.

    :param with_categories: set to ``True`` to also receive categories.
    :param category_filter: whitelist of categories to limit return values
    NrV   c                s   |  d   k S)Nr   r   )f)category_filterr   r   <lambda>  s    z&get_flashed_messages.<locals>.<lambda>c             S   s   g  |  ] } | d   q S)r   r   )r   xr   r   r   
<listcomp>  s   	 z(get_flashed_messages.<locals>.<listcomp>)r   r6   rZ   r   rH   listfilter)Zwith_categoriesr]   rZ   r   )r]   r   get_flashed_messages  s    +!rc   c          $   C   su  d } d }	 t  |  d  r' t |   }  t |  t  r |  }
 t j j |
  sf t j j t j	 |
  }
 d } | d k r t j j
 |
  } n |  } d }
 | d k r | d k	 r t j |  d p d } | d k r t d   t   } | r| d k r	t d   t | t  s'| j d  } y | j d  } WnL t k
 rd	 t j d
 |  j d d  d d t | d d i } Yn Xd	 | i } | j d d |  t j r|
 r| d k	 r| j   |
 | d <t j j |
  }	 |	 | d <d } n | d k rHt |
 d  } t j j |
  } t j j |
  }	 |	 | d <nV t | t j  ry | j   j  }	 Wn$ t! k
 rt" | j#    }	 Yn X|	 | d <t$ t% j& |  } t j' | d | d | d d } | d k	 r| | _( n | d k	 r| | _( d | j) _* | d k r%t j+ |
  } | d k	 rS| | j) _, t- t.   |  | _/ | r|
 d k	 rd d l0 m1 } y^ | j2 d t j j |
  t j j |
  t3 t |
 t  r|
 j d  n |
  d @f  Wn& t4 k
 r| d |
 d d Yn X| rqy | j5 t% d d d  |	 } Wn+ t6 k
 rN| d k	 rG| j     Yn X| j7 d! k rq| j8 j9 d" d  | S)#a  Sends the contents of a file to the client.  This will use the
    most efficient method available and configured.  By default it will
    try to use the WSGI server's file_wrapper support.  Alternatively
    you can set the application's :attr:`~Flask.use_x_sendfile` attribute
    to ``True`` to directly emit an ``X-Sendfile`` header.  This however
    requires support of the underlying webserver for ``X-Sendfile``.

    By default it will try to guess the mimetype for you, but you can
    also explicitly provide one.  For extra security you probably want
    to send certain files as attachment (HTML for instance).  The mimetype
    guessing requires a `filename` or an `attachment_filename` to be
    provided.

    ETags will also be attached automatically if a `filename` is provided. You
    can turn this off by setting `add_etags=False`.

    If `conditional=True` and `filename` is provided, this method will try to
    upgrade the response stream to support range requests.  This will allow
    the request to be answered with partial content response.

    Please never pass filenames to this function from user sources;
    you should use :func:`send_from_directory` instead.

    .. versionadded:: 0.2

    .. versionadded:: 0.5
       The `add_etags`, `cache_timeout` and `conditional` parameters were
       added.  The default behavior is now to attach etags.

    .. versionchanged:: 0.7
       mimetype guessing and etag support for file objects was
       deprecated because it was unreliable.  Pass a filename if you are
       able to, otherwise attach an etag yourself.  This functionality
       will be removed in Flask 1.0

    .. versionchanged:: 0.9
       cache_timeout pulls its default from application config, when None.

    .. versionchanged:: 0.12
       The filename is no longer automatically inferred from file objects. If
       you want to use automatic mimetype and etag support, pass a filepath via
       `filename_or_fp` or `attachment_filename`.

    .. versionchanged:: 0.12
       The `attachment_filename` is preferred over `filename` for MIME-type
       detection.

    .. versionchanged:: 1.0
        UTF-8 filenames, as specified in `RFC 2231`_, are supported.

    .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4

    .. versionchanged:: 1.0.3
        Filenames are encoded with ASCII instead of Latin-1 for broader
        compatibility with WSGI servers.

    .. versionchanged:: 1.1
        Filename may be a :class:`~os.PathLike` object.

    .. versionadded:: 1.1
        Partial content supports :class:`~io.BytesIO`.

    :param filename_or_fp: the filename of the file to send.
                           This is relative to the :attr:`~Flask.root_path`
                           if a relative path is specified.
                           Alternatively a file object might be provided in
                           which case ``X-Sendfile`` might not work and fall
                           back to the traditional method.  Make sure that the
                           file pointer is positioned at the start of data to
                           send before calling :func:`send_file`.
    :param mimetype: the mimetype of the file if provided. If a file path is
                     given, auto detection happens as fallback, otherwise an
                     error will be raised.
    :param as_attachment: set to ``True`` if you want to send this file with
                          a ``Content-Disposition: attachment`` header.
    :param attachment_filename: the filename for the attachment if it
                                differs from the file's filename.
    :param add_etags: set to ``False`` to disable attaching of etags.
    :param conditional: set to ``True`` to enable conditional responses.

    :param cache_timeout: the timeout in seconds for the headers. When ``None``
                          (default), this value is set by
                          :meth:`~Flask.get_send_file_max_age` of
                          :data:`~flask.current_app`.
    :param last_modified: set the ``Last-Modified`` header to this value,
        a :class:`~datetime.datetime` or timestamp.
        If a file was passed, this overrides its mtime.
    NZ
__fspath__r   zapplication/octet-streamzUnable to infer MIME-type because no filename is available. Please set either `attachment_filename`, pass a filepath to `filename_or_fp` or set your own MIME-type via `mimetype`.z8filename unavailable, required for sending as attachmentzutf-8asciifilenameZNFKDignorez	filename*z	UTF-8''%ssafe    zContent-Disposition
attachmentz
X-SendfilezContent-LengthrbmimetypeheadersZdirect_passthroughT)warnz%s-%s-%sl    zEAccess %s failed, maybe it does not exist, so ignore etags in headers
stacklevel   Zaccept_rangesZcomplete_lengthi0  z
x-sendfile):r8   r   
isinstancer   r    pathisabsjoinr   	root_pathbasename	mimetypes
guess_typerI   r   r=   r   decodeencodeUnicodeEncodeErrorunicodedata	normalizer   addZuse_x_sendfiler5   getsizeopengetmtimeioBytesIO	getbuffernbytesAttributeErrorr@   getvaluer   r   r!   r?   last_modifiedZcache_controlpublicget_send_file_max_ageZmax_ageintr   expireswarningsrm   Zset_etagr   OSErrorZmake_conditionalr
   status_coderl   rH   )Zfilename_or_fprk   Zas_attachmentZattachment_filenameZ	add_etagscache_timeoutconditionalr   mtimefsizere   filerl   	filenamesdatarN   rm   r   r   r   	send_file  s    b			!


	
	
r   c                s   |  g } x | D]     d k r1 t  j      t   f d d   t D  s} t j j    s}   d k s}   j d  r t    | j	    q Wt  j
 |   S)aj  Safely join `directory` and zero or more untrusted `pathnames`
    components.

    Example usage::

        @app.route('/wiki/<path:filename>')
        def wiki_page(filename):
            filename = safe_join(app.config['WIKI_FOLDER'], filename)
            with open(filename, 'rb') as fd:
                content = fd.read()  # Read and process the file content...

    :param directory: the trusted base directory.
    :param pathnames: the untrusted pathnames relative to that directory.
    :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed
            paths fall out of its boundaries.
     c             3   s   |  ] } |   k Vq d  S)Nr   )r   r   )re   r   r   r     s    zsafe_join.<locals>.<genexpr>z..z../)	posixpathnormpathany_os_alt_sepsr    rq   rr   
startswithr	   rX   rs   )	directoryZ	pathnamespartsr   )re   r   	safe_join  s    		r   c             K   s   t  |  } t  |   }  t |  |  } t j j |  sQ t j j t j |  } y t j j |  so t	    Wn! t
 t f k
 r t    Yn X| j d d  t | |  S)a  Send a file from a given directory with :func:`send_file`.  This
    is a secure way to quickly expose static files from an upload folder
    or something similar.

    Example usage::

        @app.route('/uploads/<path:filename>')
        def download_file(filename):
            return send_from_directory(app.config['UPLOAD_FOLDER'],
                                       filename, as_attachment=True)

    .. admonition:: Sending files and Performance

       It is strongly recommended to activate either ``X-Sendfile`` support in
       your webserver or (if no authentication happens) to tell the webserver
       to serve files for the given path on its own without calling into the
       web application for improved performance.

    .. versionadded:: 0.5

    :param directory: the directory where all the files are stored.
    :param filename: the filename relative to that directory to
                     download.
    :param options: optional keyword arguments that are directly
                    forwarded to :func:`send_file`.
    r   T)r   r   r    rq   rr   rs   r   rt   isfiler	   r=   rI   r   
setdefaultr   )r   re   optionsr   r   r   send_from_directory  s    r   c             C   s   t  j j |   } | d k	 rL t | d  rL t j j t j j | j   St	 j
 |   } | d k ss |  d k r} t j   St | d  r | j |   } nE t |   t  j |  } t | d d  } | d k r t d |    t j j t j j |   S)zReturns the path to a package or cwd if that cannot be found.  This
    returns the path of a package or the folder that contains a module.

    Not to be confused with the package path returned by :func:`find_package`.
    N__file____main__get_filenamea  No root path can be found for the provided module "%s".  This can happen because the module came from an import hook that does not provide file name information or because it's a namespace package.  In this case the root path needs to be explicitly provided.)sysmodulesr"   r8   r    rq   dirnameabspathr   pkgutil
get_loadergetcwdr   
__import__rQ   r7   )import_namemodloaderfilepathr   r   r   get_root_path  s     


r   c             C   s^   t  |  d  r |  j |  S|  j j d k rD |  j j d k rD d St d |  j j   d S)zGiven the loader that loaded a module and the module this function
    attempts to figure out if the given module is actually a package.
    
is_package_frozen_importlibZNamespaceLoaderTz%s.is_package() method is missing but is required by Flask of PEP 302 import hooks.  If you do not use import hooks and you encounter this error please file a bug against Flask.N)r8   r   	__class__
__module__r-   r   )r   Zmod_namer   r   r   )_matching_loader_thinks_module_is_package6  s    r   c             C   s  t  j d
 k r d d l } y. | j j |   } | d k rH t d   Wn t t f k
 rc Ynj X| j d k r t j	 j
 t t | j    S| j r t j	 j
 t j	 j
 | j   St j	 j
 | j  St j |   } | d k s |  d k r t j   St | d  r| j |   } n5 t | d	  r:| j } n t |   t  j |  j } t j	 j t j	 j
 |   } t | |   rt j	 j
 |  } | S)z/Find the path where the module's root exists in      r   Nz	not found	namespacer   r   archive)r   r   >   Nr   )r   version_infoimportlib.utilutil	find_specrI   ImportErrororiginr    rq   r   r>   r<   submodule_search_locationsr   r   r   r8   r   r   r   r   r   r   r   )root_mod_name	importlibspecr   re   package_pathr   r   r   _find_package_pathR  s4    	

r   c       
      C   s   |  j  d  \ } } } t |  } t j j |  \ } } t j j t j  } | j |  rj | | f S| j	   d k r t j j |  \ } } | j	   d k r | }	 n9 t j j
 |  j	   d k r t j j |  }	 n | }	 |	 | f Sd | f S)a  Finds a package and returns the prefix (or None if the package is
    not installed) as well as the folder that contains the package or
    module as a tuple.  The package path returned is the module that would
    have to be added to the pythonpath in order to make it possible to
    import the module.  The prefix is the path below which a UNIX like
    folder structure exists (lib, share etc.).
    rB   zsite-packageslibN)	partitionr   r    rq   splitr   r   prefixr   r'   ru   r   )
r   r   _r   Zsite_parentZsite_folderZ	py_prefixparentZfolderbase_dirr   r   r   find_package  s    
	
r   c               @   s7   e  Z d  Z d Z d d d d  Z d d d  Z d S)locked_cached_propertya#  A decorator that converts a function into a lazy property.  The
    function wrapped is called the first time to retrieve the result
    and then that calculated result is used the next time you access
    the value.  Works like the one in Werkzeug but has a lock for
    thread safety.
    Nc             C   sI   | p | j  |  _  | j |  _ | p* | j |  _ | |  _ t   |  _ d  S)N)r-   r   __doc__funcr   lock)selfr   namedocr   r   r   __init__  s
    	zlocked_cached_property.__init__c          
   C   sl   | d  k r |  S|  j  L | j j |  j t  } | t k r] |  j |  } | | j |  j <| SWd  QRXd  S)N)r   __dict__r"   r-   _missingr   )r   objtypevaluer   r   r   __get__  s    
zlocked_cached_property.__get__)r-   r   __qualname__r   r   r   r   r   r   r   r     s   r   c               @   s   e  Z d  Z d Z d Z d Z d d d d  Z e d d    Z e j	 d d    Z e d d    Z
 e
 j	 d	 d    Z
 e d
 d    Z e d d    Z d d   Z d d   Z d d d  Z d S)_PackageBoundObjectNc             C   sh   | |  _  | |  _ | d  k r- t |  j   } | |  _ d  |  _ d  |  _ d d l m } |   |  _ d  S)Nr   )AppGroup)r   template_folderr   rt   _static_folder_static_url_pathclir   )r   r   r   rt   r   r   r   r   r     s    					z_PackageBoundObject.__init__c             C   s,   |  j  d k	 r( t j j |  j |  j   Sd S)z2The absolute path to the configured static folder.N)r   r    rq   rs   rt   )r   r   r   r   static_folder  s    z!_PackageBoundObject.static_folderc             C   s(   | d  k	 r | j  d  } | |  _ d  S)Nz/\)rstripr   )r   r   r   r   r   r     s    c             C   sO   |  j  d k	 r |  j  S|  j d k	 rK t j j |  j  } d | j d  Sd 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`.
        Nr   )r   r   r    rq   ru   r   )r   ru   r   r   r   static_url_path  s
    z#_PackageBoundObject.static_url_pathc             C   s(   | d  k	 r | j  d  } | |  _ d  S)Nr   )r   r   )r   r   r   r   r   r     s    c             C   s   |  j  d k	 S)zThis is ``True`` if the package bound object's container has a
        folder for static files.

        .. versionadded:: 0.5
        N)r   )r   r   r   r   has_static_folder  s    z%_PackageBoundObject.has_static_folderc             C   s2   |  j  d k	 r. t t j j |  j |  j    Sd S)zWThe Jinja loader for this package bound object.

        .. versionadded:: 0.5
        N)r   r   r    rq   rs   rt   )r   r   r   r   jinja_loader  s    z _PackageBoundObject.jinja_loaderc             C   s   t  t j  S)a  Provides default cache_timeout for the :func:`send_file` functions.

        By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from
        the configuration of :data:`~flask.current_app`.

        Static file functions such as :func:`send_from_directory` use this
        function, and :func:`send_file` calls this function on
        :data:`~flask.current_app` when the given cache_timeout is ``None``. If a
        cache_timeout is given in :func:`send_file`, that timeout is used;
        otherwise, this method is called.

        This allows subclasses to change the behavior when sending files based
        on the filename.  For example, to set the cache timeout for .js files
        to 60 seconds::

            class MyFlask(flask.Flask):
                def get_send_file_max_age(self, name):
                    if name.lower().endswith('.js'):
                        return 60
                    return flask.Flask.get_send_file_max_age(self, name)

        .. versionadded:: 0.9
        )total_secondsr   Zsend_file_max_age_default)r   re   r   r   r   r     s    z)_PackageBoundObject.get_send_file_max_agec             C   s:   |  j  s t d   |  j |  } t |  j | d | S)zFunction used internally to send static files from the static
        folder to the browser.

        .. versionadded:: 0.5
        z No static folder for this objectr   )r   r7   r   r   r   )r   re   r   r   r   r   send_static_file0  s
    	z$_PackageBoundObject.send_static_filerj   c             C   s7   | d k r t  d   t t j j |  j |  |  S)a:  Opens a resource from the application's resource folder.  To see
        how this works, consider the following folder structure::

            /myapplication.py
            /schema.sql
            /static
                /style.css
            /templates
                /layout.html
                /index.html

        If you want to open the :file:`schema.sql` file you would do the
        following::

            with app.open_resource('schema.sql') as f:
                contents = f.read()
                do_something_with(contents)

        :param resource: the name of the resource.  To access resources within
                         subfolders use forward slashes as separator.
        :param mode: Open file in this mode. Only reading is supported,
            valid values are "r" (or "rt") and "rb".
        rrtrj   z(Resources can only be opened for reading>   r   r   rj   )rI   r   r    rq   rs   rt   )r   resourcemoder   r   r   open_resource?  s    z!_PackageBoundObject.open_resource)r-   r   r   r   r   rt   r   propertyr   setterr   r   r   r   r   r   r   r   r   r   r   r     s   		r   c             C   s   |  j  d d d |  j S)zReturns the total seconds from a timedelta object.

    :param timedelta td: the timedelta to be converted in seconds

    :returns: number of seconds
    :rtype: int
    <      )daysseconds)tdr   r   r   r   ]  s    r   c             C   s   t  rF t j d k rF y t j |   d SWn t j k
 rE d SYn XxJ t j t j f D]6 } y t j | |   Wn t j k
 r YqY Xd SqY Wd S)a  Determine if the given string is an IP address.

    Python 2 on Windows doesn't provide ``inet_pton``, so this only
    checks IPv4 addresses in that environment.

    :param value: value to check
    :type value: str

    :return: True if string is an IP address
    :rtype: bool
    ntTF)	r   r    r   socket	inet_atonrO   AF_INETAF_INET6	inet_pton)r   familyr   r   r   is_iph  s    	r   )Gr   r   rv   r    r   r   r   r   r{   	functoolsr   	threadingr   r   zlibr   Zjinja2r   Zwerkzeug.datastructuresr   Zwerkzeug.exceptionsr   r	   r
   Zwerkzeug.routingr   Zwerkzeug.urlsr   Zwerkzeug.wsgir   _compatr   r   r   r   globalsr   r   r   r   r   Zsignalsr   objectr   ra   rq   r   altsepr   r#   r)   r+   r.   r/   rA   rP   rT   r[   rc   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>
   sx   	(L1*%)0: