U
    g                     @  s  d dl m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mZ ddlmZmZmZmZ ddlmZmZmZmZmZmZmZmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& dd	l'm(Z( dd
l)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddddgZ<ddhZ=dddddZ>d2ddddddZ?d3ddddd d!Z@ddd"d#d$ZAdd%d&d'd(ZBd)d*d+d,d-ZCG d.d de	jDeEeEf ZFG d/d dZGG d0d dZHG d1d de	jDeEeEf ZIdS )4    )annotationsN)Mapping)Cookie	CookieJar   )
ByteStreamUnattachedStreamencode_requestencode_response)SUPPORTED_DECODERSByteChunkerContentDecoderIdentityDecoderLineDecoderMultiDecoderTextChunkerTextDecoder)CookieConflictHTTPStatusErrorRequestNotReadResponseNotReadStreamClosedStreamConsumedrequest_context)(get_multipart_boundary_from_content_type)codes)AsyncByteStreamCookieTypesHeaderTypesQueryParamTypesRequestContentRequestDataRequestExtensionsRequestFilesResponseContentResponseExtensionsSyncByteStream)URL)to_bytes_or_strto_strCookiesHeadersRequestResponseauthorizationzproxy-authorizationstrbool)encodingreturnc                 C  s*   zt |  W n tk
r$   Y dS X dS )z7
    Return `True` if `encoding` is a known codec.
    FT)codecslookupLookupErrorr1    r7   1/tmp/pip-unpacked-wheel-ql4n0x43/httpx/_models.py_is_known_encoding8   s
    r9   zstr | bytes
str | Nonebytes)keyr1   r2   c                 C  s   t | tr| S | |pdS )zE
    Coerce str/bytes into a strictly byte-wise HTTP header key.
    ascii)
isinstancer;   encode)r<   r1   r7   r7   r8   _normalize_header_keyC   s    r@   )valuer1   r2   c                 C  s8   t | tr| S t | ts*tdt|  | |p4dS )zG
    Coerce str/bytes into a strictly byte-wise HTTP header value.
    z'Header value must be str or bytes, not r=   )r>   r;   r/   	TypeErrortyper?   )rA   r1   r7   r7   r8   _normalize_header_valueJ   s
    

rD   )content_typer2   c                 C  s   t j }| |d< |jd dS )Ncontent-type)failobj)emailmessageMessageget_content_charset)rE   msgr7   r7   r8   _parse_content_type_charsetU   s    
rM   zlist[dict[str, str]]rA   r2   c           	   
   C  s   g }d}|  |} | s|S td| D ]}z|dd\}}W n tk
r\   |d }}Y nX d| di}|dD ]F}z|d\}} W n tk
r   Y  qY nX |  ||| |< qv|| q&|S )	a7  
    Returns a list of parsed link headers, for more info see:
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
    The generic syntax of those is:
    Link: < uri-reference >; param1=value1; param2="value2"
    So for instance:
    Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'
    would return
        [
            {"url": "http:/.../front.jpeg", "type": "image/jpeg"},
            {"url": "http://.../back.jpeg"},
        ]
    :param value: HTTP Link entity-header field
    :return: list of parsed link headers
    z '"z, *<;r    urlz<> '"=)stripresplit
ValueErrorappend)	rA   linksreplace_charsvalrQ   paramslinkparamr<   r7   r7   r8   _parse_header_links]   s&    
r^   z4typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]]z4typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]])itemsr2   c                 c  s8   | D ].\}}t | tkr(td|d}||fV  qd S )Nz[secure])Zmatch_type_of)r)   lowerSENSITIVE_HEADERSr(   )r_   kvr7   r7   r8   _obfuscate_sensitive_headers   s    rd   c                   @  sZ  e Zd ZdZdBddddddZed	d
ddZejd	ddddZedd
ddZdd
ddZ	dd
ddZ
dd
ddZdd
ddZdCd	dddd d!ZdDd	d#d$d%d&d'ZdEddd(d)d*Zd d
d+d,Zd	d	d-d.d/Zd	d	dd0d1d2Zd	dd-d3d4Zdd#d-d5d6Zd7d
d8d9Zd:d
d;d<Zdd#d=d>d?Zd	d
d@dAZdS )Fr+   z9
    HTTP headers, as a case-insensitive multi-dict.
    NHeaderTypes | Noner:   None)headersr1   r2   c                 C  s   g | _ t|trt|j | _ nt|trf| D ]2\}}t||}t||}| j ||	 |f q0n@|d k	r|D ]2\}}t||}t||}| j ||	 |f qr|| _
