B
    `;                 @   s   d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZmZ d dlmZmZmZ d dlmZmZ d dlmZmZ d dlmZ d dlmZmZ d d	lmZ G d
d dZdd Zdd Z dej!hZ"dd Z#dddhj$Z%eddd Z&G dd dZ'G dd de'Z(G dd dZ)dS )    )	lru_cacheN)existsgetmtimegetsizeisdirjoinnormcasenormpath)resource_existsresource_filenameresource_isdir)abspath_from_asset_specresolve_asset_spec)HTTPMovedPermanentlyHTTPNotFound)caller_package)FileResponse_guess_type)traversal_path_infoc               @   sJ   e Zd ZdZdddZd	d
 Zdd Zdd Zdd Zdd Z	dd Z
dS )static_viewa  An instance of this class is a callable which can act as a
    :app:`Pyramid` :term:`view callable`; this view will serve
    static files from a directory on disk based on the ``root_dir``
    you provide to its constructor.

    The directory may contain subdirectories (recursively); the static
    view implementation will descend into these directories as
    necessary based on the components of the URL in order to resolve a
    path into a response.

    You may pass an absolute or relative filesystem path or a
    :term:`asset specification` representing the directory
    containing static files as the ``root_dir`` argument to this
    class' constructor.

    If the ``root_dir`` path is relative, and the ``package_name``
    argument is ``None``, ``root_dir`` will be considered relative to
    the directory in which the Python file which *calls* ``static``
    resides.  If the ``package_name`` name argument is provided, and a
    relative ``root_dir`` is provided, the ``root_dir`` will be
    considered relative to the Python :term:`package` specified by
    ``package_name`` (a dotted path to a Python package).

    ``cache_max_age`` influences the ``Expires`` and ``Max-Age``
    response headers returned by the view (default is 3600 seconds or
    one hour).

    ``use_subpath`` influences whether ``request.subpath`` will be used as
    ``PATH_INFO`` when calling the underlying WSGI application which actually
    serves the static files.  If it is ``True``, the static application will
    consider ``request.subpath`` as ``PATH_INFO`` input.  If it is ``False``,
    the static application will consider request.environ[``PATH_INFO``] as
    ``PATH_INFO`` input. By default, this is ``False``.

    ``reload`` controls whether a cache of files is maintained or the asset
    subsystem is queried per-request to determine what files are available.
    By default, this is ``False`` and new files added while the process is
    running are not recognized.

    ``content_encodings`` is a list of alternative file encodings supported
    in the ``Accept-Encoding`` HTTP Header. Alternative files are found using
    file extensions defined in :attr:`mimetypes.encodings_map`. An encoded
    asset will be returned with the ``Content-Encoding`` header set to the
    selected encoding. If the asset contains alternative encodings then the
    ``Accept-Encoding`` value will be added to the response's ``Vary`` header.
    By default, the list is empty and no alternatives will be supported.

    .. note::

       If the ``root_dir`` is relative to a :term:`package`, or is a
       :term:`asset specification` the :app:`Pyramid`
       :class:`pyramid.config.Configurator` method can be used to override
       assets within the named ``root_dir`` package-relative directory.
       However, if the ``root_dir`` is absolute, configuration will not be able
       to override the assets it contains.

    .. versionchanged:: 2.0

       Added ``reload`` and ``content_encodings`` options.

      NF
index.html c       	      C   sd   || _ |d krt j}t||\}}|| _|| _|| _tt|| _	|| _
|| _t|| _i | _d S )N)cache_max_ager   __name__r   use_subpathpackage_namedocrootr   r	   norm_docrootindexreload_compile_content_encodingscontent_encodingsfilemap)	selfroot_dirr   r   r   r   r    r"   r   r   r   V/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/static.py__init__N   s    
zstatic_view.__init__c       
      C   sn   |  |}| |}| ||\}}|d kr6t|jt|\}}t||| j||}	t|dkrjt	|	d |	S )N   zAccept-Encoding)
get_resource_nameget_possible_filesfind_best_matchr   urlr   r   r   len	_add_vary)
r$   contextrequestresource_namefilesfilepathcontent_encodingcontent_type_responser   r   r&   __call__h   s    



zstatic_view.__call__c             C   s   | j r|j}n
t|j}t|}|dkr6td|j | jrd| j	d|f }t
| j|r|jdsr| |d|	d| jf }n>ttt| j|}t|r|jds| |t|| j}|S )z}
        Return the computed name of the requested resource.

        The returned file is not guaranteed to exist.

        NzOut of bounds: %sz%s/%s/)r   subpathr   Z	path_info_secure_pathr   r,   r   r   rstripr   path_urlendswithadd_slash_redirectr   r   r	   r   r   r   )r$   r0   
path_tuplepathresource_pathr   r   r&   r)   {   s(    


zstatic_view.get_resource_namec             C   s0   | j r t| j |r,t| j |S nt|r,|S dS )zd
        Return the absolute path to the resource or ``None`` if it doesn't
        exist.

        N)r   r
   r   r   )r$   namer   r   r&   find_resource_path   s
    zstatic_view.find_resource_pathc             C   s   | j |}|dk	r|S g }| |}|r8||df xH| j D ]:\}}x0|D ](}|| }| |}|rR|||f qRW qDW |jdd d | js|| j |< |S )z< Return a sorted list of ``(size, encoding, path)`` entries.Nc             S   s   t | d S )Nr   )r   )xr   r   r&   <lambda>       z0static_view.get_possible_files.<locals>.<lambda>)key)r#   getrD   appendr"   itemssortr    )r$   r1   resultrA   encoding
extensionsextencoded_namer   r   r&   r*      s"    



zstatic_view.get_possible_filesc             C   sr   |j s"tdd |D d}|dfS dd |j dd |D D }|d x |D ]\}}||krR||fS qRW dS )	z$ Return ``(path | None, encoding)``.c             s   s   | ]\}}|d kr|V  qd S )Nr   ).0rA   rN   r   r   r&   	<genexpr>   s    z.static_view.find_best_match.<locals>.<genexpr>Nc             S   s   h | ]}|d  qS )r   r   )rR   rE   r   r   r&   	<setcomp>   s   z.static_view.find_best_match.<locals>.<setcomp>c             S   s   g | ]\}}|d k	r|qS )Nr   )rR   rA   rN   r   r   r&   
<listcomp>   s    z/static_view.find_best_match.<locals>.<listcomp>)NN)accept_encodingnextZacceptable_offersadd)r$   r0   r2   Zidentity_pathZacceptable_encodingsrA   rN   r   r   r&   r+      s    
zstatic_view.find_best_matchc             C   s(   |j d }|j}|r |d | }t|S )Nr9   ?)r=   Zquery_stringr   )r$   r0   r,   qsr   r   r&   r?      s
    
zstatic_view.add_slash_redirect)r   NFr   Fr   )r   
__module____qualname____doc__r'   r8   r)   rD   r*   r+   r?   r   r   r   r&   r      s   =     
%#r   c             C   s:   i }x0t j D ]"\}}|| kr||g | qW |S )zb
    Convert mimetypes.encodings_map into a dict of
    ``(encoding) -> [file extensions]``.

    )	mimetypesencodings_maprK   
setdefaultrJ   )	encodingsrM   rP   rN   r   r   r&   r!      s
    r!   c                s4   | j pg }t fdd|D s*|  || _ d S )Nc             3   s   | ]}|     kV  qd S )N)lower)rR   rE   )optionr   r&   rS     s    z_add_vary.<locals>.<genexpr>)varyanyrJ   )r7   rc   rd   r   )rc   r&   r.      s    

r.   r9   c             C   s   xt D ]}|| krdS qW d S )NT)_seps)itemsepr   r   r&   _contains_slash
  s    
ri   z... i  c             C   s0   t | rd S tdd | D r"d S d| }|S )Nc             S   s   g | ]}t |qS r   )ri   )rR   rg   r   r   r&   rU     s    z _secure_path.<locals>.<listcomp>r9   )_has_insecure_pathelementre   r   )r@   encodedr   r   r&   r;     s    
r;   c               @   s"   e Zd ZdZdddZdd ZdS )	QueryStringCacheBustera  
    An implementation of :class:`~pyramid.interfaces.ICacheBuster` which adds
    a token for cache busting in the query string of an asset URL.

    The optional ``param`` argument determines the name of the parameter added
    to the query string and defaults to ``'x'``.

    To use this class, subclass it and provide a ``tokenize`` method which
    accepts ``request, pathspec, kw`` and returns a token.

    .. versionadded:: 1.6
    rE   c             C   s
   || _ d S )N)param)r$   ro   r   r   r&   r'   .  s    zQueryStringCacheBuster.__init__c             C   sP   |  |||}|di }t|tr0||| j< nt|| j|ff |d< ||fS )NZ_query)tokenizer`   
