U
    ÁÎjipG  ã                   @   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 ddlm	Z	m
Z
 ddlmZ ddlmZmZm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dgZe e¡ZdZdZe de¡Z dd„ Z!e "e!e ¡e "e!e ¡dœZ#e	e
dœZ$G dd„ deƒZ%G dd„ de%ƒZ&dd„ Z'dS )é    )Úabsolute_importNé   )ÚHTTPHeaderDictÚRecentlyUsedContainer)ÚHTTPConnectionPoolÚHTTPSConnectionPool)Úport_by_scheme)ÚLocationValueErrorÚMaxRetryErrorÚProxySchemeUnknown)Úurljoin)ÚRequestMethods)Ú	parse_url)ÚRetryÚPoolManagerÚProxyManagerÚproxy_from_url)Zkey_fileZ	cert_fileZ	cert_reqsZca_certsZssl_versionZca_cert_dirZssl_contextZkey_password)Z
key_schemeZkey_hostZkey_portZkey_timeoutZkey_retriesZ
key_strictZ	key_blockZkey_source_addressZkey_key_fileZkey_key_passwordZkey_cert_fileZkey_cert_reqsZkey_ca_certsZkey_ssl_versionZkey_ca_cert_dirZkey_ssl_contextZkey_maxsizeZkey_headersZ
key__proxyZkey__proxy_headersZkey_socket_optionsZkey__socks_optionsZkey_assert_hostnameZkey_assert_fingerprintZkey_server_hostnameÚPoolKeyc                 C   sÂ   |  ¡ }|d  ¡ |d< |d  ¡ |d< dD ],}||kr,|| dk	r,t||  ¡ ƒ||< q,| d¡}|dk	rxt|ƒ|d< t| ¡ ƒD ]}| |¡|d| < q„| j	D ]}||kr¢d||< q¢| f |ŽS )a÷  
    Create a pool key out of a request context dictionary.

    According to RFC 3986, both the scheme and host are case-insensitive.
    Therefore, this function normalizes both before constructing the pool
    key for an HTTPS request. If you wish to change this behaviour, provide
    alternate callables to ``key_fn_by_scheme``.

    :param key_class:
        The class to use when constructing the key. This should be a namedtuple
        with the ``scheme`` and ``host`` keys at a minimum.
    :type  key_class: namedtuple
    :param request_context:
        A dictionary-like object that contain the context for a request.
    :type  request_context: dict

    :return: A namedtuple that can be used as a connection pool key.
    :rtype:  PoolKey
    ÚschemeÚhost)ÚheadersÚ_proxy_headersZ_socks_optionsNZsocket_optionsZkey_)
ÚcopyÚlowerÚ	frozensetÚitemsÚgetÚtupleÚlistÚkeysÚpopÚ_fields)Z	key_classÚrequest_contextÚcontextÚkeyZsocket_optsZfield© r%   ú5/usr/lib/python3/dist-packages/urllib3/poolmanager.pyÚ_default_key_normalizerD   s    


r'   ©ÚhttpÚhttpsc                   @   sx   e Zd ZdZdZddd„Zdd„ Zdd	„ Zdd
d„Zdd„ Z	ddd„Z
dd„ Zddd„Zd dd„Zdd„ Zd!dd„ZdS )"r   a$  
    Allows for arbitrary requests while transparently keeping track of
    necessary connection pools for you.

    :param num_pools:
        Number of connection pools to cache before discarding the least
        recently used pool.

    :param headers:
        Headers to include with all requests, unless other headers are given
        explicitly.

    :param \**connection_pool_kw:
        Additional parameters are used to create fresh
        :class:`urllib3.connectionpool.ConnectionPool` instances.

    Example::

        >>> manager = PoolManager(num_pools=2)
        >>> r = manager.request('GET', 'http://google.com/')
        >>> r = manager.request('GET', 'http://google.com/mail')
        >>> r = manager.request('GET', 'http://yahoo.com/')
        >>> len(manager.pools)
        2

    Né
   c                 K   s~   t  | |¡ d|krR|d }t|tƒsR|dk	}tj|dd�}||_| ¡ }||d< || _t|dd„ d�| _	t
