U
    ڲg@                     @   sJ  d 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	m
Z
 ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ edZdd Zdd Zdd Zdd Zd7ddZd8ddZ dd Z!dd Z"dd Z#d d! Z$d9d"d#Z%d$d% Z&d&d' Z'd(d) Z(d*d+ Z)d,d- Z*d.d/ Z+d:d1d2Z,d;d3d4Z-d5d6 Z.dS )<a  
This module contains helper functions for controlling caching. It does so by
managing the "Vary" header of responses. It includes functions to patch the
header of response objects directly and decorators that change functions to do
that header-patching themselves.

For information on the Vary header, see RFC 9110 Section 12.5.5.

Essentially, the "Vary" HTTP header defines which headers a cache should take
into account when building its cache key. Requests with the same path but
different header content for headers named in "Vary" need to get different
cache keys to prevent delivery of wrong content.

An example: i18n middleware would need to distinguish caches by the
"Accept-language" header.
    N)defaultdict)settings)caches)HttpResponseHttpResponseNotModified)md5)	http_dateparse_etagsparse_http_date_safe
quote_etag)log_response)_lazy_re_compile)get_current_timezone_name)get_languagez\s*,\s*c           
         sr  dd }dd  t t}| drdt| jd D ]0}||\}dkrZ| | q2||< q2d|krd|krtt|d |d |d< d	|krd
|kr|d	= nd
|krd	|kr|d
= |	 D ]4\}}|
dddkr| | q||< qg }|	 D ]R\}	t|	trFd|	kr*dh}	| fdd|	D  n| |	 qd|}|| jd< dS )a  
    Patch the Cache-Control header by adding all keyword arguments to it.
    The transformation is as follows:

    * All keyword parameter names are turned to lowercase, and underscores
      are converted to hyphens.
    * If the value of a parameter is True (exactly True, not just a
      true value), only the parameter name is added to the header.
    * All other parameters are added with their value, after applying
      str() to it.
    c                 S   s@   |  dd}t|dkr,|d  |d fS |d  dfS d S )N=   r   Tsplitlenlowerst r   6/tmp/pip-unpacked-wheel-a78qhiua/django/utils/cache.pydictitem.   s    z%patch_cache_control.<locals>.dictitemc                  W   s,   | d dkr| d S d| d | d f S d S )Nr   Tr   z%s=%sr   )r   r   r   r   	dictvalue5   s    z&patch_cache_control.<locals>.dictvalueCache-Controlzno-cachemax-agemax_ageprivatepublic_-Tc                    s   g | ]} |qS r   r   ).0valuer   	directiver   r   
<listcomp>_   s     z'patch_cache_control.<locals>.<listcomp>, N)r   setgetcc_delim_rer   headersaddminintitemsreplace
isinstanceextendappendjoin)
responsekwargsr   ccfieldr%   kvZ
directivesvaluesr   r&   r   patch_cache_control!   s:    




r>   c              
   C   sZ   |  dsdS tdd t| jd D }zt|d W S  tttfk
rT   Y nX dS )z
    Return the max-age from the response Cache-Control header as an integer,
    or None if it wasn't found or wasn't an integer.
    r   Nc                 s   s   | ]}t |V  qd S )N)	_to_tuple)r$   elr   r   r   	<genexpr>m   s    zget_max_age.<locals>.<genexpr>r   )	
has_headerdictr,   r   r-   r0   
ValueError	TypeErrorKeyError)r7   r9   r   r   r   get_max_agef   s    
rG   c                 C   s,   | j s(| jr(tt| jdd | jd< | S )NFZusedforsecurityETag)Z	streamingcontentr   r   	hexdigestr-   r7   r   r   r   set_response_etagv   s
    
