B -<` ‘ã@sÖddlmZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z mZmZmZmZmZmZddlmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!ddl"m#Z#dd l$m%Z%dd l&m'Z'dd l(m)Z)dd l*m+Z+dd l,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5ddl6m7Z7ddl8m9Z9ddl:m;Z;mddl:m?Z?m@Z@e#jAjBZBe CeD¡ZEeFƒZGGdd„deFƒZHejIejJhZKGdd„deHe)ƒZLGdd„deLƒZMdd„ZNdd „Z=dS)!é)Úabsolute_importN)Úerror)Útimeouté)Ú BaseSSLErrorÚBrokenPipeErrorÚDummyConnectionÚHTTPConnectionÚ HTTPExceptionÚHTTPSConnectionÚVerifiedHTTPSConnectionÚport_by_scheme) ÚClosedPoolErrorÚEmptyPoolErrorÚHeaderParsingErrorÚHostChangedErrorÚInsecureRequestWarningÚLocationValueErrorÚ MaxRetryErrorÚNewConnectionErrorÚ ProtocolErrorÚ ProxyErrorÚReadTimeoutErrorÚSSLErrorÚ TimeoutError)Úsix)Úqueue)ÚCertificateError)ÚRequestMethods)Ú HTTPResponse)Úis_connection_dropped)Úconnection_requires_http_tunnel)Ú LifoQueue)Úset_file_position)Úassert_header_parsing)ÚRetry)ÚTimeout)ÚUrlÚ_encode_target)Ú_normalize_host)Úget_hostÚ parse_urlc@sBeZdZdZdZeZd dd„Zdd„Zdd„Z d d „Z d d „Z dS)ÚConnectionPoola; Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. .. note:: ConnectionPool.urlopen() does not normalize or percent-encode target URIs which is useful if your target server doesn't support percent-encoded target URIs. NcCs0|s tdƒ‚t||jd�|_| ¡|_||_dS)NzNo host specified.)Úscheme)rr)r-ÚhostÚlowerÚ _proxy_hostÚport)Úselfr.r1©r3ú=/tmp/pip-target-7cdyy134/lib/python/urllib3/connectionpool.pyÚ__init__Js  zConnectionPool.__init__cCsdt|ƒj|j|jfS)Nz%s(host=%r, port=%r))ÚtypeÚ__name__r.r1)r2r3r3r4Ú__str__RszConnectionPool.__str__cCs|S)Nr3)r2r3r3r4Ú __enter__UszConnectionPool.__enter__cCs | ¡dS)NF)Úclose)r2Úexc_typeÚexc_valÚexc_tbr3r3r4Ú__exit__XszConnectionPool.__exit__cCsdS)zD Close all pooled connections and disable the pool. Nr3)r2r3r3r4r:]szConnectionPool.close)N) r7Ú __module__Ú __qualname__Ú__doc__r-r"ÚQueueClsr5r8r9r>r:r3r3r3r4r,<s  r,c @sºeZdZdZdZeZeZdde j dddddddf dd„Z dd „Z d!d d „Z d d „Zdd„Zdd„Zdd„Zdd„Zedfdd„Zdd„Zdd„Zdd„Zdddddeddddf dd „ZdS)"ÚHTTPConnectionPoola: Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`http.client.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`http.client.HTTPConnection`. :param strict: Causes BadStatusLine to be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1 status line, passed into :class:`http.client.HTTPConnection`. .. note:: Only works in Python 2. This parameter is ignored in Python 3. :param timeout: Socket timeout in seconds for each individual connection. This can be a float or integer, which sets the timeout for the HTTP request, or an instance of :class:`urllib3.util.Timeout` which gives you more fine-grained control over request timeouts. After the constructor has been parsed, this is always a `urllib3.util.Timeout` object. :param maxsize: Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If ``block`` is set to False, more connections will be created but they will not be saved once they've been used. :param block: If set to True, no more than ``maxsize`` connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param retries: Retry configuration to use by default with requests in this pool. :param _proxy: Parsed proxy URL, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param _proxy_headers: A dictionary with proxy headers, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param \**conn_kw: Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, :class:`urllib3.connection.HTTPSConnection` instances. ÚhttpNFrc KsÖt |||¡t ||¡||_t|tƒs4t |¡}|dkrBtj}||_ ||_ |  |¡|_ ||_ | |_| pli|_| |_xt|ƒD]} |j  d¡q€Wd|_d|_| |_|jrÒ|j dg¡|j|jd<|j|jd<dS)NrÚsocket_optionsÚproxyÚ proxy_config)r,r5rÚstrictÚ isinstancer&Ú from_floatr%ÚDEFAULTrÚretriesrBÚpoolÚblockrFÚ proxy_headersrGÚxrangeÚputÚnum_connectionsÚ num_requestsÚconn_kwÚ setdefault)r2r.r1rHrÚmaxsizerNÚheadersrLÚ_proxyÚ_proxy_headersÚ _proxy_configrTÚ_r3r3r4r5¨s.      zHTTPConnectionPool.__init__cCsR|jd7_t d|j|j|jp$d¡|jf|j|j|jj|jdœ|j —Ž}|S)z9 Return a fresh :class:`HTTPConnection`. rz(Starting new HTTP connection (%d): %s:%sÚ80)r.r1rrH) rRÚlogÚdebugr.r1Ú ConnectionClsrÚconnect_timeoutrHrT)r2Úconnr3r3r4Ú _new_connÞs  zHTTPConnectionPool._new_conncCs d}y|jj|j|d�}WnBtk r8t|dƒ‚Yn&tjk r\|jrXt|dƒ‚YnX|r”t|ƒr”t   d|j ¡|  ¡t |ddƒdkr”d}|pž| ¡S) a™ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. N)rNrzPool is closed.z>Pool reached maximum size and no more connections are allowed.z Resetting dropped connection: %sÚ auto_openrr)rMÚgetrNÚAttributeErrorrrÚEmptyrr r]r^r.r:Úgetattrrb)r2rrar3r3r4Ú _get_connós"  zHTTPConnectionPool._get_conncCs\y|jj|dd�dStk r(Yn$tjk rJt d|j¡YnX|rX| ¡dS)aä Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. F)rNNz2Connection pool is full, discarding connection: %s) rMrQrerÚFullr]Úwarningr.r:)r2rar3r3r4Ú _put_connszHTTPConnectionPool._put_conncCsdS)zU Called right before a request is made, after the socket is created. Nr3)r2rar3r3r4Ú_validate_conn6sz!HTTPConnectionPool._validate_conncCsdS)Nr3)r2rar3r3r4Ú_prepare_proxy<sz!HTTPConnectionPool._prepare_proxycCs2|tkr|j ¡St|tƒr$| ¡St |¡SdS)z< Helper that always returns a :class:`urllib3.util.Timeout` N)Ú_DefaultrÚclonerIr&rJ)r2rr3r3r4Ú _get_timeout@s   zHTTPConnectionPool._get_timeoutcCsjt|tƒrt||d|ƒ‚t|dƒr>|jtkr>t||d|ƒ‚dt|ƒksVdt|ƒkrft||d|ƒ‚dS)zAIs the error actually a timeout? Will raise a ReadTimeout or passz!Read timed out. (read timeout=%s)Úerrnoz timed outzdid not complete (read)N)rIÚ SocketTimeoutrÚhasattrrqÚ_blocking_errnosÚstr)r2ÚerrÚurlÚ timeout_valuer3r3r4Ú_raise_timeoutLs z!HTTPConnectionPool._raise_timeoutc Ksn|jd7_| |¡}| ¡|j|_y| |¡Wn:ttfk rp}z|j|||jd�‚Wdd}~XYnXy*|rŠ|j ||f|Žn|j ||f|ŽWnLt k r°Yn:t k rè}z|j t jt jt jhkrØ‚Wdd}~XYnX|j} t|ddƒ�rB| dk�rt||d| ƒ‚| tjk�r6|j t ¡¡n |j | ¡yjy|jdd�} WnTtk �r¨y | ¡} Wn0tk �r¢}zt |d¡Wdd}~XYnXYnXWn<tttfk �rè}z|j||| d�‚Wdd}~XYnXt|d d ƒ} t  !d |j"|j#|j$||| | j%| j&¡ yt'| j(ƒWn@t)tfk �rh} zt j*d | +|¡| dd �Wdd} ~ XYnX| S)a Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. r)rvrwrxNÚsockrz!Read timed out. (read timeout=%s)T)Ú bufferingÚ _http_vsn_strzHTTP/?z%s://%s:%s "%s %s %s" %s %sz$Failed to parse headers (url=%s): %s)Úexc_info),rSrpÚ start_connectr`rrlrrrryÚrequest_chunkedÚrequestrÚIOErrorrqÚEPIPEÚ ESHUTDOWNÚ EPROTOTYPEÚ read_timeoutrgrr&ÚDEFAULT_TIMEOUTrzÚ settimeoutÚsocketÚgetdefaulttimeoutÚ getresponseÚ TypeErrorÚ BaseExceptionrÚ raise_fromÚ SocketErrorr]r^r-r.r1ÚstatusÚlengthr$ÚmsgrrjÚ _absolute_url) r2raÚmethodrwrÚchunkedÚhttplib_request_kwÚ timeout_objÚer…Úhttplib_responseÚ http_versionÚhper3r3r4Ú _make_requestesx      ( z HTTPConnectionPool._make_requestcCst|j|j|j|d�jS)N)r-r.r1Úpath)r'r-r.r1rw)r2rœr3r3r4r’Üsz HTTPConnectionPool._absolute_urlcCsZ|jdkrdS|jd}|_y"x|jdd�}|r | ¡q WWntjk rTYnXdS)zD Close all pooled connections and disable the pool. NF)rN)rMrdr:rrf)r2Úold_poolrar3r3r4r:ßs  zHTTPConnectionPool.closecCsx| d¡rdSt|ƒ\}}}|dk r0t||d�}|jrF|sFt |¡}n|js^|t |¡kr^d}|||f|j|j|jfkS)zj Check if the given ``url`` is a member of the same host as this connection pool. ú/TN)r-)Ú startswithr*r)r1r rdr-r.)r2rwr-r.r1r3r3r4Ú is_same_hostñs    zHTTPConnectionPool.is_same_hostTc Kst|ƒ}|j}|dkr|j}t|tƒs8tj|||jd�}| dkrL|  dd¡} |rf| |¡sft |||ƒ‚|  d¡r€t   t |ƒ¡}n t   |j¡}d}| }t|j|j|ƒ}|s¼| ¡}| |j¡d}d}t|| ƒ} �zzy | |¡}|j| d�}|j|_|jdk �o t|ddƒ }|�r"|�r"| |¡|j||||||| d �}| �sD|nd}|| d <|jj|f|||d œ| —Ž}d}WnÔtk �r’d}d}‚Yn¶t t!t"t#t$t%t&fk �rF}zˆd}t|t$t&fƒ�rÐt%|ƒ}n>t|t"t'fƒ�rô|j�rôt(d |ƒ}nt|t"t!fƒ�rt#d |ƒ}|j)||||t* +¡dd�}| ,¡|}Wdd}~XYnXWd|�sd|�o^| -¡}d}|�rt| .|¡X|�s¶t/ 0d|||¡|j1|||||||f|| | | | dœ| —ŽS|�oÂ| 2¡}|�rd|j3dk�rÚd}y|j)||||d�}Wn(t4k �r|j5�r| 6¡‚|SX| 6¡| 7|¡t/ 8d||¡|j1||||f||||| | | | dœ| —ŽSt9| :d¡ƒ}| ;||j3|¡�r y|j)||||d�}Wn(t4k �rÂ|j<�r¾| 6¡‚|SX| 6¡| ,|¡t/ 8d|¡|j1||||f||||| | | | dœ| —ŽS|S)a+ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param url: The URL to perform the request on. :param body: Data to send in the request body, either :class:`str`, :class:`bytes`, an iterable of :class:`str`/:class:`bytes`, or a file-like object. :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When ``False``, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` N)ÚredirectÚdefaultÚpreload_contentTržF)rrz)rÚbodyrWr”Úrequest_method)rMÚ connectionrLzCannot connect to proxy.zConnection aborted.é)rÚ_poolÚ _stacktracez1Retrying (%r) after connection broken by '%r': %s)rÚ pool_timeoutÚ release_connr”Úbody_posi/ÚGET)Úresponser¨zRedirecting %s -> %s)rLr¡Úassert_same_hostrrªr«r”r¬z Retry-Afterz Retry: %s)=r+r-rWrIr%Úfrom_intrLrdr rrŸrÚ ensure_strr(rwr!rFrGÚcopyÚupdaterOr#rprhr`rrgrmr›Ú ResponseClsÚ from_httplibrrr rŽrrrrrrÚ incrementÚsysr}Úsleepr:rkr]rjÚurlopenÚget_redirect_locationr�rÚraise_on_redirectÚ drain_connÚsleep_for_retryr^ÚboolÚ getheaderÚis_retryÚraise_on_status)r2r“rwr¤rWrLr¡r¯rrªr«r”r¬Ú response_kwÚ parsed_urlÚdestination_schemeraÚrelease_this_connÚhttp_tunnel_requiredrvÚ clean_exitr–Úis_new_proxy_connr˜Ú response_connr®r—Úredirect_locationÚhas_retry_afterr3r3r4r¹s(m                      zHTTPConnectionPool.urlopen)N)r7r?r@rAr-r r_rr´r&r†r5rbrhrkrlrmrpryrnr›r’r:r r¹r3r3r3r4rChsF: * ' vrCcspeZdZdZdZeZddejdddddddddddddddfdd„Z dd „Z d d „Z d d „Z ‡fdd„Z ‡ZS)ÚHTTPSConnectionPoola Same as :class:`.HTTPConnectionPool`, but HTTPS. :class:`.HTTPSConnection` uses one of ``assert_fingerprint``, ``assert_hostname`` and ``host`` in this order to verify connections. If ``assert_hostname`` is False, no verification is done. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl` is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket into an SSL socket. ÚhttpsNFrc Ks\tj|||||||||| | f |Ž| |_| |_| |_||_||_||_||_||_ ||_ dS)N) rCr5Úkey_fileÚ cert_fileÚ cert_reqsÚ key_passwordÚca_certsÚ ca_cert_dirÚ ssl_versionÚassert_hostnameÚassert_fingerprint)r2r.r1rHrrVrNrWrLrXrYrÎrÏrÐrÑrÒrÔrÕrÖrÓrTr3r3r4r5rs,zHTTPSConnectionPool.__init__c Cs@t|tƒr<|j|j|j|j|j|j|j|j |j d�|j |_ |S)zˆ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used. )rÎrÑrÏrÐrÒrÓrÕrÖ) rIr Úset_certrÎrÑrÏrÐrÒrÓrÕrÖrÔ)r2rar3r3r4Ú _prepare_conn£s  z!HTTPSConnectionPool._prepare_conncCs2| |j|j|j¡|jjdkr&d|_| ¡dS)zÏ Establishes a tunnel connection through HTTP CONNECT. Tunnel connection is established early because otherwise httplib would improperly set Host: header to proxy's IP:port. rÍTN)Ú set_tunnelr0r1rOrFr-Útls_in_tls_requiredÚconnect)r2rar3r3r4rm·s z"HTTPSConnectionPool._prepare_proxyc Csž|jd7_t d|j|j|jp$d¡|jr8|jtkr@tdƒ‚|j}|j}|jdk rf|jj}|jj}|jf|||j j |j |j |j |jdœ|j—Ž}| |¡S)zF Return a fresh :class:`http.client.HTTPSConnection`. rz)Starting new HTTPS connection (%d): %s:%sÚ443zCCan't connect to HTTPS URL because the SSL module is not available.N)r.r1rrHrÏrÎrÑ)rRr]r^r.r1r_rrrFrr`rHrÏrÎrÑrTrØ)r2Ú actual_hostÚ actual_portrar3r3r4rbÆs0   zHTTPSConnectionPool._new_conncs@tt|ƒ |¡t|ddƒs$| ¡|js>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') éPrÍr1N)r*r rdrÌrC)rwÚkwr-r.r1r3r3r4Úconnection_from_urls rçcCs.t||ƒ}| d¡r*| d¡r*|dd…}|S)z? Normalize hosts for comparisons and use with sockets. ú[ú]réÿÿÿÿ)Únormalize_hostrŸÚendswith)r.r-r3r3r4r)s  r))OÚ __future__rrqÚloggingrˆr·rárrŽrrrr¦rrrr r r r r Ú exceptionsrrrrrrrrrrrrrÚpackagesrZpackages.six.movesrZpackages.ssl_match_hostnamerr€rr®rZutil.connectionr Z util.proxyr!Z util.queuer"Z util.requestr#Z util.responser$Z util.retryr%Z util.timeoutr&Zutil.urlr'r(r)rër*r+ÚmovesrPÚ getLoggerr7r]Úobjectrnr,ÚEAGAINÚ EWOULDBLOCKrtrCrÌrçr3r3r3r4ÚsN   ( <              ) ~