| _
t ¡ | _d S )NÚretriesF©Úredirectc                 S   s   |   ¡ S ©N)Úclose)Úpr%   r%   r&   Ú<lambda>²   ó    z&PoolManager.__init__.<locals>.<lambda>)Zdispose_func)r   Ú__init__Ú
isinstancer   Úfrom_intÚraise_on_redirectr   Úconnection_pool_kwr   ÚpoolsÚpool_classes_by_schemeÚkey_fn_by_scheme)ÚselfÚ	num_poolsr   r8   r,   r7   r%   r%   r&   r4   Ÿ   s    
	zPoolManager.__init__c                 C   s   | S r/   r%   ©r<   r%   r%   r&   Ú	__enter__¹   s    zPoolManager.__enter__c                 C   s   |   ¡  dS )NF)Úclear)r<   Úexc_typeZexc_valZexc_tbr%   r%   r&   Ú__exit__¼   s    zPoolManager.__exit__c                 C   s^   | j | }|dkr| j ¡ }dD ]}| |d¡ q |dkrPtD ]}| |d¡ q>|||f|ŽS )a·  
        Create a new :class:`ConnectionPool` based on host, port, scheme, and
        any additional pool keyword arguments.

        If ``request_context`` is provided, it is provided as keyword arguments
        to the pool class used. This method is used to actually create the
        connection pools handed out by :meth:`connection_from_url` and
        companion methods. It is intended to be overridden for customization.
        N)r   r   Úportr)   )r:   r8   r   r    ÚSSL_KEYWORDS)r<   r   r   rC   r"   Zpool_clsr$   Úkwr%   r%   r&   Ú	_new_poolÁ   s    


zPoolManager._new_poolc                 C   s   | j  ¡  dS )z´
        Empty our store of pools and direct them all to close.

        This will not affect in-flight connections, but they will not be
        re-used after completion.
        N)r9   r@   r>   r%   r%   r&   r@   Ü   s    zPoolManager.clearr)   c                 C   sT   |st dƒ‚|  |¡}|pd|d< |s:t |d  ¡ d¡}||d< ||d< |  |¡S )a�  
        Get a :class:`ConnectionPool` based on the host, port, and scheme.

        If ``port`` isn't given, it will be derived from the ``scheme`` using
        ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
        provided, it is merged with the instance's ``connection_pool_kw``
        variable and used to create the new connection pool, if one is
        needed.
        zNo host specified.r)   r   éP   rC   r   )r	   Ú_merge_pool_kwargsr   r   r   Úconnection_from_context)r<   r   rC   r   Úpool_kwargsr"   r%   r%   r&   Úconnection_from_hostå   s    
z PoolManager.connection_from_hostc                 C   s,   |d   ¡ }| j| }||ƒ}| j||d�S )zâ
        Get a :class:`ConnectionPool` based on the request context.

        ``request_context`` must at least contain the ``scheme`` key and its
        value must be a key in ``key_fn_by_scheme`` instance variable.
        r   ©r"   )r   r;   Úconnection_from_pool_key)r<   r"   r   Zpool_key_constructorÚpool_keyr%   r%   r&   rI   ü   s    
z#PoolManager.connection_from_contextc              
   C   sl   | j j�Z | j  |¡}|r*|W  5 Q R £ S |d }|d }|d }| j||||d�}|| j |< W 5 Q R X |S )zû
        Get a :class:`ConnectionPool` based on the provided pool key.

        ``pool_key`` should be a namedtuple that only contains immutable
        objects. At a minimum it must have the ``scheme``, ``host``, and
        ``port`` fields.
        r   r   rC   rL   )r9   Úlockr   rF   )r<   rN   r"   Zpoolr   r   rC   r%   r%   r&   rM   	  s    
z$PoolManager.connection_from_pool_keyc                 C   s    t |ƒ}| j|j|j|j|d�S )aÖ  
        Similar to :func:`urllib3.connectionpool.connection_from_url`.

        If ``pool_kwargs`` is not provided and a new pool needs to be
        constructed, ``self.connection_pool_kw`` is used to initialize
        the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
        is provided, it is used instead. Note that if a new pool does not
        need to be created for the request, the provided ``pool_kwargs`` are
        not used.
        )rC   r   rJ   )r   rK   r   rC   r   )r<   ÚurlrJ   Úur%   r%   r&   Úconnection_from_url!  s       ÿzPoolManager.connection_from_urlc              	   C   sV   | j  ¡ }|rR| ¡ D ]:\}}|dkrHz
||= W qP tk
rD   Y qPX q|||< q|S )a  
        Merge a dictionary of override values for self.connection_pool_kw.

        This does not modify self.connection_pool_kw and returns a new dict.
        Any keys in the override dictionary with a value of ``None`` are
        removed from the merged dictionary.
        N)r8   r   r   ÚKeyError)r<   ÚoverrideZbase_pool_kwargsr$   Úvaluer%   r%   r&   rH   1  s    