d S N)_listr>   r+   listr   r_   r@   rD   rW   r`   	_encoding)selfrg   r1   rb   rc   Z	bytes_keyZbytes_valuer7   r7   r8   __init__   s    





zHeaders.__init__r/   r2   c              
   C  sn   | j dkrhdD ]R}| jD ]<\}}z|| || W q tk
rR   Y  qY qX q|| _  qhqd| _ | j S )zn
        Header encoding is mandated as ascii, but we allow fallbacks to utf-8
        or iso-8859-1.
        N)r=   utf-8z
iso-8859-1)rk   rawdecodeUnicodeDecodeError)rl   r1   r<   rA   r7   r7   r8   r1      s    

zHeaders.encodingrN   c                 C  s
   || _ d S rh   )rk   rl   rA   r7   r7   r8   r1      s    zlist[tuple[bytes, bytes]]c                 C  s   dd | j D S )zH
        Returns a list of the raw header items, as byte pairs.
        c                 S  s   g | ]\}}}||fqS r7   r7   ).0Zraw_key_rA   r7   r7   r8   
<listcomp>   s     zHeaders.raw.<locals>.<listcomp>ri   rl   r7   r7   r8   rp      s    zHeaders.rawztyping.KeysView[str]c                   s    fdd j D  S )Nc                   s    i | ]\}}}|  jd qS rh   rq   r1   rt   ru   r<   rA   rx   r7   r8   
<dictcomp>   s     
 z Headers.keys.<locals>.<dictcomp>)ri   keysrx   r7   rx   r8   r|      s    zHeaders.keysztyping.ValuesView[str]c                 C  s^   i }| j D ]J\}}}|| j}|| j}||krL||  d| 7  < q
|||< q
| S )N, )ri   rq   r1   valuesrl   Zvalues_dictru   r<   rA   Zstr_keyZ	str_valuer7   r7   r8   r~      s    
zHeaders.valuesztyping.ItemsView[str, str]c                 C  s^   i }| j D ]J\}}}|| j}|| j}||krL||  d| 7  < q
|||< q
| S )z
        Return `(key, value)` items of headers. Concatenate headers
        into a single comma separated value when a key occurs multiple times.
        r}   )ri   rq   r1   r_   r   r7   r7   r8   r_      s    
zHeaders.itemszlist[tuple[str, str]]c                   s    fdd j D S )z
        Return a list of `(key, value)` pairs of headers. Allow multiple
        occurrences of the same key without concatenating into a single
        comma separated value.
        c                   s*   g | ]"\}}}|  j|  jfqS r7   ry   rz   rx   r7   r8   rv      s   z'Headers.multi_items.<locals>.<listcomp>rw   rx   r7   rx   r8   multi_items   s    
zHeaders.multi_items
typing.Any)r<   defaultr2   c                 C  s(   z
| | W S  t k
r"   | Y S X dS )z
        Return a header value. If multiple occurrences of the header occur
        then concatenate them together with commas.
        N)KeyError)rl   r<   r   r7   r7   r8   get   s    
zHeaders.getFr0   z	list[str])r<   split_commasr2   c                   sZ   |  j  fddjD }|s.|S g }|D ]}|dd |dD  q6|S )z
        Return a list of all header values for a given key.
        If `split_commas=True` is passed, then any comma separated header
        values are split into multiple return strings.
        c                   s*   g | ]"\}}}|   kr|jqS r7   )r`   rq   r1   )rt   ru   item_keyZ
item_valueZget_header_keyrl   r7   r8   rv     s   z$Headers.get_list.<locals>.<listcomp>c                 S  s   g | ]}|  qS r7   )rS   )rt   itemr7   r7   r8   rv     s     ,)r`   r?   r1   ri   extendrU   )rl   r<   r   r~   Zsplit_valuesrA   r7   r   r8   get_list   s    zHeaders.get_list)rg   r2   c                 C  s:   t |}| D ]}|| kr| | q| j|j d S rh   )r+   r|   popri   r   )rl   rg   r<   r7   r7   r8   update  s
    zHeaders.updatec                 C  s   t | | jdS )Nr6   )r+   r1   rx   r7   r7   r8   copy  s    zHeaders.copy)r<   r2   c                   s@   |  j  fddjD }|r4d|S t|dS )z
        Return a single header value.

        If there are multiple headers with the same key, then we concatenate
        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2
        c                   s&   g | ]\}}}| kr| jqS r7   ry   )rt   ru   
header_keyheader_valueZnormalized_keyrl   r7   r8   rv   %  s   z'Headers.__getitem__.<locals>.<listcomp>r}   N)r`   r?   r1   ri   joinr   )rl   r<   r_   r7   r   r8   __getitem__  s    
zHeaders.__getitem__r<   rA   r2   c                   s   | | jpd}| | jpd}|   fddt| jD }t|dd D ]}| j|= qP|r||d }| |f| j|< n| j| |f dS )zs
        Set the header `key` to `value`, removing any duplicate entries.
        Retains insertion order.
        ro   c                   s"   g | ]\}\}}}| kr|qS r7   r7   rt   idxru   r   Z
