3 »nNjÂ�ã@s²ddlmZddlZddlZddlZddlZddlmZm Z ddlZddl m Z m Z mZmZmZmZmZmZmZmZmZmZmZddlmZddlmZddlmZdd lm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&dd l'm(Z(dd l)m*Z*dd l+m,Z,dd l-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:ddl;mZ>ej?e@ƒZAeBƒZCGdd„deBƒZDejEejFhZGGdd„deDe*ƒZHGdd„deHƒZIdd„ZJdd„ZKdS)é)Úabsolute_importN)ÚerrorÚtimeouté) ÚClosedPoolErrorÚ ProtocolErrorÚEmptyPoolErrorÚHeaderParsingErrorÚHostChangedErrorÚLocationValueErrorÚ MaxRetryErrorÚ ProxyErrorÚReadTimeoutErrorÚSSLErrorÚ TimeoutErrorÚInsecureRequestWarningÚNewConnectionError)ÚCertificateError)Úsix)Úqueue)Úport_by_schemeÚDummyConnectionÚHTTPConnectionÚHTTPSConnectionÚVerifiedHTTPSConnectionÚ HTTPExceptionÚ BaseSSLError)ÚHTTPHeaderDict)ÚRequestMethods)Ú HTTPResponse)Úis_connection_dropped)Úset_file_position)Úassert_header_parsing)ÚRetry)ÚTimeout)Úget_hostÚUrlÚNORMALIZABLE_SCHEMES)Ú LifoQueuec@sBeZdZdZdZeZd dd„Zdd„Zdd„Z d d „Z d d „Z dS)ÚConnectionPoolzz Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. NcCs.|s tdƒ‚t||jƒ|_|jƒ|_||_dS)NzNo host specified.)r Ú _ipv6_hostÚschemeÚhostÚlowerÚ _proxy_hostÚport)Úselfr,r/©r1ú$/usr/lib/python3.6/connectionpool.pyÚ__init__As  zConnectionPool.__init__cCsdt|ƒj|j|jfS)Nz%s(host=%r, port=%r))ÚtypeÚ__name__r,r/)r0r1r1r2Ú__str__Is zConnectionPool.__str__cCs|S)Nr1)r0r1r1r2Ú __enter__MszConnectionPool.__enter__cCs |jƒdS)NF)Úclose)r0Úexc_typeZexc_valZexc_tbr1r1r2Ú__exit__PszConnectionPool.__exit__cCsdS)zD Close all pooled connections and disable the pool. Nr1)r0r1r1r2r8UszConnectionPool.close)N) r5Ú __module__Ú __qualname__Ú__doc__r+r(ÚQueueClsr3r6r7r:r8r1r1r1r2r)8s r)c @s¸eZdZdZdZeZeZdde j ddddddf dd„Z dd „Z d!d d „Z d d „Zdd„Zdd„Zdd„Zdd„Zedfdd„Zdd„Zdd„Zdd„Zdddddeddddf dd „ZdS)"ÚHTTPConnectionPoolaN Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`httplib.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`httplib.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:`httplib.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.connectionpool.ProxyManager`" :param _proxy_headers: A dictionary with proxy headers, should not be used directly, instead, see :class:`urllib3.connectionpool.ProxyManager`" :param \**conn_kw: Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, :class:`urllib3.connection.HTTPSConnection` instances. ÚhttpNFrc Ks¸tj|||ƒtj||ƒ||_t|tƒs4tj|ƒ}|dkrBtj}||_ ||_ |j |ƒ|_ ||_ | |_| pli|_xt|ƒD]} |j jdƒqzWd|_d|_| |_|jr´|jjdgƒdS)NrZsocket_options)r)r3rÚstrictÚ isinstancer$Ú from_floatr#ZDEFAULTrÚretriesr>ÚpoolÚblockÚproxyÚ proxy_headersÚxrangeÚputÚnum_connectionsÚ num_requestsÚconn_kwÚ setdefault) r0r,r/rArÚmaxsizerFÚheadersrDÚ_proxyÚ_proxy_headersrMÚ_r1r1r2r3 s(     zHTTPConnectionPool.__init__cCsR|jd7_tjd|j|j|jp$dƒ|jf|j|j|jj|jdœ|j —Ž}|S)z9 Return a fresh :class:`HTTPConnection`. rz(Starting new HTTP connection (%d): %s:%sZ80)r,r/rrA) rKÚlogÚdebugr,r/Ú ConnectionClsrÚconnect_timeoutrArM)r0Úconnr1r1r2Ú _new_connÈszHTTPConnectionPool._new_connc Cs d}y|jj|j|d�}WnBtk r8t|dƒ‚Yn&tjk r\|jrXt|dƒ‚YnX|r”t|ƒr”t j d|j ƒ|j ƒt |ddƒdkr”d}|pž|jƒ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)rFrzPool is closed.z>Pool reached maximum size and no more connections are allowed.z Resetting dropped connection: %sZ auto_openrr)rEÚgetrFÚAttributeErrorrrÚEmptyrr rTrUr,r8ÚgetattrrY)r0rrXr1r1r2Ú _get_connÕs  zHTTPConnectionPool._get_connc Cs\y|jj|dd�dStk r(Yn$tjk rJtjd|jƒYnX|rX|jƒ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)rFNz2Connection pool is full, discarding connection: %s) rErJr[rZFullrTÚwarningr,r8)r0rXr1r1r2Ú _put_connûszHTTPConnectionPool._put_conncCsdS)zU Called right before a request is made, after the socket is created. Nr1)r0rXr1r1r2Ú_validate_connsz!HTTPConnectionPool._validate_conncCsdS)Nr1)r0rXr1r1r2Ú_prepare_proxysz!HTTPConnectionPool._prepare_proxycCs2|tkr|jjƒSt|tƒr$|jƒStj|ƒSdS)z< Helper that always returns a :class:`urllib3.util.Timeout` N)Ú_DefaultrZclonerBr$rC)r0rr1r1r2Ú _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)rBÚ SocketTimeoutrÚhasattrreÚ_blocking_errnosÚstr)r0ÚerrÚurlÚ timeout_valuer1r1r2Ú_raise_timeout/s  z!HTTPConnectionPool._raise_timeoutc :Ks|jd7_|j|ƒ}|jƒ|j|_y|j|ƒWn:ttfk rp}z|j|||jd�‚WYdd}~XnX|rˆ|j ||f|Žn|j ||f|Ž|j } t |ddƒrê| dkrÂt ||d| ƒ‚| tjkrÞ|jjtjƒƒn |jj| ƒyjy|jdd�} WnTtk �rPy |jƒ} Wn0tk �rJ}ztj|dƒWYdd}~XnXYnXWn<tttfk �r�}z|j||| d�‚WYdd}~XnXt |d d ƒ} tjd |j|j|j||| | j| j ƒ yt!| j"ƒWn@t#tfk �r} ztj$d |j%|ƒ| dd �WYdd} ~ XnX| 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)rjrkrlNÚsockrz!Read timed out. (read timeout=%s)T)Ú bufferingZ _http_vsn_strzHTTP/?z%s://%s:%s "%s %s %s" %s %sz$Failed to parse headers (url=%s): %s)Úexc_info)&rLrdZ start_connectrWrrarfrrmZrequest_chunkedÚrequestÚ read_timeoutr]rr$ÚDEFAULT_TIMEOUTrnZ settimeoutÚsocketZgetdefaulttimeoutZ getresponseÚ TypeErrorÚ ExceptionrZ raise_fromÚ SocketErrorrTrUr+r,r/ÚstatusZlengthr"Úmsgr r_Ú _absolute_url) r0rXÚmethodrkrÚchunkedZhttplib_request_kwÚ timeout_objÚerrÚhttplib_responseZ http_versionZhper1r1r2Ú _make_request@sT     (  $z HTTPConnectionPool._make_requestcCst|j|j|j|d�jS)N)r+r,r/Úpath)r&r+r,r/rk)r0r�r1r1r2rz•sz HTTPConnectionPool._absolute_urlc CsZ|jdkrdS|jd}|_y"x|jdd�}|r |jƒq WWntjk rTYnXdS)zD Close all pooled connections and disable the pool. NF)rF)rErZr8rr\)r0Zold_poolrXr1r1r2r8˜s  zHTTPConnectionPool.closecCst|jdƒrdSt|ƒ\}}}t||jƒ}|jr@| r@tj|ƒ}n|j rZ|tj|ƒkrZd}|||f|j|j|jfkS)zj Check if the given ``url`` is a member of the same host as this connection pool. ú/TN)Ú startswithr%r*r+r/rrZr,)r0rkr+r,r/r1r1r2Ú is_same_hostªs    zHTTPConnectionPool.is_same_hostTc .KsD|dkr|j}t|tƒs*tj|||jd�}| dkr>| jddƒ} |rZ|j|ƒ rZt|||ƒ‚d}| }|jdkr€|j ƒ}|j |j ƒd}d}t || ƒ} �zry–|j |ƒ}|j| d�}|j|_|jdk oÌt|ddƒ }|rÜ|j|ƒ|j||||||| d �}| �sþ|nd}|| d <|jj|f|||d œ| —Ž}d}WnÖtjk �rNt|d ƒ‚Yn¶ttttttt fk �r}zŠd}t|tt fƒ�rŒt|ƒ}n>t|tt!fƒ�r°|j�r°t"d |ƒ}nt|ttfƒ�rÊtd|ƒ}|j#||||t$j%ƒdd�}|j&ƒ|}WYdd}~XnXWd|�s |�o|j'ƒ}d}|�r0|j(|ƒX|�spt)j*d|||ƒ|j+|||||||f|| | | dœ| —ŽSdd„}|�o„|j,ƒ}|�rš|j-dk�r¬d}d}t.|ƒj/ƒ}|j0�r|j|ƒ �rt|t.ƒ�sÜt.|�pØiƒ}x4t1t2j3|ƒƒD]"}|j4ƒ|j0k�rì|j5|dƒ�qìWy|j#||||d�}Wn(t6k �rP|j7�rL||ƒ‚|SX||ƒ|j8|ƒt)j9d||ƒ|j+||||f||||| | | dœ| —ŽSt:|j;dƒƒ}|j<||j-|ƒ�r@y|j#||||d�}Wn(t6k �rø|j=�rô||ƒ‚|SX||ƒ|j&|ƒt)j9d|ƒ|j+||||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 body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :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ÚdefaultZpreload_contentTr@F)rrn)rÚbodyrPr|Zrequest_method)rEÚ connectionrDz"No pool connections are available.zCannot connect to proxy.zConnection aborted.é)rÚ_poolZ _stacktracez1Retrying (%r) after connection broken by '%r': %s)rÚ pool_timeoutÚ release_connÚbody_poscSsFy|j|jd�Wn.ttttttfk r@}zWYdd}~XnXdS)N)Zdecode_content)ÚreadZ_has_decoded_contentrrrwrrr)Úresponser~r1r1r2Údrain_and_release_connžs  z:HTTPConnectionPool.urlopen..drain_and_release_conni/ZGET)r�rŠzRedirecting %s -> %s)rDr…Úassert_same_hostrr‹rŒr�z Retry-Afterz Retry: %s)>rPrBr#Zfrom_intrDrZr„r r+ÚcopyÚupdaterHr!rdr^rWrrGr]rbr€Ú ResponseClsZ from_httplibrr\rrrrwrrrrrr Z incrementÚsysrpZsleepr8r`rTr_ÚurlopenZget_redirect_locationrxrZ_prepare_for_method_changeZremove_headers_on_redirectÚlistrZiterkeysr-Úpopr Zraise_on_redirectZsleep_for_retryrUÚboolZ getheaderZis_retryZraise_on_status)r0r{rkr‡rPrDr…r‘rr‹rŒr|r�Z response_kwrXZrelease_this_connrjZ clean_exitr}Zis_new_proxy_connrZ response_connr�r~r�Zredirect_locationÚheaderZhas_retry_afterr1r1r2r–¿sä^                           zHTTPConnectionPool.urlopen)N)r5r;r<r=r+rrVrr”r$rsr3rYr^r`rarbrdrmrcr€rzr8r„r–r1r1r1r2r?`s.:% & Ur?csneZdZdZdZeZddejddddddddddddddfdd„Z dd „Z d d „Z d d „Z ‡fdd„Z ‡ZS)ÚHTTPSConnectionPoolaÍ Same as :class:`.HTTPConnectionPool`, but HTTPS. When Python is compiled with the :mod:`ssl` module, then :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates, instead of :class:`.HTTPSConnection`. :class:`.VerifiedHTTPSConnection` 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``, and ``ssl_version`` 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 Ksftj|||||||||| | f |Ž|r2| dkr2d} | |_| |_| |_||_||_||_||_||_ dS)NZ CERT_REQUIRED) r?r3Úkey_fileÚ cert_fileÚ cert_reqsÚca_certsÚ ca_cert_dirÚ ssl_versionÚassert_hostnameÚassert_fingerprint)r0r,r/rArrOrFrPrDrQrRr�ržrŸr r¢r£r¤r¡rMr1r1r2r3 s   zHTTPSConnectionPool.__init__c Cs<t|tƒr8|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¤) rBrZset_certr�ržrŸr r¡r£r¤r¢)r0rXr1r1r2Ú _prepare_conn"s  z!HTTPSConnectionPool._prepare_conncCs |j|j|j|jƒ|jƒdS)zŒ Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port. N)Z set_tunnelr.r/rHÚconnect)r0rXr1r1r2rb3sz"HTTPSConnectionPool._prepare_proxycCs”|jd7_tjd|j|j|jp$dƒ|j s:|jtkrBtdƒ‚|j}|j}|jdk rh|jj}|jj}|jf|||j j |j dœ|j —Ž}|j |ƒS)zB Return a fresh :class:`httplib.HTTPSConnection`. rz)Starting new HTTPS connection (%d): %s:%sZ443zCCan't connect to HTTPS URL because the SSL module is not available.N)r,r/rrA)rKrTrUr,r/rVrrrGrrWrArMr¥)r0Z actual_hostZ actual_portrXr1r1r2rY;s  zHTTPSConnectionPool._new_conncs:tt|ƒj|ƒt|ddƒs$|jƒ|js6tjdtƒdS)zU Called right before a request is made, after the socket is created. rnNz«Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings) Úsuperr›rar]r¦Z is_verifiedÚwarningsÚwarnr)r0rX)Ú __class__r1r2raSs z"HTTPSConnectionPool._validate_conn)r5r;r<r=r+rrVr$rsr3r¥rbrYraÚ __classcell__r1r1)rªr2r›ôs r›cKsRt|ƒ\}}}|ptj|dƒ}|dkr:t|fd|i|—ŽSt|fd|i|—ŽSdS)a€ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example:: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') éPrœr/N)r%rrZr›r?)rkÚkwr+r,r/r1r1r2Úconnection_from_urlfs r®cCs:|jdƒr&|jdƒr&|jddƒjdƒ}|tkr6|jƒ}|S)z' Process IPv6 address literals ú[ú]z%25ú%z[])rƒÚendswithÚreplaceÚstripr'r-)r,r+r1r1r2r*‚s r*)LZ __future__rreZloggingr•r¨rtrrwrrfÚ exceptionsrrrr r r r r rrrrrZpackages.ssl_match_hostnamerZpackagesrZpackages.six.movesrrˆrrrrrrrÚ _collectionsrrqrr�rZutil.connectionr Z util.requestr!Z util.responser"Z util.retryr#Z util.timeoutr$Zutil.urlr%r&r'Z util.queuer(ZmovesrIZ getLoggerr5rTÚobjectrcr)ZEAGAINZ EWOULDBLOCKrhr?r›r®r*r1r1r1r2ÚsF <   $          % r