U eY@sddlmZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZdd lmZmZmZdd lmZmZmZmZdd lmZdd lmZdd lmZddl m!Z!ddl"m#Z#ddl$m%Z%m&Z&ej'rddl(Z(ddlm)Z)dddgZ*e+e,Z-dZ.dZ/e0dZ1Gdddej2Z3ddddddZ4e5e4e3e5e4e3dZ6eedZ7Gd ddeZ8Gd!dde8Z9d"d#dd$d%dZ:dS)&) annotationsN) TracebackType)urljoin)HTTPHeaderDictRecentlyUsedContainer)RequestMethods) ProxyConfig)HTTPConnectionPoolHTTPSConnectionPoolport_by_scheme)LocationValueError MaxRetryErrorProxySchemeUnknownURLSchemeUnknown)BaseHTTPResponse)_TYPE_SOCKET_OPTIONS)connection_requires_http_tunnel)Retry)Timeout)Url parse_url)Literal PoolManager ProxyManagerproxy_from_url) key_file cert_file cert_reqsca_certs ca_cert_data ssl_versionZssl_minimum_versionZssl_maximum_version ca_cert_dir ssl_context key_passwordserver_hostnamei@_SelfTc@seZdZUdZded<ded<ded<ded<d ed <d ed <d ed<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<d ed!<d"ed#<d ed$<d%ed&<d'ed(<d ed)<d*ed+<ded,<ded-<ded.<d/S)0PoolKeyz All known keyword arguments that could be provided to the pool manager, its pools, or the underlying connections. All custom key schemes should include the fields in this key at a minimum. str key_schemekey_host int | Nonekey_portzTimeout | float | int | None key_timeoutzRetry | bool | int | None key_retriesz bool | None key_blockztuple[str, int] | Nonekey_source_address str | None key_key_filekey_key_password key_cert_file key_cert_reqs key_ca_certszstr | bytes | NoneZkey_ca_cert_datazint | str | Nonekey_ssl_versionzssl.TLSVersion | NoneZkey_ssl_minimum_versionZkey_ssl_maximum_versionkey_ca_cert_dirssl.SSLContext | Nonekey_ssl_context key_maxsizez!frozenset[tuple[str, str]] | None key_headers Url | None key__proxykey__proxy_headersProxyConfig | Nonekey__proxy_configz_TYPE_SOCKET_OPTIONS | Nonekey_socket_optionskey__socks_optionszbool | str | Nonekey_assert_hostnamekey_assert_fingerprintkey_server_hostname key_blocksizeN)__name__ __module__ __qualname____doc____annotations__rMrMA/opt/hc_python/lib/python3.8/site-packages/urllib3/poolmanager.pyr'9s< r'z type[PoolKey]dict[str, typing.Any]) key_classrequest_contextreturncCs|}|d|d<|d|d<dD],}||kr,||dk r,t||||<q,|d}|dk rxt||d<t|D]}|||d|<q|j D]}||krd||<q|ddkrt |d<|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 schemehost)headers_proxy_headers_socks_optionsNsocket_optionskey_rG) copylower frozensetitemsgettuplelistkeyspop_fields_DEFAULT_BLOCKSIZE)rPrQcontextkey socket_optsfieldrMrMrN_default_key_normalizer`s"    rihttphttpscseZdZUdZdZded<dZded<dAdd d d d fd d ZdddddZdddddddZ dBddddddddZ d d d!d"Z dCd$d%d$ddd&d'd(Z d)dd*d+d,Z d-d)dd.d/d0ZdDdddd1d2d3Zdd)d4d5d6Zd7d8d9d:d;ZdEddd8d d=d>d?d@ZZS)FraV 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: .. code-block:: python import urllib3 http = urllib3.PoolManager(num_pools=2) resp1 = http.request("GET", "https://google.com/") resp2 = http.request("GET", "https://google.com/mail") resp3 = http.request("GET", "https://yahoo.com/") print(len(http.pools)) # 2 Nr=proxyr@ proxy_config inttyping.Mapping[str, str] | None typing.AnyNone) num_poolsrUconnection_pool_kwrRc s4t|||_|t||_t|_t|_dSN)super__init__rurpoolspool_classes_by_schemekey_fn_by_schemerZ)selfrtrUru __class__rMrNrxs   zPoolManager.__init__r&)r|rRcCs|SrvrMr|rMrMrN __enter__szPoolManager.__enter__ztype[BaseException] | NonezBaseException | NonezTracebackType | NonezLiteral[False])exc_typeexc_valexc_tbrRcCs |dS)NF)clear)r|rrrrMrMrN__exit__szPoolManager.__exit__r(dict[str, typing.Any] | Noner )rSrTportrQrRcCst|j|}|dkr|j}|ddkr2t|d<dD]}||dq6|dkrftD]}||dqT|||f|S)a Create a new :class:`urllib3.connectionpool.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 blocksize)rSrTrrk)rzrurZr^rdrb SSL_KEYWORDS)r|rSrTrrQpool_clsrfkwrMrMrN _new_pools  zPoolManager._new_pool)rRcCs|jdS)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)ryrrrMrMrNr szPoolManager.clearrkr1r+rTrrS pool_kwargsrRcCsT|s td||}|pd|d<|s:t|dd}||d<||d<||S)a Get a :class:`urllib3.connectionpool.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. zNo host specified.rkrSPrrT)r _merge_pool_kwargsr r^r[connection_from_context)r|rTrrSrrQrMrMrNconnection_from_hosts  z PoolManager.connection_from_hostrO)rQrRcCsXd|krtdt|d|d}|j|}|sBt|||}|j||dS)z Get a :class:`urllib3.connectionpool.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. strictzdThe 'strict' parameter is no longer needed on Python 3+. This will raise an error in urllib3 v2.1.0.rSrQ) warningswarnDeprecationWarningrbr[r{r^rconnection_from_pool_key)r|rQrSpool_key_constructorpool_keyrMrMrNr2s    z#PoolManager.connection_from_contextr')rrQrRc Csl|jjZ|j|}|r*|W5QRS|d}|d}|d}|j||||d}||j|<W5QRX|S)a Get a :class:`urllib3.connectionpool.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. rSrTrr)rylockr^r)r|rrQpoolrSrTrrMrMrNrKs  z$PoolManager.connection_from_pool_key)urlrrRcCs t|}|j|j|j|j|dS)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. )rrSr)rrrTrrS)r|rrurMrMrNconnection_from_urles zPoolManager.connection_from_url)overriderRc CsV|j}|rR|D]:\}}|dkrHz ||=WqPtk rDYqPXq|||<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)rurZr]KeyError)r|rbase_pool_kwargsrfvaluerMrMrNrws   zPoolManager._merge_pool_kwargsrbool) parsed_urlrRcCs"|jdkrdSt|j|j|j S)z Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel. NF)rmrrnrS)r|rrMrMrN!_proxy_requires_url_absolute_forms z-PoolManager._proxy_requires_url_absolute_formTrmethodrredirectrrRc Kst|}|jdkr"tjdtdd|j|j|j|jd}d|d<d|d<d |krZ|j|d <| |rv|j ||f|}n|j ||j f|}|o| }|s|St ||}|jd krd }d|d <t|d |d <|d } t| tstj| |d} | jrF||sF|d } |d D]"} | | jkr| | dq| |d <z| j||||d} Wn,tk r| jr||YSX| |d <||d<td||||j ||f|S)aN Same as :meth:`urllib3.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. Na URLs without a scheme (ie 'https://') are deprecated and will raise an error in a future version of urllib3. To avoid this DeprecationWarning ensure all URLs start with 'https://' or 'http://'. Read more in this issue: https://github.com/urllib3/urllib3/issues/2920)category stacklevel)rrSFassert_same_hostrrUi/GETbodyretries)r)response_poolzRedirecting %s -> %s) rrSrrrrrTrrUrurlopen request_uriget_redirect_locationrstatusrZ_prepare_for_method_changer^ isinstancerfrom_intremove_headers_on_redirect is_same_hostrZr[rb incrementrraise_on_redirect drain_connloginfo) r|rrrrrconnrredirect_locationr new_headersheaderrMrMrNrs\              zPoolManager.urlopen)roN)N)NrkN)N)T)rHrIrJrKrmrLrnrxrrrrrrrrrrr __classcell__rMrMr}rNrs. !  & c seZdZdZd!dddddd d d d d d fdd Zd"d dd dddfdd Zd#ddddddZd$ddd d ddfdd ZZS)%ra> 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. :param proxy_ssl_context: The proxy SSL context is used to establish the TLS connection to the proxy when using HTTPS proxies. :param use_forwarding_for_https: (Defaults to False) If set to True will forward requests to the HTTPS proxy to be made on behalf of the client instead of creating a TLS tunnel via the CONNECT method. **Enabling this flag means that request and response headers and content will be visible from the HTTPS proxy** whereas tunneling keeps request and response headers and content private. IP address, target hostname, SNI, and port are always visible to an HTTPS proxy even when this flag is disabled. :param proxy_assert_hostname: The hostname of the certificate to verify against. :param proxy_assert_fingerprint: The fingerprint of the certificate to verify against. Example: .. code-block:: python import urllib3 proxy = urllib3.ProxyManager("https://localhost:3128/") resp1 = proxy.request("GET", "https://google.com/") resp2 = proxy.request("GET", "https://httpbin.org/") print(len(proxy.pools)) # 1 resp3 = proxy.request("GET", "https://httpbin.org/") resp4 = proxy.request("GET", "https://twitter.com/") print(len(proxy.pools)) # 3 roNFr(rprqr9rzNone | str | Literal[False]r1rrrs) proxy_urlrtrU proxy_headersproxy_ssl_contextuse_forwarding_for_httpsproxy_assert_hostnameproxy_assert_fingerprintrurRc  st|tr&|jd|jd|j} n|} t| } | jdkrFt| j| jsft| jd} | j | d} | |_ |pri|_ ||_ t |||||_|j | d<|j | d<|j| d<tj||f| dS) Nz://:rjr)r_proxyrV _proxy_config)rr rSrTrrrr r^_replacermrrr rnrwrx) r|rrtrUrrrrrruZ str_proxy_urlrmrr}rMrNrx$s,        zProxyManager.__init__rkr+rr rcs<|dkrtj||||dStj|jj|jj|jj|dS)Nrl)r)rwrrmrTrrS)r|rTrrSrr}rMrNrMsz!ProxyManager.connection_from_hostztyping.Mapping[str, str])rrUrRcCs0ddi}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. Acceptz*/*Host)rnetlocupdate)r|rrUheaders_rrMrMrN_set_proxy_headers]s  zProxyManager._set_proxy_headersTrrc sRt|}t|j|j|js8|d|j}||||d<tj ||fd|i|S)z@Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.rUr) rrrmrnrSr^rUrrwr)r|rrrrrrUr}rMrNrns zProxyManager.urlopen)roNNNFNN)NrkN)N)T) rHrIrJrKrxrrrrrMrMr}rNrs"9&,r(rr)rrrRcKstfd|i|S)Nr)r)rrrMrMrNr}s); __future__r functoolsloggingtypingrtypesr urllib.parser _collectionsrrZ_request_methodsr connectionr connectionpoolr r r exceptionsr rrrrrZutil.connectionrZ util.proxyrZ util.retryrZ util.timeoutrZutil.urlrr TYPE_CHECKINGsslr__all__ getLoggerrHrrrdTypeVarr& NamedTupler'ripartialr{rzrrrrMrMrMrNsJ              '<   L