lookup_keyr7   r8   rv   9  s   z'Headers.__setitem__.<locals>.<listcomp>r   Nr   )r?   rk   r`   	enumerateri   reversedrW   )rl   r<   rA   Zset_key	set_valueZfound_indexesr   r7   r   r8   __setitem__0  s    

zHeaders.__setitem__c                   sN   |  | j  fddt| jD }|s4t|t|D ]}| j|= q<dS )z*
        Remove the header `key`.
        c                   s&   g | ]\}\}}}|   kr|qS r7   )r`   r   Zdel_keyr7   r8   rv   N  s   z'Headers.__delitem__.<locals>.<listcomp>N)r`   r?   r1   r   ri   r   r   )rl   r<   Zpop_indexesr   r7   r   r8   __delitem__H  s    
zHeaders.__delitem__c                 C  s$   |  | j}|dd | jD kS )Nc                 S  s   g | ]\}}}|qS r7   r7   )rt   ru   r<   r7   r7   r8   rv   \  s     z(Headers.__contains__.<locals>.<listcomp>)r`   r?   r1   ri   )rl   r<   r   r7   r7   r8   __contains__Z  s    zHeaders.__contains__ztyping.Iterator[typing.Any]c                 C  s   t |  S rh   )iterr|   rx   r7   r7   r8   __iter__^  s    zHeaders.__iter__intc                 C  s
   t | jS rh   )lenri   rx   r7   r7   r8   __len__a  s    zHeaders.__len__)otherr2   c                 C  sT   zt |}W n tk
r"   Y dS X dd | jD }dd |jD }t|t|kS )NFc                 S  s   g | ]\}}}||fqS r7   r7   rz   r7   r7   r8   rv   j  s     z"Headers.__eq__.<locals>.<listcomp>c                 S  s   g | ]\}}}||fqS r7   r7   rz   r7   r7   r8   rv   k  s     )r+   rV   ri   sorted)rl   r   Zother_headersZ	self_listZ
other_listr7   r7   r8   __eq__d  s    zHeaders.__eq__c                 C  sv   | j j}d}| jdkr"d| j}tt|  }t|}t|t|k}|rb| d|| dS | d|| dS )NrP   r=   z, encoding=())	__class____name__r1   rj   rd   r   dictr   )rl   
class_nameZencoding_strZas_listZas_dictZno_duplicate_keysr7   r7   r8   __repr__n  s    
zHeaders.__repr__)NN)N)F)N)r   
__module____qualname____doc__rm   propertyr1   setterrp   r|   r~   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r7   r7   r7   r8   r+      s4     

c                   @  s   e Zd Z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ZdddddZeddddZddddZddddZddddZ	d dd!d"Z
d dd#d$d%ZdS )&r,   N)	r[   rg   cookiescontentdatafilesjsonstream
extensionsr/   z	URL | strzQueryParamTypes | Nonere   CookieTypes | NonezRequestContent | NonezRequestData | NonezRequestFiles | Noneztyping.Any | None'SyncByteStream | AsyncByteStream | NonezRequestExtensions | Nonerf   )methodrQ   r[   rg   r   r   r   r   r   r   r   r2   c       	      	   C  s   |  | _|d krt|n
t||d| _t|| _|d kr>i nt|| _|rZt|	|  |
d kr| j
d}t||||	t|r|| jjnd dd\}}
| | |
| _t|
tr|   n|
| _d S )N)r[   rF   )rE   )r   r   r   r   boundary)upperr   r'   rQ   r+   rg   r   r   r*   set_cookie_headerr   r	   r   r?   r1   _preparer   r>   r   read)rl   r   rQ   r[   rg   r   r   r   r   r   r   r   rE   r7   r7   r8   rm     s0    





zRequest.__init__dict[str, str]default_headersr2   c                 C  s   |  D ].\}}| dkr(d| jkr(q| j|| qg }d| jk}d| jkpXd| jk}|sx| jjrx|d| jjf |s| jdkr|d t	|| jj
 | _d S )Ntransfer-encodingzContent-LengthHostzTransfer-Encodings   Host)POSTPUTPATCH)s   Content-Length   0)r_   r`   rg   
setdefaultrQ   hostrW   netlocr   r+   rp   )rl   r   r<   rA   Zauto_headersZhas_hostZhas_content_lengthr7   r7   r8   r     s    

zRequest._preparer;   rn   c                 C  s   t | dst | jS N_content)hasattrr   r   rx   r7   r7   r8   r     s    
zRequest.contentc                 C  sH   t | dsBt| jtjstd| j| _t| jtsBt| j| _| jS )6
        Read and return the request content.
        r       )	r   r>   r   typingIterableAssertionErrorr   r   r   rx   r7   r7   r8   r     s    