zPoolManager._merge_pool_kwargsTc                 K   s¶  t |ƒ}| j|j|j|jd�}d|d< d|d< d|krD| j ¡ |d< | jdk	rj|jdkrj|j||f|Ž}n|j||j	f|Ž}|o†| 
¡ }|s�|S t||ƒ}|jdkrÄd	}d|d
< t|d ƒ ¡ |d< | d|j¡}	t|	tƒsêtj|	|d�}	|	j�r<| |¡�s<tt |d ¡ƒ}
|
D ]&}| ¡ |	jk�r|d  |d¡ �qz|	j||||d�}	W n, tk
�r~   |	j�rv| ¡  ‚ | Y S X |	|d< ||d< t  d||¡ | ¡  | j||f|ŽS )a]  
        Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
        with custom cross-host redirect logic and only sends the request-uri
        portion of the ``url``.

        The given ``url`` parameter must be absolute, such that an appropriate
        :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
        )rC   r   FZassert_same_hostr.   r   Nr)   i/  ZGETZbodyr,   r-   )ÚresponseZ_poolzRedirecting %s -> %s)!r   rK   r   rC   r   r   r   ÚproxyÚurlopenZrequest_uriZget_redirect_locationr   Zstatusr   Z_prepare_for_method_changer   r,   r5   r   r6   Zremove_headers_on_redirectZis_same_hostr   ÚsixZiterkeysr   r    Z	incrementr
   r7   Z
drain_connÚlogÚinfo)r<   ÚmethodrP   r.   rE   rQ   ZconnrV   Zredirect_locationr,   r   Úheaderr%   r%   r&   rX   E  sN    	


ÿ
zPoolManager.urlopen)r+   N)N)Nr)   N)N)N)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rW   r4   r?   rB   rF   r@   rK   rI   rM   rR   rH   rX   r%   r%   r%   r&   r   �   s   

	


c                       sH   e Zd ZdZd‡ fdd„	Zd‡ fdd„	Zdd	d
„Zd‡ fdd„	Z‡  ZS )r   ax  
    Behaves just like :class:`PoolManager`, but sends all requests through
    the defined proxy, using the CONNECT method for HTTPS URLs.

    :param proxy_url:
        The URL of the proxy to be used.

    :param proxy_headers:
        A dictionary containing headers that will be sent to the proxy. In case
        of HTTP they are being sent with each request, while in the
        HTTPS/CONNECT case they are sent only once. Could be used for proxy
        authentication.

    Example:
        >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
        >>> r1 = proxy.request('GET', 'http://google.com/')
        >>> r2 = proxy.request('GET', 'http://httpbin.org/')
        >>> len(proxy.pools)
        1
        >>> r3 = proxy.request('GET', 'https://httpbin.org/')
        >>> r4 = proxy.request('GET', 'https://twitter.com/')
        >>> len(proxy.pools)
        3

    r+   Nc                    s˜   t |tƒrd|j|j|jf }t|ƒ}|jsFt |jd¡}|j|d�}|jdkrZt	|jƒ‚|| _
|pfi | _| j
|d< | j|d< tt| ƒj||f|Ž d S )Nz
%s://%s:%irG   )rC   r(   Ú_proxyr   )r5   r   r   r   rC   r   r   r   Ú_replacer   rW   Úproxy_headersÚsuperr   r4   )r<   Ú	proxy_urlr=   r   rd   r8   rW   rC   ©Ú	__class__r%   r&   r4   ¥  s"    	
ý




zProxyManager.__init__r)   c                    sD   |dkr t t| ƒj||||d�S t t| ƒj| jj| jj| jj|d�S )Nr*   )rJ   )re   r   rK   rW   r   rC   r   )r<   r   rC   r   rJ   rg   r%   r&   rK   Ä  s    
   ÿ
   ÿz!ProxyManager.connection_from_hostc                 C   s0   ddi}t |ƒj}|r||d< |r,| |¡ |S )z�
        Sets headers needed by proxies: specifically, the Accept and Host
        headers. Only sets headers not provided by the user.
        ZAcceptz*/*ZHost)r   ÚnetlocÚupdate)r<   rP   r   Zheaders_ri   r%   r%   r&   Ú_set_proxy_headersÎ  s    

zProxyManager._set_proxy_headersTc                    sN   t |ƒ}|jdkr0| d| j¡}|  ||¡|d< tt| ƒj||fd|i|—ŽS )z@Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.r)   r   r.   )r   r   r   r   rk   re   r   rX   )r<   r\   rP   r.   rE   rQ   r   rg   r%   r&   rX   Ý  s
    
zProxyManager.urlopen)r+   NN)Nr)   N)N)T)	r^   r_   r`   ra   r4   rK   rk   rX   Ú__classcell__r%   r%   rg   r&   r   Š  s      û

c                 K   s   t f d| i|—ŽS )Nrf   )r   )rP   rE   r%   r%   r&   r   ë  s    )(Z
__future__r   ÚcollectionsÚ	functoolsZloggingÚ_collectionsr   r   Zconnectionpoolr   r   r   Ú
exceptionsr	   r
   r   rY   Zsix.moves.urllib.parser   Zrequestr   Zutil.urlr   Z
util.retryr   Ú__all__Z	getLoggerr^   rZ   rD   Z_key_fieldsÚ
namedtupler   r'   Úpartialr;   r:   r   r   r   r%   r%   r%   r&   Ú<module>   s6   

6

þ
  a