rM   c                 C   s    t dd}td| j|| d |S )Ni  )statuszPrecondition Failed: %s)r7   request)r   r   path)rO   r7   r   r   r   _precondition_failed~   s    
rQ   c                 C   s8   t  }|r4dD ]}||kr|j| |j|< q|j|_|S )N)r   zContent-LocationDaterI   ExpireszLast-ModifiedVary)r   r-   cookies)rO   r7   Znew_responseheaderr   r   r   _not_modified   s    	rW   c                 C   s   |r d|j   krdk s n |S t| jdd}| jd}|oHt|}t| jdd}| jd}|ort|}|rt||st| S |s|rt||st| S |rt||s| j	dkrt
| |S t| S |s|rt||s| j	dkrt
| |S |S )	N   i,  ZHTTP_IF_MATCH ZHTTP_IF_UNMODIFIED_SINCEZHTTP_IF_NONE_MATCHZHTTP_IF_MODIFIED_SINCE)GETHEAD)status_coder	   METAr+   r
   _if_match_passesrQ   _if_unmodified_since_passes_if_none_match_passesmethodrW   _if_modified_since_passes)rO   etaglast_modifiedr7   Zif_match_etagsif_unmodified_sinceZif_none_match_etagsif_modified_sincer   r   r   get_conditional_response   sB    


rg   c                 C   s0   | sdS |dgkrdS |  dr$dS | |kS dS )zM
    Test the If-Match comparison as defined in RFC 9110 Section 13.1.1.
    F*TW/N)
startswithZtarget_etagZetagsr   r   r   r^      s    

r^   c                 C   s   | o
| |kS )z\
    Test the If-Unmodified-Since comparison as defined in RFC 9110 Section
    13.1.4.
    r   )rd   re   r   r   r   r_      s    r_   c                 C   s:   | sdS |dgkrdS |  d} dd |D }| |kS dS )zR
    Test the If-None-Match comparison as defined in RFC 9110 Section 13.1.2.
    Trh   Fri   c                 s   s   | ]}| d V  qdS )ri   Nstrip)r$   rc   r   r   r   rA     s     z(_if_none_match_passes.<locals>.<genexpr>Nrl   rk   r   r   r   r`      s    

r`   c                 C   s   |  p| |kS )zZ
    Test the If-Modified-Since comparison as defined in RFC 9110 Section
    13.1.3.
    r   )rd   rf   r   r   r   rb     s    rb   c                 C   sJ   |dkrt j}|dk rd}| ds:tt | | jd< t| |d dS )z
    Add HTTP caching headers to the given HttpResponse: Expires and
    Cache-Control.

    Each header is only added if it isn't already set.

    cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used
    by default.
    Nr   rS   )r   )r   CACHE_MIDDLEWARE_SECONDSrB   r   timer-   r>   )r7   cache_timeoutr   r   r   patch_response_headers  s    

rq   c                 C   s"   t | dd t| ddddd dS )zS
    Add headers to a response to indicate that a page should never be cached.
    )rp   T)no_cacheno_storeZmust_revalidater    N)rq   r>   rL   r   r   r   add_never_cache_headers   s        ru   c                    sp   |  drt| jd }ng }dd |D   fdd|D }||7 }d|kr\d| jd< nd|| jd< dS )	a)  
    Add (or update) the "Vary" header in the given HttpResponse object.
    newheaders is a list of header names that should be in "Vary". If headers
    contains an asterisk, then "Vary" header will consist of a single asterisk
    '*'. Otherwise, existing headers in "Vary" aren't removed.
    rT   c                 S   s   h | ]}|  qS r   r   r$   rV   r   r   r   	<setcomp>9  s     z%patch_vary_headers.<locals>.<setcomp>c                    s   g | ]}|   kr|qS r   rv   )r$   Z	newheaderexisting_headersr   r   r(   :  s   z&patch_vary_headers.<locals>.<listcomp>rh   r)   N)rB   r,   r   r-   r6   )r7   
newheadersvary_headersZadditional_headersr   ry   r   patch_vary_headers*  s    