zRequest.readc                   sX   t | dsRt| jtjstddd | j2 I dH | _t| jtsRt| j| _| jS )r   r   r   c                   s   g | z3 d H W }|q6 S rh   r7   rt   partr7   r7   r8   rv     s     z!Request.aread.<locals>.<listcomp>N)	r   r>   r   r   AsyncIterabler   r   r   r   rx   r7   r7   r8   aread  s    
zRequest.areadc                 C  s,   | j j}t| j}d| d| jd|dS )N<r   r}   z)>)r   r   r/   rQ   r   )rl   r   rQ   r7   r7   r8   r     s    
zRequest.__repr__dict[str, typing.Any]c                 C  s   dd | j  D S )Nc                 S  s   i | ]\}}|d kr||qS ))r   r   r7   rt   namerA   r7   r7   r8   r{     s    z(Request.__getstate__.<locals>.<dictcomp>__dict__r_   rx   r7   r7   r8   __getstate__  s    zRequest.__getstate__stater2   c                 C  s0   |  D ]\}}t| || qi | _t | _d S rh   )r_   setattrr   r   r   rl   r   r   rA   r7   r7   r8   __setstate__  s    zRequest.__setstate__)r   r   r   rm   r   r   r   r   r   r   r   r   r7   r7   r7   r8   r,   ~  s$   (:c                   @  s  e Zd Z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dZdddddZeddddZejdddddZeddddZejdddd dZed!dd"d#Z	ed!dd$d%Z
ed&dd'd(Zed)dd*d+Zed!dd,d-Zeddd.d/Zejd!ddd0d/Zeddd1d2Zd3dd4d5Zed6dd7d8Zed6dd9d:Zed6dd;d<Zed6dd=d>Zed6dd?d@Zed6ddAdBZed6ddCdDZd ddEdFZdddGdHdIZedJddKdLZedMddNdOZedddPdQZd!ddRdSZdTddUdVZdTddWdXdYZd)ddZd[Z dxd\d]d^d_d`Z!dyd\dad^dbdcZ"daddddeZ#dzd\d]d^dfdgZ$dddhdiZ%d)ddjdkZ&d{d\dld^dmdnZ'd|d\dod^dpdqZ(doddrdsZ)d}d\dld^dtduZ*dddvdwZ+dS )~r-   Nro   )
rg   r   texthtmlr   r   requestr   historydefault_encodingr   re   zResponseContent | Noner:   r   r   zRequest | NonezResponseExtensions | Nonezlist[Response] | Nonez#str | typing.Callable[[bytes], str]rf   )status_coderg   r   r   r   r   r   r   r   r   r   r2   c       
         C  s   || _ t|| _|| _d | _|	d kr(i nt|	| _|
d kr>g nt|
| _d| _	d| _
|| _|d krt||||\}}| | || _t|tr|   n|| _d| _d S )NFr   )r   r+   rg   _requestZnext_requestr   r   rj   r   	is_closedis_stream_consumedr   r
   r   r   r>   r   r   _num_bytes_downloaded)rl   r   rg   r   r   r   r   r   r   r   r   r   r7   r7   r8   rm     s"    