isinstancedictro   tuple)r$   r0   r:   kwtokenqueryr   r   r&   r8   1  s    
zQueryStringCacheBuster.__call__N)rE   )r   r[   r\   r]   r'   r8   r   r   r   r&   rn      s   
rn   c                   s*   e Zd ZdZd fdd	Zdd Z  ZS )QueryStringConstantCacheBustera  
    An implementation of :class:`~pyramid.interfaces.ICacheBuster` which adds
    an arbitrary token for cache busting in the query string of an asset URL.

    The ``token`` parameter is the token string to use for cache busting and
    will be the same for every request.

    The optional ``param`` argument determines the name of the parameter added
    to the query string and defaults to ``'x'``.

    .. versionadded:: 1.6
    rE   c                s   t  j|d || _d S )N)ro   )superr'   _token)r$   ru   ro   )	__class__r   r&   r'   I  s    z'QueryStringConstantCacheBuster.__init__c             C   s   | j S )N)ry   )r$   r0   r:   rt   r   r   r&   rp   M  s    z'QueryStringConstantCacheBuster.tokenize)rE   )r   r[   r\   r]   r'   rp   __classcell__r   r   )rz   r&   rw   ;  s   rw   c               @   sN   e Zd ZdZeeZeeZdddZdd Zdd Z	e
