{fddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlmZddlmZddlmZdd lmZmZmZmZmZmZmZmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+dd l,m-Z-dd l.m/Z/ddl0m1Z1ddl2m3Z3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:m;Z;mZ>m?Z?ddl=m@ZAddl=mBZBddlCmDZDejrddlFZFddlGmHZHddlmIZImJZJejeLZMejes r?__str__zConnectionPool.__str__^s.t*%%&fTYYM QOOrAc|SNrFs r? __enter__zConnectionPool.__enter__as rAc$|jy)NF)close)r>exc_typeexc_valexc_tbs r?__exit__zConnectionPool.__exit__ds rAcyzD Close all pooled connections and disable the pool. NrJrFs r?rMzConnectionPool.closenrArI)r9strr: int | NonereturnNone)rWrU)rWr0)rNztype[BaseException] | NonerOzBaseException | NonerPzTracebackType | NonerWztyping.Literal[False]rWrX)rE __module__ __qualname____doc__r6__annotations__queue LifoQueueQueueClsr@rGrKrQrMrJrAr?r4r4Cs]FJH MP,&%    rAr4c reZdZUdZdZeZded<dedddddddf ddZ dd Z ddd Z dd Z dd Z dd ZddZ ddZdddedddddf ddZddZddZdddddeddddddf d dZy)!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 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. httpz4type[BaseHTTPConnection] | type[BaseHTTPSConnection] ConnectionClsNrFc  tj|||tj||t|tst j |}|t j}||_||_ |j||_ ||_ ||_ | xsi|_| |_t!|D]} |jj#dd|_d|_| |_|jrN|j(j+dg|j|j(d<|j|j(d<|j} t-j.|t0| y)Nrsocket_optionsproxy proxy_config)r4r@r isinstancer* from_floatr&DEFAULTrretriesr`poolblockrg proxy_headersrhrangeputnum_connections num_requestsconn_kw setdefaultweakreffinalize_close_pool_connections)r>r9r:rmaxsizernheadersrl_proxy_proxy_headers _proxy_configrt_rms r?r@zHTTPConnectionPool.__init__s, dD1g.'7+((1G ?mmG  8< g8N   +1r)wA IIMM$   ! :: LL # #$4b 9$(JJDLL !+/+<+conns r? _new_connzHTTPConnectionPool._new_conns ! 6  II II   "t!! LL00 ll    rAcd}|j t|d |jj|j|}|r;t|r0tjd|j|j|xs|jS#t$rt|ddt j $r|jr t|ddYwxYw)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``. NzPool is closed.)rnrzHPool is empty and a new connection can't be opened due to blocking mode.z Resetting dropped connection: %s)rmrgetrnAttributeErrorr^Emptyrr"rrr9rMr)r>rrs r? _get_connzHTTPConnectionPool._get_conns 99 !$(9: : 99==tzz7=CD )$/ II8$)) D JJL't~~''! E!$(9: D{{ zz$^   s'BACCc|j |jj|dy|r|j yy#t$rYtj$rg|r|j |j r t|ddtjd|j|jjYwxYw)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. NFrnz>Pool reached maximum size and no more connections are allowed.zLConnection pool is full, discarding connection: %s. Connection pool size: %s) rmrqrr^FullrMrnrrwarningr9qsizers r? _put_connzHTTPConnectionPool._put_conn(s 99   d% 0.  JJL -" :: JJL::'X   bIIIIOO% sA C A6CCcy)U Called right before a request is made, after the socket is created. NrJrs r?_validate_connz!HTTPConnectionPool._validate_connSrTrAcyrIrJrs r?_prepare_proxyz!HTTPConnectionPool._prepare_proxyXs rAc|tur|jjSt|tr|jSt j |S)z:Helper that always returns a :class:`urllib3.util.Timeout`)r(rclonerir*rj)r>rs r? _get_timeoutzHTTPConnectionPool._get_timeout\sG & &<<%%' ' gw '==? "%%g. .rAct|trt||d|d|t|dr%|jt vrt||d|d|yy)zAIs the error actually a timeout? Will raise a ReadTimeout or passRead timed out. (read timeout=rCerrnoN)ri SocketTimeoutrhasattrr_blocking_errnos)r>errurl timeout_values r?_raise_timeoutz!HTTPConnectionPool._raise_timeouthsq c= )"c;M?!L  3 SYY2B%B"c;M?!L &C rATc P|xjdz c_|j|} | jtj| j |_ |j| |j+|||||| | | | j4}|j6s|dk(rt9||d|d||_ |j;}||_| |_||_ tBjEd|j(|jF|jH|||jJ|jL|jN |S#ttf$r$}|j|||j d}~wwxYw#ttttttf$r}|}t!|ttfr t|}t!|ttttfr:|r8|j"r,|j$s t'||j"j(}|d}~wwxYw#t,$rYt$rF}|j.t.j0k7r|j.t.j2k7rYd}~d}~wwxYw#ttf$r}|j|||d}~wwxYw) a8 Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :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 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 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 response_conn: Set this to ``None`` if you will handle releasing the connection or set the connection to have the response release it. :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param enforce_content_length: Enforce content length checking. Body returned by server must match value of Content-Length header, if present. Otherwise, raise error. rrrrN)bodyrzchunkedpreload_contentdecode_contentenforce_content_lengthrrrCz %s://%s:%s "%s %s HTTP/%s" %s %s)(rsr start_connectr*resolve_default_timeoutrrrrr rOSErrorrr r'rrirghas_connected_to_proxyrr6requestr r EPROTOTYPE ECONNRESET read_timeout is_closedr getresponserl _connection_poolrrr9r:versionstatuslength_remaining)r>rmethodrrrzrlrr response_connrrr timeout_objenew_erresponses r? _make_requestz HTTPConnectionPool._make_request{s}\ Q''0 !!#66{7R7RS   ##D)8  LL /-'=  2#// ~~ q &#!? ~QO(DL '')H #, . KK II II      OO  % % w"<0 ##s$,,#O           !E!l,<=>  !3\8LDJJt/J/J)%1B1BCK# H    ww%***qww%:J:J/J  4g&    A3l  K  sgD?0H?I<?E2E--E22E55#HA?HH I9+I93;I44I9<J% J  J%c\|jy|jdc}|_t|yrS)rmrx)r>old_pools r?rMzHTTPConnectionPool.close0s- 99  "ii$) )rAcV|jdryt|^}}}}}|xsd}| t||}|jr|st j |}n&|js|t j |k(rd}|||f|j |j|jfk(S)zj Check if the given ``url`` is a member of the same host as this connection pool. /TrcNr8) startswithr.r-r:rrr6r9)r>rr6r~r9r:s r? is_same_hostzHTTPConnectionPool.is_same_host<s >># %.cN!4!6  "47D 99T!%%f-Dt~'9'9&'AADd# TYY 'JJJrAc  t|}|j}| |j}t|ts"t j |||j }| | } |r|j|s t||||jdrtt|}nt|j}d}| }t|j|j|}|s+|j!}|j#|j$d}d}t'|| } |j)|}|j+| }|j,|_|j |r|j0r |j3|| s|nd}|j<|||f|||| ||| |d|}d}|s|r|j[d}d}|r|j]| |s9t^jad ||||jb|||||||f|| | | | | |d |S|xrje}|rjfdk(rd}d}ti|jk} |jS||||}|jq|js|t^jud|||jb||||f||||| | | | | |d |Stwjjyd}|j{||jf|rn |jS||||}|jq|jY|t^jud||jb||||f||||| | | | | |d |S|S#t4t6t8f$r8}|j;||jj|j.d}~wwxYw#t>$rd}d}t@tBt6tDt4tFtHtJf$r}d}|}t|t4tHfr tG|}t|t6tLt@tFtBfr;|r9|jr-|jNs!tQ||jj}n"t|t6tBfr tEd |}|jS||||tUjVd  }|jY|}Yd}~ %s) rlrassert_same_hostrrrrrrrz Retry-Afterz Retry: %s)?r.r6rzrir&from_intrlrrrr/r,rr#rgrhcopyupdateror%rrrrrrr rrrrrr rrrr'rrrr incrementsysexc_infosleeprMrrrurlopenget_redirect_locationrr _prepare_for_method_changerraise_on_redirect drain_connsleep_for_retryrboolris_retryraise_on_status)r>rrrrzrlrrrrrrrrr response_kw parsed_urldestination_schemerrelease_this_connhttp_tunnel_requiredr clean_exitrrrrrredirect_locationhas_retry_afters r?rzHTTPConnectionPool.urlopenRsbs^ '.. ?llG'5)nnWxVG  *L D$5$5c$:"4g6 6 >># ,-C(C)> JJ))+= $llnG NN4-- . %T84e %++G4K>>,>7D&66DLzz%*>4>>''-)5D$M*t)) $+ /-  H J^ JJLD$(! t$ KKCWcSV  4<<  ))! /- &%I)G)G)I #%(1LLN !++FC(RV+W    !  # #H - II,c3D E4<<!   !!1))! /- &x//33MBC   FHOO_ E !++FC(RV+W    ! MM( # IIk3 '4<<   !!1))! /- $u%g}=''4::>>( > J %            $ J E!l,<=>  & !  DJJt/J/J)%1B1BCEG]#;<%&;UC''5#,,.QRBS(G MMOCI$ N JJLD$(! t$ !R! ,,'')  @! **'')  stAN8)M):&N8 T:U)N5=3N00N55N88:S!2C$SS$S!!S$$.T(U?U(U.-U.)r9rUr:rVr_TYPE_TIMEOUT | Noneryintrnrrztyping.Mapping[str, str] | NonerlRetry | bool | int | Noner{ Url | Noner|rr}zProxyConfig | Nonert typing.Any)rWr1rI)rz float | NonerWr1)rBaseHTTPConnection | NonerWrXrr1rWrX)r _TYPE_TIMEOUTrWr*)rz&BaseSSLError | OSError | SocketTimeoutrrUrrrWrX)rr1rrUrrUr_TYPE_BODY | Nonerzrrlz Retry | NonerrrrrrrrrrrrrWr!rY)rrUrWr) rrUrrUrrrzrrlrrrrrrrrrVrz bool | Nonerrrz_TYPE_BODY_POSITION | NonerrrrrrrWr!)rErZr[r\r6rrdr]r(r@rrrrrrrrrMrrrJrAr?rbrbxs1fF < (837-1!:>,0;>;>;>& ;>  ;>  ;>1;>+;>;>8;>*;>;>z($(L)V   / 3,   0#'37 $!137 $#'+s ss s  s 1 ssss1sss!%s sj *K4#'37-1!%!1#'$(/3 $#ppp p 1 p + pppp!p"pp-ppp "!p" #prArbceZdZUdZdZeZded<dedddddddddddddddddf d fd Z d d Z dd Z dfd Z xZ S)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. httpsztype[BaseHTTPSConnection]rdNrFc t|||||||||| f i|| |_| |_| |_| |_||_||_||_||_ ||_ ||_ ||_ yrI) superr@key_file cert_file cert_reqs key_passwordca_certs ca_cert_dir ssl_versionssl_minimum_versionssl_maximum_versionassert_hostnameassert_fingerprint)r>r9r:rryrnrzrlr{r|rrrrrrrrrrrrt __class__s r?r@zHTTPSConnectionPool.__init__s0            ! ""(  &&#6 #6 ."4rAc|jr|jjdk(rd}nd}|j||j|j|j |j y)z5Establishes a tunnel connection through HTTP CONNECT.rrc)r6r9r:rzN)rgr6 set_tunnelr=r:roconnect)r>r tunnel_schemes r?rz"HTTPSConnectionPool._prepare_proxys\ ::$**++w6#M"M  ""&&  rAc|xjdz c_tjd|j|j|jxsd|j r|j t ur td|j}|j}|jB|jj,|jj}|jj}|j d|||jj|j|j|j|j|j|j |j"|j$|j&|j(|j*d|j,S)zL Return a fresh :class:`urllib3.connection.HTTPConnection`. rz)Starting new HTTPS connection (%d): %s:%s443zCCan't connect to HTTPS URL because the SSL module is not available.)r9r:rrrrrrrrrrrrrJ)rrrrr9r:rdr ImportErrorrgrrrrrrrrrrrrrrt)r> actual_host actual_ports r?rzHTTPSConnectionPool._new_connsC ! 7  II II   !!T%7%7?%JU  99 ii :: !djjoo&A**//K**//K!t!! LL00nn]]**nn]](( 00#66(( $ 8 8 $ 8 8 ll  rAct|||jr|j|js6|j s)t jd|jdtyyy)rz0Unverified HTTPS request is being made to host 'z'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warningsN) rrrr is_verifiedproxy_is_verifiedwarningswarnr9r)r>rrs r?rz"HTTPSConnectionPool._validate_conn?sf t$ >> LLN(>(> MMFtyykR$$ ' )?rA),r9rUr:rVrrryrrnrrzrrlrr{rr|rrr5rr5rint | str | Nonerr5rr5rrrssl.TLSVersion | Nonerrrz"str | typing.Literal[False] | Nonerr5rr5rtrrWrX)rrrWrX)rWr2r)rErZr[r\r6rrdr]r(r@rrr __classcell__)rs@r?rrsJ F/>M,>  (837-1!:># $&*#'#(,5959>B)-"&+/5/5/5& /5  /5  /51/5+/5/58/5/5/5$/5!/5/5 &!/5"3#/5$3%/5&<'/5(')/5* +/5,-/5. //5b ' RrArc t|^}}}}}|xsd}|xstj|d}|dk(rt|fd|i|St |fd|i|S)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', '/') rcPrr:)r.rrrrb)rkwr6r~r9r:s r?connection_from_urlrVsk(!*#FAtTA  vF  1>%%fb1D "49d9b99!$8T8R88rAcyrIrJr9r6s r?r-r-srAcyrIrJrs r?r-r-xrrAcpt||}|r'|jdr|jdr|dd}|S)z? Normalize hosts for comparisons and use with sockets. []r)r;rendswithrs r?r-r-}s; $ 'D $s);Abz KrAcpt|j|j|j|jS)zZReturns the URL from a given connection pool. This is mainly used for testing and logging.)r6r9r:path)r+r6r9r:r)rmr$s r?_url_from_poolr%s' dkk   M Q QQrAc |jd}|r|j%#tj$rYywxYw)z2Drains a queue of connections and closes each one.FrN)rrMr^r)rmrs r?rxrxsC 88%8(D  ;;   s &(>>)rrUrrrWrb)r9rXr6r5rWrX)r9rUr6r5rWrU)r9r5r6r5rWr5rI)rmz(HTTPConnectionPool | HTTPSConnectionPoolr$r5rWrU)rmzqueue.LifoQueue[typing.Any]rWrX)[ __future__rrloggingr^rtypingrrvsocketrrtypesr_base_connectionr _collectionsr _request_methodsr connectionr r r rrrrrr exceptionsrrrrrrrrrrrrr rr!util.connectionr" util.proxyr# util.requestr$r% util.retryr&util.ssl_match_hostnamer' util.timeoutr(r)r*util.urlr+r,r-r;r. util.utilr/ TYPE_CHECKINGssltyping_extensionsr0r1r2 getLoggerrErUnionfloatrr4EAGAIN EWOULDBLOCKrrbrroverloadr%rxrJrAr?rBs_"  +((,   9'27@5BB)7 &Ig! We]D@A . . dLL%"3"34J J ZN,Nb9:&HLR 2R:DRR rA