zResponse.__init__r   r   c                 C  s<   |  D ].\}}| dkr(d| jkr(q| j|| qd S )Nr   zcontent-length)r_   r`   rg   r   )rl   r   r<   rA   r7   r7   r8   r   ;  s    zResponse._preparezdatetime.timedeltarn   c                 C  s   t | dstd| jS )ze
        Returns the time taken for the complete request/response
        cycle to complete.
        _elapsedzK'.elapsed' may only be accessed after the response has been read or closed.)r   RuntimeErrorr   rx   r7   r7   r8   elapsedB  s
    
zResponse.elapsed)r   r2   c                 C  s
   || _ d S rh   )r   )rl   r   r7   r7   r8   r   O  s    r,   c                 C  s   | j dkrtd| j S )zR
        Returns the request instance associated to the current response.
        Nz7The request instance has not been set on this response.)r   r   rx   r7   r7   r8   r   S  s
    
zResponse.requestrN   c                 C  s
   || _ d S rh   )r   rs   r7   r7   r8   r   ^  s    r/   c                 C  s8   z| j d }W n tk
r$   Y dS X |jdddS d S )Nhttp_versionzHTTP/1.1r=   ignoreerrors)r   r   rq   )rl   r   r7   r7   r8   r   b  s
    zResponse.http_versionc                 C  sB   z| j d }W n  tk
r.   t| j Y S X |jdddS d S )Nreason_phraser=   r   r   )r   r   r   Zget_reason_phraser   rq   )rl   r   r7   r7   r8   r   k  s
    zResponse.reason_phraser'   c                 C  s   | j jS )zA
        Returns the URL for which the request was made.
        )r   rQ   rx   r7   r7   r8   rQ   t  s    zResponse.urlr;   c                 C  s   t | dst | jS r   )r   r   r   rx   r7   r7   r8   r   {  s    
zResponse.contentc                 C  sN   t | dsH| j}|sd| _n,t| jp&dd}d|| j| g| _| jS )N_textrP   ro   r6   )r   r   r   r   r1   r   rq   flush)rl   r   decoderr7   r7   r8   r     s    
zResponse.textc                 C  sZ   t | dsT| j}|dks t|sJt| jtr4| j}nt | drJ| | j}|pPd| _| jS )a  
        Return an encoding to use for decoding the byte content into text.
        The priority for determining this is given by...

        * `.encoding = <>` has been set explicitly.
        * The encoding as specified by the charset parameter in the Content-Type header.
        * The encoding as determined by `default_encoding`, which may either be
          a string like "utf-8" indicating the encoding to use, or may be a callable
          which enables charset autodetection.
        rk   Nr   ro   )r   charset_encodingr9   r>   r   r/   r   rk   )rl   r1   r7   r7   r8   r1     s    


zResponse.encodingc                 C  s   t | drtd|| _dS )z
        Set the encoding to use for decoding the byte content into text.

        If the `text` attribute has been accessed, attempting to set the
        encoding will throw a ValueError.
        r   z?Setting encoding after `text` has been accessed is not allowed.N)r   rV   rk   rs   r7   r7   r8   r1     s
    
c                 C  s    | j d}|dkrdS t|S )zO
        Return the encoding, as specified by the Content-Type header.
        zContent-TypeN)rg   r   rM   )rl   rE   r7   r7   r8   r     s    zResponse.charset_encodingr   c              	   C  s   t | dsg }| jjddd}|D ]B}|  }zt| }||  W q" tk
rb   Y q"Y q"X q"t|dkr~|d | _	n"t|dkrt
|d| _	nt | _	| j	S )z
        Returns a decoder instance which can be used to decode the raw byte
        content, depending on the Content-Encoding used in the response.
        _decoderzcontent-encodingT)r   r   r   )children)r   rg   r   rS   r`   r   rW   r   r   r   r   r   )rl   Zdecodersr~   rA   Zdecoder_clsr7   r7   r8   _get_content_decoder  s     
zResponse._get_content_decoderr0   c                 C  s   t | jS )zU
        A property which is `True` for 1xx status codes, `False` otherwise.
        )r   is_informationalr   rx   r7   r7   r8   r     s    zResponse.is_informationalc                 C  s   t | jS )zU
        A property which is `True` for 2xx status codes, `False` otherwise.
        )r   
is_successr   rx   r7   r7   r8   r     s    zResponse.is_successc                 C  s   t | jS )a  
        A property which is `True` for 3xx status codes, `False` otherwise.

        Note that not all responses with a 3xx status code indicate a URL redirect.

        Use `response.has_redirect_location` to determine responses with a properly
        formed URL redirection.
        )r   is_redirectr   rx   r7   r7   r8   r    s    
zResponse.is_redirectc                 C  s   t | jS )zU
        A property which is `True` for 4xx status codes, `False` otherwise.
        )r   is_client_errorr   rx   r7   r7   r8   r    s    zResponse.is_client_errorc                 C  s   t | jS )zU
        A property which is `True` for 5xx status codes, `False` otherwise.
        )r   is_server_errorr   rx   r7   r7   r8   r    s    zResponse.is_server_errorc                 C  s   t | jS )z]
        A property which is `True` for 4xx and 5xx status codes, `False` otherwise.
        )r   is_errorr   rx   r7   r7   r8   r    s    zResponse.is_errorc                 C  s(   | j tjtjtjtjtjfko&d| jkS )zs
        Returns True for 3xx responses with a properly formed URL redirection,
        `False` otherwise.
        ZLocation)r   r   MOVED_PERMANENTLYFOUND	SEE_OTHERTEMPORARY_REDIRECTPERMANENT_REDIRECTrg   rx   r7   r7   r8   has_redirect_location  s    zResponse.has_redirect_locationc                 C  st   | j }|dkrtd| jr | S | jr,d}nd}| jd }dddd	d
}||d}|j| |d}t||| ddS )z>
        Raise the `HTTPStatusError` if one occurred.
        NzYCannot call `raise_for_status` as the request instance has not been set on this response.z{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'
Redirect location: '{0.headers[location]}'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}z{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}d   zInformational responsezRedirect responsezClient errorzServer error)r            zInvalid status code)
error_type)r   response)r   r   r   r
  r   r   formatr   )rl   r   rI   Zstatus_classZerror_typesr  r7   r7   r8   raise_for_status  s*    