d	d
 Zdd ZdS )ManifestCacheBusteraT  
    An implementation of :class:`~pyramid.interfaces.ICacheBuster` which
    uses a supplied manifest file to map an asset path to a cache-busted
    version of the path.

    The ``manifest_spec`` can be an absolute path or a :term:`asset
    specification` pointing to a package-relative file.

    The manifest file is expected to conform to the following simple JSON
    format:

    .. code-block:: json

       {
           "css/main.css": "css/main-678b7c80.css",
           "images/background.png": "images/background-a8169106.png",
       }

    By default, it is a JSON-serialized dictionary where the keys are the
    source asset paths used in calls to
    :meth:`~pyramid.request.Request.static_url`. For example:

    .. code-block:: pycon

       >>> request.static_url('myapp:static/css/main.css')
       "http://www.example.com/static/css/main-678b7c80.css"

    The file format and location can be changed by subclassing and overriding
    :meth:`.parse_manifest`.

    If a path is not found in the manifest it will pass through unchanged.

    If ``reload`` is ``True`` then the manifest file will be reloaded when
    changed. It is not recommended to leave this enabled in production.

    If the manifest file cannot be found on disk it will be treated as
    an empty mapping unless ``reload`` is ``False``.

    .. versionadded:: 1.6
    Fc             C   s2   t  j}t||| _|| _d | _|s.|  | _d S )N)r   r   r   manifest_pathr    _mtimeget_manifest	_manifest)r$   Zmanifest_specr    r   r   r   r&   r'   ~  s    
zManifestCacheBuster.__init__c          	   C   s&   t | jd}| | S Q R X d S )Nrb)openr}   parse_manifestread)r$   fpr   r   r&   r     s    z ManifestCacheBuster.get_manifestc             C   s   t |dS )a  
        Parse the ``content`` read from the ``manifest_path`` into a
        dictionary mapping.

        Subclasses may override this method to use something other than
        ``json.loads`` to load any type of file format and return a conforming
        dictionary.

        zutf-8)jsonloadsdecode)r$   contentr   r   r&   r     s    
z"ManifestCacheBuster.parse_manifestc             C   sL   | j rF| | jsi S | | j}| jdks6|| jkrF|  | _|| _| jS )z! The current manifest dictionary.N)r    r   r}   r   r~   r   r   )r$   mtimer   r   r&   manifest  s    
zManifestCacheBuster.manifestc             C   s   | j ||}||fS )N)r   rI   )r$   r0   r:   rt   r   r   r&   r8     s    zManifestCacheBuster.__call__N)F)r   r[   r\   r]   staticmethodr   r   r'   r   r   propertyr   r8   r   r   r   r&   r|   Q  s   (
r|   )*	functoolsr   r   r^   osos.pathr   r   r   r   r   r   r	   pkg_resourcesr
   r   r   Zpyramid.assetr   r   Zpyramid.httpexceptionsr   r   Zpyramid.pathr   Zpyramid.responser   r   Zpyramid.traversalr   r   r!   r.   rh   rf   ri   intersectionrl   r;   rn   rw   r|   r   r   r   r&   <module>   s*   $ e