r}   c                 C   s8   |  dsdS t| jd }dd |D }| |kS )zR
    Check to see if the response has a given header name in its Vary header.
    rT   Fc                 S   s   h | ]}|  qS r   rv   rw   r   r   r   rx   M  s     z"has_vary_header.<locals>.<setcomp>)rB   r,   r   r-   r   )r7   Zheader_queryr|   rz   r   r   r   has_vary_headerF  s
    
r~   c                 C   s4   t jr|dt| dt  7 }t jr0|dt  7 }|S )zCIf necessary, add the current locale or time zone to the cache key.z.%sZLANGUAGE_CODE)r   USE_I18Ngetattrr   ZUSE_TZr   )rO   	cache_keyr   r   r   _i18n_cache_key_suffixQ  s
    r   c           	      C   sn   t dd}|D ]&}| j|}|dk	r||  qt |  ddd}d||| | f }t| |S )z=Return a cache key from the headers given in the header list.FrH   Nasciiz-views.decorators.cache.cache_page.%s.%s.%s.%s)r   r]   r+   updateencodebuild_absolute_urirK   r   )	rO   ra   
headerlist
key_prefixctxrV   r%   urlr   r   r   r   _generate_cache_key]  s    
r   c                 C   s0   t | ddd}d| | f }t||S )z(Return a cache key for the header cache.r   FrH   z)views.decorators.cache.cache_header.%s.%s)r   r   r   rK   r   )r   rO   r   r   r   r   r   _generate_cache_header_keyn  s    r   rZ   c                 C   sR   |dkrt j}t|| }|dkr*tt j }||}|dk	rJt| |||S dS dS )ae  
    Return a cache key based on the request URL and query. It can be used
    in the request phase because it pulls the list of headers to take into
    account from the global URL registry and uses those to build a cache key
    to check against.

    If there isn't a headerlist stored, return None, indicating that the page
    needs to be rebuilt.
    N)r   CACHE_MIDDLEWARE_KEY_PREFIXr   r   CACHE_MIDDLEWARE_ALIASr+   r   )rO   r   ra   cacher   r   r   r   r   get_cache_keyx  s    



r   c           	      C   s   |dkrt j}|dkrt j}t|| }|dkr8tt j }|drt j}g }t	|j
d D ].}| dd}|dks||s\|d|  q\|  |||| t| | j||S ||g | t| | jg |S dS )a  
    Learn what headers to take into account for some request URL from the
    response object. Store those headers in a global URL registry so that
    later access to that URL will know what headers to take into account
    without building the response object itself. The headers are named in the
    Vary header of the response, but we want to prevent response generation.

    The list of headers to use for cache key generation is stored in the same
    cache as the pages themselves. If the cache ages some data out of the
    cache, this just means that we have to build the response once to get at
    the Vary header and so at the list of headers to use for the cache key.
    NrT   r#   r"   ZACCEPT_LANGUAGEZHTTP_)r   r   rn   r   r   r   rB   r   r,   r   r-   upperr2   r5   sortr*   r   ra   )	rO   r7   rp   r   r   r   Zis_accept_language_redundantr   rV   r   r   r   learn_cache_key  s&    


r   c                 C   s<   |  dd}t|dkr,|d  |d fS |d  dfS )Nr   r      r   Tr   r   r   r   r   r?     s    r?   )N)NNN)N)NrZ   N)NNN)/__doc__ro   collectionsr   Zdjango.confr   Zdjango.core.cacher   Zdjango.httpr   r   Zdjango.utils.cryptor   Zdjango.utils.httpr   r	   r
   r   Zdjango.utils.logr   Zdjango.utils.regex_helperr   Zdjango.utils.timezoner   Zdjango.utils.translationr   r,   r>   rG   rM   rQ   rW   rg   r^   r_   r`   rb   rq   ru   r}   r~   r   r   r   r   r   r?   r   r   r   r   <module>   s@   E

2




)