zResponse.raise_for_status)kwargsr2   c                 K  s   t j| jf|S rh   )jsonlibloadsr   )rl   r  r7   r7   r8   r   ?  s    zResponse.jsonr*   c                 C  s$   t | dst | _| j|  | jS )N_cookies)r   r*   r  extract_cookiesrx   r7   r7   r8   r   B  s    
zResponse.cookiesz dict[str | None, dict[str, str]]c                 C  s*   | j d}|dkri S dd t|D S )zI
        Returns the parsed header links of the response, if any
        r\   Nc                 S  s"   i | ]}| d p| d|qS )relrQ   )r   )rt   r\   r7   r7   r8   r{   R  s    z"Response.links.<locals>.<dictcomp>)rg   r   r^   )rl   headerr7   r7   r8   rX   I  s    zResponse.linksc                 C  s   | j S rh   )r   rx   r7   r7   r8   num_bytes_downloadedW  s    zResponse.num_bytes_downloadedc                 C  s   d| j  d| j dS )Nz<Response [ ]>)r   r   rx   r7   r7   r8   r   [  s    zResponse.__repr__r   c                 C  s   dd | j  D S )Nc                 S  s   i | ]\}}|d kr||qS ))r   r   r   r   r7   r   r7   r7   r8   r{   _  s    z)Response.__getstate__.<locals>.<dictcomp>r   rx   r7   r7   r8   r   ^  s    zResponse.__getstate__r   c                 C  s6   |  D ]\}}t| || qd| _i | _t | _d S )NT)r_   r   r   r   r   r   r   r7   r7   r8   r   e  s
    zResponse.__setstate__c                 C  s    t | dsd|  | _| jS )7
        Read and return the response content.
        r   r   )r   r   
iter_bytesr   rx   r7   r7   r8   r   l  s    
zResponse.readz
int | Noneztyping.Iterator[bytes])
chunk_sizer2   c              	   c  s   t | drT|dkrt| jn|}tdt| jt|dD ]}| j|||  V  q8n|  }t|d}t| jdf | 	 D ]$}|
|}|
|D ]
}|V  qq|| }|
|D ]
}|V  q| D ]
}|V  qW 5 Q R X dS z
        A byte-iterator over the decoded response content.
        This allows us to handle gzip, deflate, brotli, and zstd encoded responses.
        r   Nr   r   r  r   )r   r   r   rangemaxr   r   r   r   iter_rawrq   r   rl   r  ir   chunkerZ	raw_bytesdecodedchunkr7   r7   r8   r  t  s     



zResponse.iter_bytestyping.Iterator[str]c              	   c  s   t | jp
dd}t|d}t| jdf |  D ]$}||}||D ]
}|V  qHq0| }||D ]
}|V  qh| D ]
}|V  q|W 5 Q R X dS z
        A str-iterator over the decoded response content
        that handles both gzip, deflate, etc but also detects the content's
        string encoding.
        ro   r6   r!  r"  N)r   r1   r   r   r   r  rq   r   rl   r  r   r(  Zbyte_contentZtext_contentr*  r7   r7   r8   	iter_text  s    


zResponse.iter_textc              	   c  sZ   t  }t| jd> |  D ]}||D ]
}|V  q*q| D ]
}|V  q@W 5 Q R X d S Nr"  )r   r   r   r.  rq   r   rl   r   r   liner7   r7   r8   
iter_lines  s    
zResponse.iter_linesc              	   c  s   | j rt | jrt t| jts,tdd| _ d| _t	|d}t
| jd: | jD ],}|  jt|7  _||D ]
}|V  qvqVW 5 Q R X | D ]
}|V  q|   dS )@
        A byte-iterator over the raw response content.
        z5Attempted to call a sync iterator on an async stream.Tr   r!  r"  N)r   r   r   r   r>   r   r&   r   r   r   r   r   r   rq   r   closerl   r  r(  Zraw_stream_bytesr*  r7   r7   r8   r%    s"    

zResponse.iter_rawc              	   C  sF   t | jtstd| jsBd| _t| jd | j  W 5 Q R X dS )
        Close the response and release the connection.
        Automatically called if the response body is read to completion.
        z3Attempted to call an sync close on an async stream.Tr"  N)r>   r   r&   r   r   r   r   r4  rx   r7   r7   r8   r4    s    zResponse.closec                   s0   t | ds*ddd |  2 I dH | _| jS )r  r   r   c                   s   g | z3 d H W }|q6 S rh   r7   r   r7   r7   r8   rv     s     z"Response.aread.<locals>.<listcomp>N)r   r   aiter_bytesr   rx   r7   r7   r8   r     s    
 zResponse.areadztyping.AsyncIterator[bytes]c              	   C s   t | drT|dkrt| jn|}tdt| jt|dD ]}| j|||  V  q8n|  }t|d}t| jdp | 	 2 z,3 dH W }|
|}|
|D ]
}|V  qq|6 | }|
|D ]
}|V  q| D ]
}|V  qW 5 Q R X dS r   )r   r   r   r#  r$  r   r   r   r   	aiter_rawrq   r   r&  r7   r7   r8   r7    s     


zResponse.aiter_bytesztyping.AsyncIterator[str]c              	   C s   t | jp
dd}t|d}t| jdp |  2 z,3 dH W }||}||D ]
}|V  qPq06 | }||D ]
}|V  qr| D ]
}|V  qW 5 Q R X dS r,  )r   r1   r   r   r   r7  rq   r   r-  r7   r7   r8   
aiter_text  s    

zResponse.aiter_textc              	   C sd   t  }t| jdH |  2 z"3 d H W }||D ]
}|V  q2q6 | D ]
}|V  qJW 5 Q R X d S r/  )r   r   r   r9  rq   r   r0  r7   r7   r8   aiter_lines  s    zResponse.aiter_linesc              	   C s   | j rt | jrt t| jts,tdd| _ d| _t	|d}t
| jdD | j2 z43 dH W }|  jt|7  _||D ]
}|V  q~qV6 W 5 Q R X | D ]
}|V  q|  I dH  dS )r3  z6Attempted to call an async iterator on an sync stream.Tr   r!  r"  N)r   r   r   r   r>   r   r   r   r   r   r   r   r   rq   r   acloser5  r7   r7   r8   r8    s"    
zResponse.aiter_rawc              	     sL   t | jtstd| jsHd| _t| jd | j I dH  W 5 Q R X dS )r6  z3Attempted to call an async close on an sync stream.Tr"  N)r>   r   r   r   r   r   r   r;  rx   r7   r7   r8   r;  )  s    zResponse.aclose)N)N)N)N)N)N),r   r   r   rm   r   r   r   r   r   r   r   rQ   r   r   r1   r   r   r   r   r  r  r  r  r
  r  r   r   rX   r  r   r   r   r   r  r.  r2  r%  r4  r   r7  r9  r:  r8  r;  r7   r7   r7   r8   r-     s   (7


%		  
 c                   @  s:  e Zd ZdZd:dddddZddd	d
dZdddddZd;ddddddddZd<ddddddddZd=dddddddZ	d>ddddddZ
d?dddd d!Zdddd"d#d$Zddd%d&d'Zddd%d(d)Zd*d+d,d-Zd.d+d/d0Zd1d+d2d3Zdd+d4d5ZG d6d7 d7ejjZG d8d9 d9ZdS )@r*   z-
    HTTP Cookies, as a mutable mapping.
    Nr   rf   )r   r2   c                 C  s   |d kst |trDt | _t |tr| D ]\}}| || q,n`t |trrt | _|D ]\}}| || qZn2t |trt | _|jD ]}| j| qn|| _d S rh   )	r>   r   r   jarr_   setrj   r*   
set_cookie)rl   r   r<   rA   cookier7   r7   r8   rm   <  s    



zCookies.__init__r-   r  r2   c                 C  s(   |  |}| |j}| j|| dS )zO
        Loads any cookies based on the response `Set-Cookie` headers.
        N)_CookieCompatResponse_CookieCompatRequestr   r<  r  )rl   r  Zurllib_responseurllib_requestr7   r7   r8   r  M  s    
zCookies.extract_cookiesr,   r   r2   c                 C  s   |  |}| j| dS )zM
        Sets an appropriate 'Cookie:' HTTP header on the `Request`.
        N)rB  r<  add_cookie_header)rl   r   rC  r7   r7   r8   r   V  s    
zCookies.set_cookie_headerrP   /r/   )r   rA   domainpathr2   c                 C  sT   d||dd|t ||d|t |dddddddidd}tf |}| j| dS )zU
        Set a cookie value by name. May optionally include domain and path.
        r   NF.THttpOnly)versionr   rA   portport_specifiedrG  domain_specifieddomain_initial_dotrH  path_specifiedsecureexpiresdiscardcommentcomment_urlrestrfc2109)r0   
startswithr   r<  r>  )rl   r   rA   rG  rH  r  r?  r7   r7   r8   r=  ]  s(    
zCookies.setr:   )r   r   rG  rH  r2   c                 C  sn   d}| j D ]R}|j|kr
|dks*|j|kr
|dks<|j|kr
|dk	rVd| }t||j}q
|dkrj|S |S )z
        Get a cookie by name. May optionally include domain and path
        in order to specify exactly which cookie to retrieve.
        Nz!Multiple cookies exist with name=)r<  r   rG  rH  r   rA   )rl   r   r   rG  rH  rA   r?  rI   r7   r7   r8   r   w  s    


zCookies.get)r   rG  rH  r2   c                   s\    dk	r dk	r | j  S  fdd| j D }|D ]}| j |j|j|j q<dS )z
        Delete a cookie by name. May optionally include domain and path
        in order to specify exactly which cookie to delete.
        Nc                   s>   g | ]6}|j kr d ks$|j krd ks6|jkr|qS rh   )r   rG  rH  rt   r?  rG  r   rH  r7   r8   rv     s   
 
 
z"Cookies.delete.<locals>.<listcomp>)r<  clearrG  rH  r   )rl   r   rG  rH  remover?  r7   rZ  r8   delete  s    
zCookies.delete)rG  rH  r2   c                 C  sD   g }|dk	r| | |dk	r4|dk	s*t| | | jj|  dS )z
        Delete all cookies. Optionally include a domain and path in
        order to only delete a subset of all the cookies.
        N)rW   r   r<  r[  )rl   rG  rH  argsr7   r7   r8   r[    s    

zCookies.clearc                 C  s$   t |}|jD ]}| j| qd S rh   )r*   r<  r>  )rl   r   r?  r7   r7   r8   r     s    
zCookies.update)r   rA   r2   c                 C  s   |  ||S rh   )r=  rl   r   rA   r7   r7   r8   r     s    zCookies.__setitem__)r   r2   c                 C  s   |  |}|d krt||S rh   )r   r   r_  r7   r7   r8   r     s    
zCookies.__getitem__c                 C  s
   |  |S rh   )r]  )rl   r   r7   r7   r8   r     s    zCookies.__delitem__r   rn   c                 C  s
   t | jS rh   )r   r<  rx   r7   r7   r8   r     s    zCookies.__len__r+  c                 C  s   dd | j D S )Nc                 s  s   | ]}|j V  qd S rh   )r   rY  r7   r7   r8   	<genexpr>  s     z#Cookies.__iter__.<locals>.<genexpr>r<  rx   r7   r7   r8   r     s    zCookies.__iter__r0   c                 C  s   | j D ]} dS dS )NTFra  )rl   ru   r7   r7   r8   __bool__  s    
zCookies.__bool__c                 C  s"   d dd | jD }d| dS )Nr}   c              	   S  s*   g | ]"}d |j  d|j d|j dqS )z<Cookie rR   z for z />)r   rA   rG  rY  r7   r7   r8   rv     s   z$Cookies.__repr__.<locals>.<listcomp>z	<Cookies[r  )r   r<  )rl   Zcookies_reprr7   r7   r8   r     s    zCookies.__repr__c                      s>   e Zd ZdZddd fddZdddd fd	d
Z  ZS )zCookies._CookieCompatRequest
        Wraps a `Request` instance up in a compatibility interface suitable
        for use with `CookieJar` operations.
        r,   rf   rD  c                   s*   t  jt|jt|j|jd || _d S )N)rQ   rg   r   )superrm   r/   rQ   r   rg   r   r   )rl   r   r   r7   r8   rm     s    z%Cookies._CookieCompatRequest.__init__r/   r   c                   s   t  || || jj|< d S rh   )rd  add_unredirected_headerr   rg   )rl   r<   rA   re  r7   r8   rf    s    z4Cookies._CookieCompatRequest.add_unredirected_header)r   r   r   r   rm   rf  __classcell__r7   r7   re  r8   rB    s   rB  c                   @  s.   e Zd ZdZdddddZddd	d
ZdS )zCookies._CookieCompatResponserc  r-   rf   r@  c                 C  s
   || _ d S rh   )r  )rl   r  r7   r7   r8   rm     s    z&Cookies._CookieCompatResponse.__init__zemail.message.Messagern   c                 C  s,   t j }| jj D ]\}}|||< q|S rh   )rH   rI   rJ   r  rg   r   )rl   infor<   rA   r7   r7   r8   rh    s    

z"Cookies._CookieCompatResponse.infoN)r   r   r   r   rm   rh  r7   r7   r7   r8   rA    s   rA  )N)rP   rF  )NNN)NN)NN)N)r   r   r   r   rm   r  r   r=  r   r]  r[  r   r   r   r   r   r   rb  r   urllibr   r,   rB  rA  r7   r7   r7   r8   r*   7  s.   	     
)N)N)J
__future__r   r3   datetimeemail.messagerH   r   r  rT   r   urllib.requestri  collections.abcr   http.cookiejarr   r   r   r   r   r	   r
   	_decodersr   r   r   r   r   r   r   r   _exceptionsr   r   r   r   r   r   r   Z
_multipartr   Z_status_codesr   _typesr   r   r   r   r    r!   r"   r#   r$   r%   r&   Z_urlsr'   _utilsr(   r)   __all__ra   r9   r@   rD   rM   r^   rd   MutableMappingr/   r+   r,   r-   r*   r7   r7   r7   r8   <module>   sF   (
$	4%	 t     8