Skip to content
Myr

Switch to private module names (#785)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Rename modules * Update names in package * Fix tests * Review docs

authored by Florimond Manca · committed by Tom Christie · parent c2eb0bd · Browse files · 70 files+7205 added−7205 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

70 files+7205 added−7205 removed

  • tests:+39 added−39 removed
  • other:+7166 added−7166 removed

70 files+7205 added−7205 removed

modified:docs/environment_variables.md+34 added-34 removed
30 unmodified lines
31Debug output:3233```console34$ HTTPX_LOG_LEVEL=debug python test_script.py35DEBUG [2019-11-06 19:11:24] httpx.client - HTTP Request: GET https://google.com "HTTP/1.1 301 Moved Permanently"36DEBUG [2019-11-06 19:11:24] httpx.client - HTTP Request: GET https://www.google.com/ "HTTP/1.1 200 OK"35DEBUG [2019-11-06 19:11:24] httpx._client - HTTP Request: GET https://google.com "HTTP/1.1 301 Moved Permanently"36DEBUG [2019-11-06 19:11:24] httpx._client - HTTP Request: GET https://www.google.com/ "HTTP/1.1 200 OK"37```3839Trace output:4041```console42$ HTTPX_LOG_LEVEL=trace python test_script.py43TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='google.com' port=443)44TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='google.com' port=443))45TRACE [2019-11-06 19:18:56] httpx.config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])46TRACE [2019-11-06 19:18:56] httpx.config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem47TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='google.com' port=443 timeout=Timeout(timeout=5.0)48TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - connected http_version='HTTP/2'49TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]50TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - end_stream stream_id=151TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>52TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>53TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>54TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'301'), (b'location', b'https://www.google.com/'), (b'content-type', b'text/html; charset=UTF-8'), (b'date', b'Wed, 06 Nov 2019 18:18:56 GMT'), (b'expires', b'Fri, 06 Dec 2019 18:18:56 GMT'), (b'cache-control', b'public, max-age=2592000'), (b'server', b'gws'), (b'content-length', b'220'), (b'x-xss-protection', b'0'), (b'x-frame-options', b'SAMEORIGIN'), (b'alt-svc', b'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000')]>55DEBUG [2019-11-06 19:18:56] httpx.client - HTTP Request: GET https://google.com "HTTP/2 301 Moved Permanently"56TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)57TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))58TRACE [2019-11-06 19:18:56] httpx.config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])59TRACE [2019-11-06 19:18:56] httpx.config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem60TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='www.google.com' port=443 timeout=Timeout(timeout=5.0)61TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - connected http_version='HTTP/2'62TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'www.google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]63TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - end_stream stream_id=164TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>65TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>66TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>67TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'200'), (b'date', b'Wed, 06 Nov 2019 18:18:56 GMT'), (b'expires', b'-1'), (b'cache-control', b'private, max-age=0'), (b'content-type', b'text/html; charset=ISO-8859-1'), (b'p3p', b'CP="This is not a P3P policy! See g.co/p3phelp for more info."'), (b'content-encoding', b'gzip'), (b'server', b'gws'), (b'content-length', b'5073'), (b'x-xss-protection', b'0'), (b'x-frame-options', b'SAMEORIGIN'), (b'set-cookie', b'1P_JAR=2019-11-06-18; expires=Fri, 06-Dec-2019 18:18:56 GMT; path=/; domain=.google.com; SameSite=none'), (b'set-cookie', b'NID=190=m8G9qLxCz2_4HbZI02ON2HTJF4xTvOhoJiS57Hm-OJrNS2eY20LfXMR_u-mLjujeshW5-BTezI69OGpHksT4ZK2TCDsWeU0DF7AmDTjjXFOdj30eIUTpNq7r9aWRvI8UrqiwlIsLkE8Ee3t5PiIiVdSMUcji7dkavGlMUpkMXU8; expires=Thu, 07-May-2020 18:18:56 GMT; path=/; domain=.google.com; HttpOnly'), (b'alt-svc', b'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000')]>68DEBUG [2019-11-06 19:18:56] httpx.client - HTTP Request: GET https://www.google.com/ "HTTP/2 200 OK"69TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:5186, data:1f8b08000000000002ffc55af97adb4692ff3f4f>70TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:221, data:>71TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>72TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>73TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))74TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - close_connection43TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='google.com' port=443)44TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='google.com' port=443))45TRACE [2019-11-06 19:18:56] httpx._config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])46TRACE [2019-11-06 19:18:56] httpx._config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem47TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - start_connect host='google.com' port=443 timeout=Timeout(timeout=5.0)48TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - connected http_version='HTTP/2'49TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]50TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - end_stream stream_id=151TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>52TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>53TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>54TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'301'), (b'location', b'https://www.google.com/'), (b'content-type', b'text/html; charset=UTF-8'), (b'date', b'Wed, 06 Nov 2019 18:18:56 GMT'), (b'expires', b'Fri, 06 Dec 2019 18:18:56 GMT'), (b'cache-control', b'public, max-age=2592000'), (b'server', b'gws'), (b'content-length', b'220'), (b'x-xss-protection', b'0'), (b'x-frame-options', b'SAMEORIGIN'), (b'alt-svc', b'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000')]>55DEBUG [2019-11-06 19:18:56] httpx._client - HTTP Request: GET https://google.com "HTTP/2 301 Moved Permanently"56TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)57TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))58TRACE [2019-11-06 19:18:56] httpx._config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])59TRACE [2019-11-06 19:18:56] httpx._config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem60TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - start_connect host='www.google.com' port=443 timeout=Timeout(timeout=5.0)61TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - connected http_version='HTTP/2'62TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'www.google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]63TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - end_stream stream_id=164TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>65TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>66TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>67TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'200'), (b'date', b'Wed, 06 Nov 2019 18:18:56 GMT'), (b'expires', b'-1'), (b'cache-control', b'private, max-age=0'), (b'content-type', b'text/html; charset=ISO-8859-1'), (b'p3p', b'CP="This is not a P3P policy! See g.co/p3phelp for more info."'), (b'content-encoding', b'gzip'), (b'server', b'gws'), (b'content-length', b'5073'), (b'x-xss-protection', b'0'), (b'x-frame-options', b'SAMEORIGIN'), (b'set-cookie', b'1P_JAR=2019-11-06-18; expires=Fri, 06-Dec-2019 18:18:56 GMT; path=/; domain=.google.com; SameSite=none'), (b'set-cookie', b'NID=190=m8G9qLxCz2_4HbZI02ON2HTJF4xTvOhoJiS57Hm-OJrNS2eY20LfXMR_u-mLjujeshW5-BTezI69OGpHksT4ZK2TCDsWeU0DF7AmDTjjXFOdj30eIUTpNq7r9aWRvI8UrqiwlIsLkE8Ee3t5PiIiVdSMUcji7dkavGlMUpkMXU8; expires=Thu, 07-May-2020 18:18:56 GMT; path=/; domain=.google.com; HttpOnly'), (b'alt-svc', b'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000')]>68DEBUG [2019-11-06 19:18:56] httpx._client - HTTP Request: GET https://www.google.com/ "HTTP/2 200 OK"69TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:5186, data:1f8b08000000000002ffc55af97adb4692ff3f4f>70TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:221, data:>71TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>72TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>73TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))74TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - close_connection75```7677`SSLKEYLOGFILE`78-----------
76 unmodified lines
added:httpx/_backends/__init__.py
added:httpx/_backends/asyncio.py+268 added
1import asyncio2import ssl3import typing45from .._config import Timeout6from .._exceptions import ConnectTimeout, ReadTimeout, WriteTimeout7from .._utils import as_network_error8from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend910SSL_MONKEY_PATCH_APPLIED = False111213def ssl_monkey_patch() -> None:14 """15 Monkey-patch for https://bugs.python.org/issue367091617 This prevents console errors when outstanding HTTPS connections18 still exist at the point of exiting.1920 Clients which have been opened using a `with` block, or which have21 had `close()` closed, will not exhibit this issue in the first place.22 """23 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore2425 _write = MonkeyPatch.write2627 def _fixed_write(self, data: bytes) -> None: # type: ignore28 if self._loop and not self._loop.is_closed():29 _write(self, data)3031 MonkeyPatch.write = _fixed_write323334async def backport_start_tls(35 transport: asyncio.BaseTransport,36 protocol: asyncio.BaseProtocol,37 sslcontext: ssl.SSLContext = None,38 *,39 server_side: bool = False,40 server_hostname: str = None,41 ssl_handshake_timeout: float = None,42) -> asyncio.Transport: # pragma: nocover (Since it's not used on all Python versions.)43 """44 Python 3.6 asyncio doesn't have a start_tls() method on the loop45 so we use this function in place of the loop's start_tls() method.4647 Adapted from this comment:4849 https://github.com/urllib3/urllib3/issues/1323#issuecomment-36249483950 """51 import asyncio.sslproto5253 loop = asyncio.get_event_loop()54 waiter = loop.create_future()55 ssl_protocol = asyncio.sslproto.SSLProtocol(56 loop,57 protocol,58 sslcontext,59 waiter,60 server_side=False,61 server_hostname=server_hostname,62 call_connection_made=False,63 )6465 transport.set_protocol(ssl_protocol)66 loop.call_soon(ssl_protocol.connection_made, transport)67 loop.call_soon(transport.resume_reading) # type: ignore6869 await waiter70 return ssl_protocol._app_transport717273class SocketStream(BaseSocketStream):74 def __init__(75 self, stream_reader: asyncio.StreamReader, stream_writer: asyncio.StreamWriter,76 ):77 self.stream_reader = stream_reader78 self.stream_writer = stream_writer79 self.read_lock = asyncio.Lock()80 self.write_lock = asyncio.Lock()8182 self._inner: typing.Optional[SocketStream] = None8384 async def start_tls(85 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout86 ) -> "SocketStream":87 loop = asyncio.get_event_loop()8889 stream_reader = asyncio.StreamReader()90 protocol = asyncio.StreamReaderProtocol(stream_reader)91 transport = self.stream_writer.transport9293 loop_start_tls = getattr(loop, "start_tls", backport_start_tls)9495 transport = await asyncio.wait_for(96 loop_start_tls(97 transport=transport,98 protocol=protocol,99 sslcontext=ssl_context,100 server_hostname=hostname,101 ),102 timeout=timeout.connect_timeout,103 )104105 stream_reader.set_transport(transport)106 stream_writer = asyncio.StreamWriter(107 transport=transport, protocol=protocol, reader=stream_reader, loop=loop108 )109110 ssl_stream = SocketStream(stream_reader, stream_writer)111 # When we return a new SocketStream with new StreamReader/StreamWriter instances112 # we need to keep references to the old StreamReader/StreamWriter so that they113 # are not garbage collected and closed while we're still using them.114 ssl_stream._inner = self115 return ssl_stream116117 def get_http_version(self) -> str:118 ssl_object = self.stream_writer.get_extra_info("ssl_object")119120 if ssl_object is None:121 return "HTTP/1.1"122123 ident = ssl_object.selected_alpn_protocol()124 return "HTTP/2" if ident == "h2" else "HTTP/1.1"125126 async def read(self, n: int, timeout: Timeout) -> bytes:127 try:128 async with self.read_lock:129 with as_network_error(OSError):130 return await asyncio.wait_for(131 self.stream_reader.read(n), timeout.read_timeout132 )133 except asyncio.TimeoutError:134 raise ReadTimeout() from None135136 async def write(self, data: bytes, timeout: Timeout) -> None:137 if not data:138 return139140 try:141 async with self.write_lock:142 with as_network_error(OSError):143 self.stream_writer.write(data)144 return await asyncio.wait_for(145 self.stream_writer.drain(), timeout.write_timeout146 )147 except asyncio.TimeoutError:148 raise WriteTimeout() from None149150 def is_connection_dropped(self) -> bool:151 # Counter-intuitively, what we really want to know here is whether the socket is152 # *readable*, i.e. whether it would return immediately with empty bytes if we153 # called `.recv()` on it, indicating that the other end has closed the socket.154 # See: https://github.com/encode/httpx/pull/143#issuecomment-515181778155 #156 # As it turns out, asyncio checks for readability in the background157 # (see: https://github.com/encode/httpx/pull/276#discussion_r322000402),158 # so checking for EOF or readability here would yield the same result.159 #160 # At the cost of rigour, we check for EOF instead of readability because asyncio161 # does not expose any public API to check for readability.162 # (For a solution that uses private asyncio APIs, see:163 # https://github.com/encode/httpx/pull/143#issuecomment-515202982)164165 return self.stream_reader.at_eof()166167 async def close(self) -> None:168 # NOTE: StreamWriter instances expose a '.wait_closed()' coroutine function,169 # but using it has caused compatibility issues with certain sites in170 # the past (see https://github.com/encode/httpx/issues/634), which is171 # why we don't call it here.172 # This is fine, though, because '.close()' schedules the actual closing of the173 # stream, meaning that at best it will happen during the next event loop174 # iteration, and at worst asyncio will take care of it on program exit.175 async with self.write_lock:176 with as_network_error(OSError):177 self.stream_writer.close()178179180class AsyncioBackend(ConcurrencyBackend):181 def __init__(self) -> None:182 global SSL_MONKEY_PATCH_APPLIED183184 if not SSL_MONKEY_PATCH_APPLIED:185 ssl_monkey_patch()186 SSL_MONKEY_PATCH_APPLIED = True187188 async def open_tcp_stream(189 self,190 hostname: str,191 port: int,192 ssl_context: typing.Optional[ssl.SSLContext],193 timeout: Timeout,194 ) -> SocketStream:195 try:196 with as_network_error(OSError):197 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore198 asyncio.open_connection(hostname, port, ssl=ssl_context),199 timeout.connect_timeout,200 )201 except asyncio.TimeoutError:202 raise ConnectTimeout()203204 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)205206 async def open_uds_stream(207 self,208 path: str,209 hostname: typing.Optional[str],210 ssl_context: typing.Optional[ssl.SSLContext],211 timeout: Timeout,212 ) -> SocketStream:213 server_hostname = hostname if ssl_context else None214215 try:216 with as_network_error(OSError):217 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore218 asyncio.open_unix_connection(219 path, ssl=ssl_context, server_hostname=server_hostname220 ),221 timeout.connect_timeout,222 )223 except asyncio.TimeoutError:224 raise ConnectTimeout()225226 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)227228 def time(self) -> float:229 loop = asyncio.get_event_loop()230 return loop.time()231232 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:233 return Semaphore(max_value, exc_class)234235 def create_lock(self) -> BaseLock:236 return Lock()237238239class Lock(BaseLock):240 def __init__(self) -> None:241 self._lock = asyncio.Lock()242243 def release(self) -> None:244 self._lock.release()245246 async def acquire(self) -> None:247 await self._lock.acquire()248249250class Semaphore(BaseSemaphore):251 def __init__(self, max_value: int, exc_class: type) -> None:252 self.max_value = max_value253 self.exc_class = exc_class254255 @property256 def semaphore(self) -> asyncio.BoundedSemaphore:257 if not hasattr(self, "_semaphore"):258 self._semaphore = asyncio.BoundedSemaphore(value=self.max_value)259 return self._semaphore260261 async def acquire(self, timeout: float = None) -> None:262 try:263 await asyncio.wait_for(self.semaphore.acquire(), timeout)264 except asyncio.TimeoutError:265 raise self.exc_class()266267 def release(self) -> None:268 self.semaphore.release()
added:httpx/_backends/auto.py+51 added
1import ssl2import typing34import sniffio56from .._config import Timeout7from .base import (8 BaseLock,9 BaseSemaphore,10 BaseSocketStream,11 ConcurrencyBackend,12 lookup_backend,13)141516class AutoBackend(ConcurrencyBackend):17 @property18 def backend(self) -> ConcurrencyBackend:19 if not hasattr(self, "_backend_implementation"):20 backend = sniffio.current_async_library()21 if backend not in ("asyncio", "trio"): # pragma: nocover22 raise RuntimeError(f"Unsupported concurrency backend {backend!r}")23 self._backend_implementation = lookup_backend(backend)24 return self._backend_implementation2526 async def open_tcp_stream(27 self,28 hostname: str,29 port: int,30 ssl_context: typing.Optional[ssl.SSLContext],31 timeout: Timeout,32 ) -> BaseSocketStream:33 return await self.backend.open_tcp_stream(hostname, port, ssl_context, timeout)3435 async def open_uds_stream(36 self,37 path: str,38 hostname: typing.Optional[str],39 ssl_context: typing.Optional[ssl.SSLContext],40 timeout: Timeout,41 ) -> BaseSocketStream:42 return await self.backend.open_uds_stream(path, hostname, ssl_context, timeout)4344 def time(self) -> float:45 return self.backend.time()4647 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:48 return self.backend.create_semaphore(max_value, exc_class)4950 def create_lock(self) -> BaseLock:51 return self.backend.create_lock()
added:httpx/_backends/base.py+121 added
1import ssl2import typing3from types import TracebackType45from .._config import Timeout678def lookup_backend(9 backend: typing.Union[str, "ConcurrencyBackend"] = "auto"10) -> "ConcurrencyBackend":11 if not isinstance(backend, str):12 return backend1314 if backend == "auto":15 from .auto import AutoBackend1617 return AutoBackend()18 elif backend == "asyncio":19 from .asyncio import AsyncioBackend2021 return AsyncioBackend()22 elif backend == "trio":23 from .trio import TrioBackend2425 return TrioBackend()2627 raise RuntimeError(f"Unknown or unsupported concurrency backend {backend!r}")282930class BaseSocketStream:31 """32 A socket stream with read/write operations. Abstracts away any asyncio-specific33 interfaces into a more generic base class, that we can use with alternate34 backends, or for stand-alone test cases.35 """3637 def get_http_version(self) -> str:38 raise NotImplementedError() # pragma: no cover3940 async def start_tls(41 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout42 ) -> "BaseSocketStream":43 raise NotImplementedError() # pragma: no cover4445 async def read(self, n: int, timeout: Timeout) -> bytes:46 raise NotImplementedError() # pragma: no cover4748 async def write(self, data: bytes, timeout: Timeout) -> None:49 raise NotImplementedError() # pragma: no cover5051 async def close(self) -> None:52 raise NotImplementedError() # pragma: no cover5354 def is_connection_dropped(self) -> bool:55 raise NotImplementedError() # pragma: no cover565758class BaseLock:59 """60 An abstract interface for Lock classes.61 Abstracts away any asyncio-specific interfaces.62 """6364 async def __aenter__(self) -> None:65 await self.acquire()6667 async def __aexit__(68 self,69 exc_type: typing.Type[BaseException] = None,70 exc_value: BaseException = None,71 traceback: TracebackType = None,72 ) -> None:73 self.release()7475 def release(self) -> None:76 raise NotImplementedError() # pragma: no cover7778 async def acquire(self) -> None:79 raise NotImplementedError() # pragma: no cover808182class BaseSemaphore:83 """84 An abstract interface for Semaphore classes.85 Abstracts away any asyncio-specific interfaces.86 """8788 async def acquire(self, timeout: float = None) -> None:89 raise NotImplementedError() # pragma: no cover9091 def release(self) -> None:92 raise NotImplementedError() # pragma: no cover939495class ConcurrencyBackend:96 async def open_tcp_stream(97 self,98 hostname: str,99 port: int,100 ssl_context: typing.Optional[ssl.SSLContext],101 timeout: Timeout,102 ) -> BaseSocketStream:103 raise NotImplementedError() # pragma: no cover104105 async def open_uds_stream(106 self,107 path: str,108 hostname: typing.Optional[str],109 ssl_context: typing.Optional[ssl.SSLContext],110 timeout: Timeout,111 ) -> BaseSocketStream:112 raise NotImplementedError() # pragma: no cover113114 def time(self) -> float:115 raise NotImplementedError() # pragma: no cover116117 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:118 raise NotImplementedError() # pragma: no cover119120 def create_lock(self) -> BaseLock:121 raise NotImplementedError() # pragma: no cover
added:httpx/_backends/trio.py+176 added
1import ssl2import typing34import trio56from .._config import Timeout7from .._exceptions import ConnectTimeout, ReadTimeout, WriteTimeout8from .._utils import as_network_error9from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend101112def none_as_inf(value: typing.Optional[float]) -> float:13 return value if value is not None else float("inf")141516class SocketStream(BaseSocketStream):17 def __init__(18 self, stream: typing.Union[trio.SocketStream, trio.SSLStream],19 ) -> None:20 self.stream = stream21 self.read_lock = trio.Lock()22 self.write_lock = trio.Lock()2324 async def start_tls(25 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout26 ) -> "SocketStream":27 connect_timeout = none_as_inf(timeout.connect_timeout)28 ssl_stream = trio.SSLStream(29 self.stream, ssl_context=ssl_context, server_hostname=hostname30 )3132 with trio.move_on_after(connect_timeout):33 with as_network_error(trio.BrokenResourceError):34 await ssl_stream.do_handshake()35 return SocketStream(ssl_stream)3637 raise ConnectTimeout()3839 def get_http_version(self) -> str:40 if not isinstance(self.stream, trio.SSLStream):41 return "HTTP/1.1"4243 ident = self.stream.selected_alpn_protocol()44 return "HTTP/2" if ident == "h2" else "HTTP/1.1"4546 async def read(self, n: int, timeout: Timeout) -> bytes:47 read_timeout = none_as_inf(timeout.read_timeout)4849 with trio.move_on_after(read_timeout):50 async with self.read_lock:51 with as_network_error(trio.BrokenResourceError):52 return await self.stream.receive_some(max_bytes=n)5354 raise ReadTimeout()5556 async def write(self, data: bytes, timeout: Timeout) -> None:57 if not data:58 return5960 write_timeout = none_as_inf(timeout.write_timeout)6162 with trio.move_on_after(write_timeout):63 async with self.write_lock:64 with as_network_error(trio.BrokenResourceError):65 return await self.stream.send_all(data)6667 raise WriteTimeout()6869 def is_connection_dropped(self) -> bool:70 # Adapted from: https://github.com/encode/httpx/pull/143#issuecomment-51520298271 stream = self.stream7273 # Peek through any SSLStream wrappers to get the underlying SocketStream.74 while hasattr(stream, "transport_stream"):75 stream = stream.transport_stream76 assert isinstance(stream, trio.SocketStream)7778 # Counter-intuitively, what we really want to know here is whether the socket is79 # *readable*, i.e. whether it would return immediately with empty bytes if we80 # called `.recv()` on it, indicating that the other end has closed the socket.81 # See: https://github.com/encode/httpx/pull/143#issuecomment-51518177882 return stream.socket.is_readable()8384 async def close(self) -> None:85 async with self.write_lock:86 await self.stream.aclose()878889class TrioBackend(ConcurrencyBackend):90 async def open_tcp_stream(91 self,92 hostname: str,93 port: int,94 ssl_context: typing.Optional[ssl.SSLContext],95 timeout: Timeout,96 ) -> SocketStream:97 connect_timeout = none_as_inf(timeout.connect_timeout)9899 with trio.move_on_after(connect_timeout):100 with as_network_error(OSError):101 stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)102103 if ssl_context is not None:104 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)105 with as_network_error(trio.BrokenResourceError):106 await stream.do_handshake()107108 return SocketStream(stream=stream)109110 raise ConnectTimeout()111112 async def open_uds_stream(113 self,114 path: str,115 hostname: typing.Optional[str],116 ssl_context: typing.Optional[ssl.SSLContext],117 timeout: Timeout,118 ) -> SocketStream:119 connect_timeout = none_as_inf(timeout.connect_timeout)120121 with trio.move_on_after(connect_timeout):122 with as_network_error(OSError):123 stream: trio.SocketStream = await trio.open_unix_socket(path)124125 if ssl_context is not None:126 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)127 with as_network_error(trio.BrokenResourceError):128 await stream.do_handshake()129130 return SocketStream(stream=stream)131132 raise ConnectTimeout()133134 def time(self) -> float:135 return trio.current_time()136137 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:138 return Semaphore(max_value, exc_class)139140 def create_lock(self) -> BaseLock:141 return Lock()142143144class Semaphore(BaseSemaphore):145 def __init__(self, max_value: int, exc_class: type):146 self.max_value = max_value147 self.exc_class = exc_class148149 @property150 def semaphore(self) -> trio.Semaphore:151 if not hasattr(self, "_semaphore"):152 self._semaphore = trio.Semaphore(self.max_value, max_value=self.max_value)153 return self._semaphore154155 async def acquire(self, timeout: float = None) -> None:156 timeout = none_as_inf(timeout)157158 with trio.move_on_after(timeout):159 await self.semaphore.acquire()160 return161162 raise self.exc_class()163164 def release(self) -> None:165 self.semaphore.release()166167168class Lock(BaseLock):169 def __init__(self) -> None:170 self._lock = trio.Lock()171172 def release(self) -> None:173 self._lock.release()174175 async def acquire(self) -> None:176 await self._lock.acquire()
added:httpx/_dispatch/__init__.py
added:httpx/_dispatch/asgi.py+123 added
1import typing23from .._config import TimeoutTypes4from .._content_streams import ByteStream5from .._models import Request, Response6from .base import AsyncDispatcher789class ASGIDispatch(AsyncDispatcher):10 """11 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.12 The simplest way to use this functionality is to use the `app` argument.1314 ```15 client = httpx.AsyncClient(app=app)16 ```1718 Alternatively, you can setup the dispatch instance explicitly.19 This allows you to include any additional configuration arguments specific20 to the ASGIDispatch class:2122 ```23 dispatch = httpx.ASGIDispatch(24 app=app,25 root_path="/submount",26 client=("1.2.3.4", 123)27 )28 client = httpx.AsyncClient(dispatch=dispatch)29 ```3031 Arguments:3233 * `app` - The ASGI application.34 * `raise_app_exceptions` - Boolean indicating if exceptions in the application35 should be raised. Default to `True`. Can be set to `False` for use cases36 such as testing the content of a client 500 response.37 * `root_path` - The root path on which the ASGI application should be mounted.38 * `client` - A two-tuple indicating the client IP and port of incoming requests.39 ```40 """4142 def __init__(43 self,44 app: typing.Callable,45 raise_app_exceptions: bool = True,46 root_path: str = "",47 client: typing.Tuple[str, int] = ("127.0.0.1", 123),48 ) -> None:49 self.app = app50 self.raise_app_exceptions = raise_app_exceptions51 self.root_path = root_path52 self.client = client5354 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:55 scope = {56 "type": "http",57 "asgi": {"version": "3.0"},58 "http_version": "1.1",59 "method": request.method,60 "headers": request.headers.raw,61 "scheme": request.url.scheme,62 "path": request.url.path,63 "query_string": request.url.query.encode("ascii"),64 "server": request.url.host,65 "client": self.client,66 "root_path": self.root_path,67 }68 status_code = None69 headers = None70 body_parts = []71 response_started = False72 response_complete = False7374 request_body_chunks = request.stream.__aiter__()7576 async def receive() -> dict:77 try:78 body = await request_body_chunks.__anext__()79 except StopAsyncIteration:80 return {"type": "http.request", "body": b"", "more_body": False}81 return {"type": "http.request", "body": body, "more_body": True}8283 async def send(message: dict) -> None:84 nonlocal status_code, headers, body_parts85 nonlocal response_started, response_complete8687 if message["type"] == "http.response.start":88 assert not response_started8990 status_code = message["status"]91 headers = message.get("headers", [])92 response_started = True9394 elif message["type"] == "http.response.body":95 assert not response_complete96 body = message.get("body", b"")97 more_body = message.get("more_body", False)9899 if body and request.method != "HEAD":100 body_parts.append(body)101102 if not more_body:103 response_complete = True104105 try:106 await self.app(scope, receive, send)107 except Exception:108 if self.raise_app_exceptions or not response_complete:109 raise110111 assert response_complete112 assert status_code is not None113 assert headers is not None114115 stream = ByteStream(b"".join(body_parts))116117 return Response(118 status_code=status_code,119 http_version="HTTP/1.1",120 headers=headers,121 stream=stream,122 request=request,123 )
added:httpx/_dispatch/base.py+64 added
1import typing2from types import TracebackType34from .._config import Timeout5from .._models import (6 HeaderTypes,7 QueryParamTypes,8 Request,9 RequestData,10 Response,11 URLTypes,12)131415class SyncDispatcher:16 """17 Base class for Dispatcher classes, that handle sending the request.18 """1920 def send(self, request: Request, timeout: Timeout = None) -> Response:21 raise NotImplementedError() # pragma: nocover2223 def close(self) -> None:24 pass # pragma: nocover252627class AsyncDispatcher:28 """29 Base class for AsyncDispatcher classes, that handle sending the request.3031 Stubs out the interface, as well as providing a `.request()` convenience32 implementation, to make it easy to use or test stand-alone AsyncDispatchers,33 without requiring a complete `AsyncClient` instance.34 """3536 async def request(37 self,38 method: str,39 url: URLTypes,40 *,41 data: RequestData = b"",42 params: QueryParamTypes = None,43 headers: HeaderTypes = None,44 timeout: Timeout = None,45 ) -> Response:46 request = Request(method, url, data=data, params=params, headers=headers)47 return await self.send(request, timeout=timeout)4849 async def send(self, request: Request, timeout: Timeout = None) -> Response:50 raise NotImplementedError() # pragma: nocover5152 async def close(self) -> None:53 pass # pragma: nocover5455 async def __aenter__(self) -> "AsyncDispatcher":56 return self5758 async def __aexit__(59 self,60 exc_type: typing.Type[BaseException] = None,61 exc_value: BaseException = None,62 traceback: TracebackType = None,63 ) -> None:64 await self.close()
added:httpx/_dispatch/connection_pool.py+221 added
1import typing23from .._backends.base import BaseSemaphore, ConcurrencyBackend, lookup_backend4from .._config import (5 DEFAULT_POOL_LIMITS,6 CertTypes,7 PoolLimits,8 SSLConfig,9 Timeout,10 VerifyTypes,11)12from .._exceptions import PoolTimeout13from .._models import Origin, Request, Response14from .._utils import get_logger15from .base import AsyncDispatcher16from .connection import HTTPConnection1718CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]192021logger = get_logger(__name__)222324class NullSemaphore(BaseSemaphore):25 async def acquire(self, timeout: float = None) -> None:26 return2728 def release(self) -> None:29 return303132class ConnectionStore:33 """34 We need to maintain collections of connections in a way that allows us to:3536 * Lookup connections by origin.37 * Iterate over connections by insertion time.38 * Return the total number of connections.39 """4041 def __init__(self) -> None:42 self.all: typing.Dict[HTTPConnection, float] = {}43 self.by_origin: typing.Dict[Origin, typing.Dict[HTTPConnection, float]] = {}4445 def pop_by_origin(46 self, origin: Origin, http2_only: bool = False47 ) -> typing.Optional[HTTPConnection]:48 try:49 connections = self.by_origin[origin]50 except KeyError:51 return None5253 connection = next(reversed(list(connections.keys())))54 if http2_only and not connection.is_http2:55 return None5657 del connections[connection]58 if not connections:59 del self.by_origin[origin]60 del self.all[connection]6162 return connection6364 def add(self, connection: HTTPConnection) -> None:65 self.all[connection] = 0.066 try:67 self.by_origin[connection.origin][connection] = 0.068 except KeyError:69 self.by_origin[connection.origin] = {connection: 0.0}7071 def remove(self, connection: HTTPConnection) -> None:72 del self.all[connection]73 del self.by_origin[connection.origin][connection]74 if not self.by_origin[connection.origin]:75 del self.by_origin[connection.origin]7677 def clear(self) -> None:78 self.all.clear()79 self.by_origin.clear()8081 def __iter__(self) -> typing.Iterator[HTTPConnection]:82 return iter(self.all.keys())8384 def __len__(self) -> int:85 return len(self.all)868788class ConnectionPool(AsyncDispatcher):89 KEEP_ALIVE_EXPIRY = 5.09091 def __init__(92 self,93 *,94 verify: VerifyTypes = True,95 cert: CertTypes = None,96 trust_env: bool = None,97 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,98 http2: bool = False,99 backend: typing.Union[str, ConcurrencyBackend] = "auto",100 uds: typing.Optional[str] = None,101 ):102 self.ssl = SSLConfig(verify=verify, cert=cert, trust_env=trust_env, http2=http2)103 self.pool_limits = pool_limits104 self.is_closed = False105 self.uds = uds106107 self.keepalive_connections = ConnectionStore()108 self.active_connections = ConnectionStore()109110 self.backend = lookup_backend(backend)111 self.next_keepalive_check = 0.0112113 @property114 def max_connections(self) -> BaseSemaphore:115 # We do this lazily, to make sure backend autodetection always116 # runs within an async context.117 if not hasattr(self, "_max_connections"):118 limit = self.pool_limits.hard_limit119 if limit:120 self._max_connections = self.backend.create_semaphore(121 limit, exc_class=PoolTimeout122 )123 else:124 self._max_connections = NullSemaphore()125126 return self._max_connections127128 @property129 def num_connections(self) -> int:130 return len(self.keepalive_connections) + len(self.active_connections)131132 async def check_keepalive_expiry(self) -> None:133 now = self.backend.time()134 if now < self.next_keepalive_check:135 return136 self.next_keepalive_check = now + 1.0137138 # Iterate through all the keep alive connections.139 # We create a list here to avoid any 'changed during iteration' errors.140 keepalives = list(self.keepalive_connections.all.keys())141 for connection in keepalives:142 if connection.expires_at is not None and now > connection.expires_at:143 self.keepalive_connections.remove(connection)144 self.max_connections.release()145 await connection.close()146147 async def send(self, request: Request, timeout: Timeout = None) -> Response:148 await self.check_keepalive_expiry()149 connection = await self.acquire_connection(150 origin=Origin(request.url), timeout=timeout151 )152 try:153 response = await connection.send(request, timeout=timeout)154 except BaseException as exc:155 self.active_connections.remove(connection)156 self.max_connections.release()157 raise exc158159 return response160161 async def acquire_connection(162 self, origin: Origin, timeout: Timeout = None163 ) -> HTTPConnection:164 logger.trace(f"acquire_connection origin={origin!r}")165 connection = self.pop_connection(origin)166167 if connection is None:168 pool_timeout = None if timeout is None else timeout.pool_timeout169170 await self.max_connections.acquire(timeout=pool_timeout)171 connection = HTTPConnection(172 origin,173 ssl=self.ssl,174 backend=self.backend,175 release_func=self.release_connection,176 uds=self.uds,177 )178 logger.trace(f"new_connection connection={connection!r}")179 else:180 logger.trace(f"reuse_connection connection={connection!r}")181182 self.active_connections.add(connection)183184 return connection185186 async def release_connection(self, connection: HTTPConnection) -> None:187 logger.trace(f"release_connection connection={connection!r}")188 if connection.is_closed:189 self.active_connections.remove(connection)190 self.max_connections.release()191 elif (192 self.pool_limits.soft_limit is not None193 and self.num_connections > self.pool_limits.soft_limit194 ):195 self.active_connections.remove(connection)196 self.max_connections.release()197 await connection.close()198 else:199 now = self.backend.time()200 connection.expires_at = now + self.KEEP_ALIVE_EXPIRY201 self.active_connections.remove(connection)202 self.keepalive_connections.add(connection)203204 async def close(self) -> None:205 self.is_closed = True206 connections = list(self.keepalive_connections)207 self.keepalive_connections.clear()208 for connection in connections:209 self.max_connections.release()210 await connection.close()211212 def pop_connection(self, origin: Origin) -> typing.Optional[HTTPConnection]:213 connection = self.active_connections.pop_by_origin(origin, http2_only=True)214 if connection is None:215 connection = self.keepalive_connections.pop_by_origin(origin)216217 if connection is not None and connection.is_connection_dropped():218 self.max_connections.release()219 connection = None220221 return connection
added:httpx/_dispatch/connection.py+149 added
1import functools2import typing34import h1156from .._backends.base import ConcurrencyBackend, lookup_backend7from .._config import SSLConfig, Timeout8from .._models import URL, Origin, Request, Response9from .._utils import get_logger10from .base import AsyncDispatcher11from .http2 import HTTP2Connection12from .http11 import HTTP11Connection1314# Callback signature: async def callback(conn: HTTPConnection) -> None15ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]161718logger = get_logger(__name__)192021class HTTPConnection(AsyncDispatcher):22 def __init__(23 self,24 origin: typing.Union[str, Origin],25 ssl: SSLConfig = None,26 backend: typing.Union[str, ConcurrencyBackend] = "auto",27 release_func: typing.Optional[ReleaseCallback] = None,28 uds: typing.Optional[str] = None,29 ):30 self.origin = Origin(origin) if isinstance(origin, str) else origin31 self.ssl = SSLConfig() if ssl is None else ssl32 self.backend = lookup_backend(backend)33 self.release_func = release_func34 self.uds = uds35 self.connection: typing.Union[None, HTTP11Connection, HTTP2Connection] = None36 self.expires_at: typing.Optional[float] = None3738 async def send(self, request: Request, timeout: Timeout = None) -> Response:39 timeout = Timeout() if timeout is None else timeout4041 if self.connection is None:42 self.connection = await self.connect(timeout=timeout)4344 return await self.connection.send(request, timeout=timeout)4546 async def connect(47 self, timeout: Timeout48 ) -> typing.Union[HTTP11Connection, HTTP2Connection]:49 host = self.origin.host50 port = self.origin.port51 ssl_context = None if not self.origin.is_ssl else self.ssl.ssl_context5253 if self.release_func is None:54 on_release = None55 else:56 on_release = functools.partial(self.release_func, self)5758 if self.uds is None:59 logger.trace(60 f"start_connect tcp host={host!r} port={port!r} timeout={timeout!r}"61 )62 socket = await self.backend.open_tcp_stream(63 host, port, ssl_context, timeout64 )65 else:66 logger.trace(67 f"start_connect uds path={self.uds!r} host={host!r} timeout={timeout!r}"68 )69 socket = await self.backend.open_uds_stream(70 self.uds, host, ssl_context, timeout71 )7273 http_version = socket.get_http_version()74 logger.trace(f"connected http_version={http_version!r}")7576 if http_version == "HTTP/2":77 return HTTP2Connection(socket, self.backend, on_release=on_release)78 return HTTP11Connection(socket, on_release=on_release)7980 async def tunnel_start_tls(81 self, origin: Origin, proxy_url: URL, timeout: Timeout = None,82 ) -> None:83 """84 Upgrade this connection to use TLS, assuming it represents a TCP tunnel.85 """86 timeout = Timeout() if timeout is None else timeout8788 # First, check that we are in the correct state to start TLS, i.e. we've89 # just agreed to switch protocols with the server via HTTP/1.1.90 assert isinstance(self.connection, HTTP11Connection)91 h11_connection = self.connection92 assert h11_connection is not None93 assert h11_connection.h11_state.our_state == h11.SWITCHED_PROTOCOL9495 # Store this information here so that we can transfer96 # it to the new internal connection object after97 # the old one goes to 'SWITCHED_PROTOCOL'.98 # Note that the negotiated 'http_version' may change after the TLS upgrade.99 http_version = "HTTP/1.1"100 socket = h11_connection.socket101 on_release = h11_connection.on_release102103 if origin.is_ssl:104 # Pull the socket stream off the internal HTTP connection object,105 # and run start_tls().106 ssl_context = self.ssl.ssl_context107108 logger.trace(f"tunnel_start_tls proxy_url={proxy_url!r} origin={origin!r}")109 socket = await socket.start_tls(110 hostname=origin.host, ssl_context=ssl_context, timeout=timeout111 )112 http_version = socket.get_http_version()113 logger.trace(114 f"tunnel_tls_complete "115 f"proxy_url={proxy_url!r} "116 f"origin={origin!r} "117 f"http_version={http_version!r}"118 )119 else:120 # User requested the use of a tunnel, but they're performing a plain-text121 # HTTP request. Don't try to upgrade to TLS in this case.122 pass123124 if http_version == "HTTP/2":125 self.connection = HTTP2Connection(126 socket, self.backend, on_release=on_release127 )128 else:129 self.connection = HTTP11Connection(socket, on_release=on_release)130131 async def close(self) -> None:132 logger.trace("close_connection")133 if self.connection is not None:134 await self.connection.close()135136 @property137 def is_http2(self) -> bool:138 return self.connection is not None and self.connection.is_http2139140 @property141 def is_closed(self) -> bool:142 return self.connection is not None and self.connection.is_closed143144 def is_connection_dropped(self) -> bool:145 return self.connection is not None and self.connection.is_connection_dropped()146147 def __repr__(self) -> str:148 class_name = self.__class__.__name__149 return f"{class_name}(origin={self.origin!r})"
added:httpx/_dispatch/http11.py+206 added
1import typing23import h1145from .._backends.base import BaseSocketStream6from .._config import Timeout7from .._content_streams import AsyncIteratorStream8from .._exceptions import ConnectionClosed, ProtocolError9from .._models import Request, Response10from .._utils import get_logger1112H11Event = typing.Union[13 h11.Request,14 h11.Response,15 h11.InformationalResponse,16 h11.Data,17 h11.EndOfMessage,18 h11.ConnectionClosed,19]202122# Callback signature: async def callback() -> None23# In practice the callback will be a functools partial, which binds24# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.25OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]262728logger = get_logger(__name__)293031class HTTP11Connection:32 READ_NUM_BYTES = 40963334 def __init__(35 self,36 socket: BaseSocketStream,37 on_release: typing.Optional[OnReleaseCallback] = None,38 ):39 self.socket = socket40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)4243 @property44 def is_http2(self) -> bool:45 return False4647 async def send(self, request: Request, timeout: Timeout = None) -> Response:48 timeout = Timeout() if timeout is None else timeout4950 await self._send_request(request, timeout)51 await self._send_request_body(request, timeout)52 http_version, status_code, headers = await self._receive_response(timeout)53 stream = AsyncIteratorStream(54 aiterator=self._receive_response_data(timeout),55 close_func=self.response_closed,56 )5758 return Response(59 status_code=status_code,60 http_version=http_version,61 headers=headers,62 stream=stream,63 request=request,64 )6566 async def close(self) -> None:67 event = h11.ConnectionClosed()68 try:69 logger.trace(f"send_event event={event!r}")70 self.h11_state.send(event)71 except h11.LocalProtocolError: # pragma: no cover72 # Premature client disconnect73 pass74 await self.socket.close()7576 async def _send_request(self, request: Request, timeout: Timeout) -> None:77 """78 Send the request method, URL, and headers to the network.79 """80 logger.trace(81 f"send_headers method={request.method!r} "82 f"target={request.url.full_path!r} "83 f"headers={request.headers!r}"84 )8586 method = request.method.encode("ascii")87 target = request.url.full_path.encode("ascii")88 headers = request.headers.raw89 event = h11.Request(method=method, target=target, headers=headers)90 await self._send_event(event, timeout)9192 async def _send_request_body(self, request: Request, timeout: Timeout) -> None:93 """94 Send the request body to the network.95 """96 try:97 # Send the request body.98 async for chunk in request.stream:99 logger.trace(f"send_data data=Data(<{len(chunk)} bytes>)")100 event = h11.Data(data=chunk)101 await self._send_event(event, timeout)102103 # Finalize sending the request.104 event = h11.EndOfMessage()105 await self._send_event(event, timeout)106 except OSError: # pragma: nocover107 # Once we've sent the initial part of the request we don't actually108 # care about connection errors that occur when sending the body.109 # Ignore these, and defer to any exceptions on reading the response.110 self.h11_state.send_failed()111112 async def _send_event(self, event: H11Event, timeout: Timeout) -> None:113 """114 Send a single `h11` event to the network, waiting for the data to115 drain before returning.116 """117 bytes_to_send = self.h11_state.send(event)118 await self.socket.write(bytes_to_send, timeout)119120 async def _receive_response(121 self, timeout: Timeout122 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:123 """124 Read the response status and headers from the network.125 """126 while True:127 event = await self._receive_event(timeout)128 if isinstance(event, h11.InformationalResponse):129 continue130 else:131 assert isinstance(event, h11.Response)132 break # pragma: no cover133 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")134 return http_version, event.status_code, event.headers135136 async def _receive_response_data(137 self, timeout: Timeout138 ) -> typing.AsyncIterator[bytes]:139 """140 Read the response data from the network.141 """142 while True:143 event = await self._receive_event(timeout)144 if isinstance(event, h11.Data):145 yield bytes(event.data)146 else:147 assert isinstance(event, h11.EndOfMessage) or event is h11.PAUSED148 break # pragma: no cover149150 async def _receive_event(self, timeout: Timeout) -> H11Event:151 """152 Read a single `h11` event, reading more data from the network if needed.153 """154 while True:155 try:156 event = self.h11_state.next_event()157 except h11.RemoteProtocolError as e:158 logger.debug(159 "h11.RemoteProtocolError exception "160 + f"their_state={self.h11_state.their_state} "161 + f"error_status_hint={e.error_status_hint}"162 )163 if self.socket.is_connection_dropped():164 raise ConnectionClosed(e)165 raise ProtocolError(e)166167 if isinstance(event, h11.Data):168 logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")169 else:170 logger.trace(f"receive_event event={event!r}")171172 if event is h11.NEED_DATA:173 try:174 data = await self.socket.read(self.READ_NUM_BYTES, timeout)175 except OSError: # pragma: nocover176 data = b""177 self.h11_state.receive_data(data)178 else:179 assert event is not h11.NEED_DATA180 break # pragma: no cover181 return event182183 async def response_closed(self) -> None:184 logger.trace(185 f"response_closed "186 f"our_state={self.h11_state.our_state!r} "187 f"their_state={self.h11_state.their_state}"188 )189 if (190 self.h11_state.our_state is h11.DONE191 and self.h11_state.their_state is h11.DONE192 ):193 # Get ready for another request/response cycle.194 self.h11_state.start_next_cycle()195 else:196 await self.close()197198 if self.on_release is not None:199 await self.on_release()200201 @property202 def is_closed(self) -> bool:203 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)204205 def is_connection_dropped(self) -> bool:206 return self.socket.is_connection_dropped()
added:httpx/_dispatch/http2.py+298 added
1import typing23import h2.connection4import h2.events5from h2.config import H2Configuration6from h2.settings import SettingCodes, Settings78from .._backends.base import (9 BaseLock,10 BaseSocketStream,11 ConcurrencyBackend,12 lookup_backend,13)14from .._config import Timeout15from .._content_streams import AsyncIteratorStream16from .._exceptions import ProtocolError17from .._models import Request, Response18from .._utils import get_logger1920logger = get_logger(__name__)212223class HTTP2Connection:24 READ_NUM_BYTES = 409625 CONFIG = H2Configuration(validate_inbound_headers=False)2627 def __init__(28 self,29 socket: BaseSocketStream,30 backend: typing.Union[str, ConcurrencyBackend] = "auto",31 on_release: typing.Callable = None,32 ):33 self.socket = socket34 self.backend = lookup_backend(backend)35 self.on_release = on_release36 self.state = h2.connection.H2Connection(config=self.CONFIG)3738 self.streams = {} # type: typing.Dict[int, HTTP2Stream]39 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]4041 self.sent_connection_init = False4243 @property44 def is_http2(self) -> bool:45 return True4647 @property48 def init_lock(self) -> BaseLock:49 # We do this lazily, to make sure backend autodetection always50 # runs within an async context.51 if not hasattr(self, "_initialization_lock"):52 self._initialization_lock = self.backend.create_lock()53 return self._initialization_lock5455 async def send(self, request: Request, timeout: Timeout = None) -> Response:56 timeout = Timeout() if timeout is None else timeout5758 async with self.init_lock:59 if not self.sent_connection_init:60 # The very first stream is responsible for initiating the connection.61 await self.send_connection_init(timeout)62 self.sent_connection_init = True63 stream_id = self.state.get_next_available_stream_id()6465 stream = HTTP2Stream(stream_id=stream_id, connection=self)66 self.streams[stream_id] = stream67 self.events[stream_id] = []68 return await stream.send(request, timeout)6970 async def send_connection_init(self, timeout: Timeout) -> None:71 """72 The HTTP/2 connection requires some initial setup before we can start73 using individual request/response streams on it.74 """7576 # Need to set these manually here instead of manipulating via77 # __setitem__() otherwise the H2Connection will emit SettingsUpdate78 # frames in addition to sending the undesired defaults.79 self.state.local_settings = Settings(80 client=True,81 initial_values={82 # Disable PUSH_PROMISE frames from the server since we don't do anything83 # with them for now. Maybe when we support caching?84 SettingCodes.ENABLE_PUSH: 0,85 # These two are taken from h2 for safe defaults86 SettingCodes.MAX_CONCURRENT_STREAMS: 100,87 SettingCodes.MAX_HEADER_LIST_SIZE: 65536,88 },89 )9091 # Some websites (*cough* Yahoo *cough*) balk at this setting being92 # present in the initial handshake since it's not defined in the original93 # RFC despite the RFC mandating ignoring settings you don't know about.94 del self.state.local_settings[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL]9596 self.state.initiate_connection()97 self.state.increment_flow_control_window(2 ** 24)98 data_to_send = self.state.data_to_send()99 await self.socket.write(data_to_send, timeout)100101 @property102 def is_closed(self) -> bool:103 return False104105 def is_connection_dropped(self) -> bool:106 return self.socket.is_connection_dropped()107108 async def close(self) -> None:109 await self.socket.close()110111 async def wait_for_outgoing_flow(self, stream_id: int, timeout: Timeout) -> int:112 """113 Returns the maximum allowable outgoing flow for a given stream.114115 If the allowable flow is zero, then waits on the network until116 WindowUpdated frames have increased the flow rate.117118 https://tools.ietf.org/html/rfc7540#section-6.9119 """120 local_flow = self.state.local_flow_control_window(stream_id)121 connection_flow = self.state.max_outbound_frame_size122 flow = min(local_flow, connection_flow)123 while flow == 0:124 await self.receive_events(timeout)125 local_flow = self.state.local_flow_control_window(stream_id)126 connection_flow = self.state.max_outbound_frame_size127 flow = min(local_flow, connection_flow)128 return flow129130 async def wait_for_event(self, stream_id: int, timeout: Timeout) -> h2.events.Event:131 """132 Returns the next event for a given stream.133134 If no events are available yet, then waits on the network until135 an event is available.136 """137 while not self.events[stream_id]:138 await self.receive_events(timeout)139 return self.events[stream_id].pop(0)140141 async def receive_events(self, timeout: Timeout) -> None:142 """143 Read some data from the network, and update the H2 state.144 """145 data = await self.socket.read(self.READ_NUM_BYTES, timeout)146 events = self.state.receive_data(data)147 for event in events:148 event_stream_id = getattr(event, "stream_id", 0)149 logger.trace(f"receive_event stream_id={event_stream_id} event={event!r}")150151 if hasattr(event, "error_code"):152 raise ProtocolError(event)153154 if event_stream_id in self.events:155 self.events[event_stream_id].append(event)156157 data_to_send = self.state.data_to_send()158 await self.socket.write(data_to_send, timeout)159160 async def send_headers(161 self,162 stream_id: int,163 headers: typing.List[typing.Tuple[bytes, bytes]],164 end_stream: bool,165 timeout: Timeout,166 ) -> None:167 self.state.send_headers(stream_id, headers, end_stream=end_stream)168 self.state.increment_flow_control_window(2 ** 24, stream_id=stream_id)169 data_to_send = self.state.data_to_send()170 await self.socket.write(data_to_send, timeout)171172 async def send_data(self, stream_id: int, chunk: bytes, timeout: Timeout) -> None:173 self.state.send_data(stream_id, chunk)174 data_to_send = self.state.data_to_send()175 await self.socket.write(data_to_send, timeout)176177 async def end_stream(self, stream_id: int, timeout: Timeout) -> None:178 self.state.end_stream(stream_id)179 data_to_send = self.state.data_to_send()180 await self.socket.write(data_to_send, timeout)181182 async def acknowledge_received_data(183 self, stream_id: int, amount: int, timeout: Timeout184 ) -> None:185 self.state.acknowledge_received_data(amount, stream_id)186 data_to_send = self.state.data_to_send()187 await self.socket.write(data_to_send, timeout)188189 async def close_stream(self, stream_id: int) -> None:190 del self.streams[stream_id]191 del self.events[stream_id]192193 if not self.streams and self.on_release is not None:194 await self.on_release()195196197class HTTP2Stream:198 def __init__(self, stream_id: int, connection: HTTP2Connection) -> None:199 self.stream_id = stream_id200 self.connection = connection201202 async def send(self, request: Request, timeout: Timeout) -> Response:203 # Send the request.204 has_body = (205 "Content-Length" in request.headers206 or "Transfer-Encoding" in request.headers207 )208209 await self.send_headers(request, has_body, timeout)210 if has_body:211 await self.send_body(request, timeout)212213 # Receive the response.214 status_code, headers = await self.receive_response(timeout)215 stream = AsyncIteratorStream(216 aiterator=self.body_iter(timeout), close_func=self.close217 )218219 return Response(220 status_code=status_code,221 http_version="HTTP/2",222 headers=headers,223 stream=stream,224 request=request,225 )226227 async def send_headers(228 self, request: Request, has_body: bool, timeout: Timeout229 ) -> None:230 headers = [231 (b":method", request.method.encode("ascii")),232 (b":authority", request.url.authority.encode("ascii")),233 (b":scheme", request.url.scheme.encode("ascii")),234 (b":path", request.url.full_path.encode("ascii")),235 ] + [236 (k, v)237 for k, v in request.headers.raw238 if k not in (b"host", b"transfer-encoding")239 ]240 end_stream = not has_body241242 logger.trace(243 f"send_headers "244 f"stream_id={self.stream_id} "245 f"method={request.method!r} "246 f"target={request.url.full_path!r} "247 f"headers={headers!r}"248 )249 await self.connection.send_headers(self.stream_id, headers, end_stream, timeout)250251 async def send_body(self, request: Request, timeout: Timeout) -> None:252 logger.trace(f"send_body stream_id={self.stream_id}")253 async for data in request.stream:254 while data:255 max_flow = await self.connection.wait_for_outgoing_flow(256 self.stream_id, timeout257 )258 chunk_size = min(len(data), max_flow)259 chunk, data = data[:chunk_size], data[chunk_size:]260 await self.connection.send_data(self.stream_id, chunk, timeout)261262 await self.connection.end_stream(self.stream_id, timeout)263264 async def receive_response(265 self, timeout: Timeout266 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:267 """268 Read the response status and headers from the network.269 """270 while True:271 event = await self.connection.wait_for_event(self.stream_id, timeout)272 if isinstance(event, h2.events.ResponseReceived):273 break274275 status_code = 200276 headers = []277 for k, v in event.headers:278 if k == b":status":279 status_code = int(v.decode("ascii", errors="ignore"))280 elif not k.startswith(b":"):281 headers.append((k, v))282283 return (status_code, headers)284285 async def body_iter(self, timeout: Timeout) -> typing.AsyncIterator[bytes]:286 while True:287 event = await self.connection.wait_for_event(self.stream_id, timeout)288 if isinstance(event, h2.events.DataReceived):289 amount = event.flow_controlled_length290 await self.connection.acknowledge_received_data(291 self.stream_id, amount, timeout292 )293 yield event.data294 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):295 break296297 async def close(self) -> None:298 await self.connection.close_stream(self.stream_id)
added:httpx/_dispatch/proxy_http.py+208 added
1import enum2import typing3import warnings4from base64 import b64encode56from .._backends.base import ConcurrencyBackend7from .._config import (8 DEFAULT_POOL_LIMITS,9 CertTypes,10 PoolLimits,11 SSLConfig,12 Timeout,13 VerifyTypes,14)15from .._exceptions import ProxyError16from .._models import URL, Headers, HeaderTypes, Origin, Request, Response, URLTypes17from .._utils import get_logger18from .connection import HTTPConnection19from .connection_pool import ConnectionPool2021logger = get_logger(__name__)222324class HTTPProxyMode(enum.Enum):25 # This enum is pending deprecation in order to reduce API surface area,26 # but is currently still around for 0.8 backwards compat.27 DEFAULT = "DEFAULT"28 FORWARD_ONLY = "FORWARD_ONLY"29 TUNNEL_ONLY = "TUNNEL_ONLY"303132DEFAULT_MODE = "DEFAULT"33FORWARD_ONLY = "FORWARD_ONLY"34TUNNEL_ONLY = "TUNNEL_ONLY"353637class HTTPProxy(ConnectionPool):38 """A proxy that sends requests to the recipient server39 on behalf of the connecting client.40 """4142 def __init__(43 self,44 proxy_url: URLTypes,45 *,46 proxy_headers: HeaderTypes = None,47 proxy_mode: str = "DEFAULT",48 verify: VerifyTypes = True,49 cert: CertTypes = None,50 trust_env: bool = None,51 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,52 http2: bool = False,53 backend: typing.Union[str, ConcurrencyBackend] = "auto",54 ):5556 if isinstance(proxy_mode, HTTPProxyMode): # pragma: nocover57 warnings.warn(58 "The 'HTTPProxyMode' enum is pending deprecation. "59 "Use a plain string instead. proxy_mode='FORWARD_ONLY', or "60 "proxy_mode='TUNNEL_ONLY'."61 )62 proxy_mode = proxy_mode.value63 assert proxy_mode in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY")6465 self.tunnel_ssl = SSLConfig(66 verify=verify, cert=cert, trust_env=trust_env, http2=False67 )6869 super(HTTPProxy, self).__init__(70 verify=verify,71 cert=cert,72 pool_limits=pool_limits,73 backend=backend,74 trust_env=trust_env,75 http2=http2,76 )7778 self.proxy_url = URL(proxy_url)79 self.proxy_mode = proxy_mode80 self.proxy_headers = Headers(proxy_headers)8182 url = self.proxy_url83 if url.username or url.password:84 self.proxy_headers.setdefault(85 "Proxy-Authorization",86 self.build_auth_header(url.username, url.password),87 )88 # Remove userinfo from the URL authority, e.g.:89 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'90 credentials, _, authority = url.authority.rpartition("@")91 self.proxy_url = url.copy_with(authority=authority)9293 def build_auth_header(self, username: str, password: str) -> str:94 userpass = (username.encode("utf-8"), password.encode("utf-8"))95 token = b64encode(b":".join(userpass)).decode().strip()96 return f"Basic {token}"9798 async def acquire_connection(99 self, origin: Origin, timeout: Timeout = None100 ) -> HTTPConnection:101 if self.should_forward_origin(origin):102 logger.trace(103 f"forward_connection proxy_url={self.proxy_url!r} origin={origin!r}"104 )105 return await super().acquire_connection(Origin(self.proxy_url), timeout)106 else:107 logger.trace(108 f"tunnel_connection proxy_url={self.proxy_url!r} origin={origin!r}"109 )110 return await self.tunnel_connection(origin, timeout)111112 async def tunnel_connection(113 self, origin: Origin, timeout: Timeout = None114 ) -> HTTPConnection:115 """Creates a new HTTPConnection via the CONNECT method116 usually reserved for proxying HTTPS connections.117 """118 connection = self.pop_connection(origin)119120 if connection is None:121 connection = await self.request_tunnel_proxy_connection(origin)122123 # After we receive the 2XX response from the proxy that our124 # tunnel is open we switch the connection's origin125 # to the original so the tunnel can be re-used.126 self.active_connections.remove(connection)127 connection.origin = origin128 self.active_connections.add(connection)129130 await connection.tunnel_start_tls(131 origin=origin, proxy_url=self.proxy_url, timeout=timeout,132 )133 else:134 self.active_connections.add(connection)135136 return connection137138 async def request_tunnel_proxy_connection(self, origin: Origin) -> HTTPConnection:139 """Creates an HTTPConnection by setting up a TCP tunnel"""140 proxy_headers = self.proxy_headers.copy()141 proxy_headers.setdefault("Accept", "*/*")142 proxy_request = Request(143 method="CONNECT", url=self.proxy_url.copy_with(), headers=proxy_headers144 )145 proxy_request.url.full_path = f"{origin.host}:{origin.port}"146147 await self.max_connections.acquire()148149 connection = HTTPConnection(150 Origin(self.proxy_url),151 ssl=self.tunnel_ssl,152 backend=self.backend,153 release_func=self.release_connection,154 )155 self.active_connections.add(connection)156157 # See if our tunnel has been opened successfully158 proxy_response = await connection.send(proxy_request)159 logger.trace(160 f"tunnel_response "161 f"proxy_url={self.proxy_url!r} "162 f"origin={origin!r} "163 f"response={proxy_response!r}"164 )165 if not (200 <= proxy_response.status_code <= 299):166 await proxy_response.aread()167 raise ProxyError(168 f"Non-2XX response received from HTTP proxy "169 f"({proxy_response.status_code})",170 request=proxy_request,171 response=proxy_response,172 )173 else:174 # Hack to ingest the response, without closing it.175 async for chunk in proxy_response._raw_stream:176 pass177178 return connection179180 def should_forward_origin(self, origin: Origin) -> bool:181 """Determines if the given origin should182 be forwarded or tunneled. If 'proxy_mode' is 'DEFAULT'183 then the proxy will forward all 'HTTP' requests and184 tunnel all 'HTTPS' requests.185 """186 return (187 self.proxy_mode == DEFAULT_MODE and not origin.is_ssl188 ) or self.proxy_mode == FORWARD_ONLY189190 async def send(self, request: Request, timeout: Timeout = None) -> Response:191 if self.should_forward_origin(Origin(request.url)):192 # Change the request to have the target URL193 # as its full_path and switch the proxy URL194 # for where the request will be sent.195 target_url = str(request.url)196 request.url = self.proxy_url.copy_with()197 request.url.full_path = target_url198 for name, value in self.proxy_headers.items():199 request.headers.setdefault(name, value)200201 return await super().send(request=request, timeout=timeout)202203 def __repr__(self) -> str:204 return (205 f"HTTPProxy(proxy_url={self.proxy_url!r} "206 f"proxy_headers={self.proxy_headers!r} "207 f"proxy_mode={self.proxy_mode!r})"208 )
added:httpx/_dispatch/urllib3.py+128 added
1import math2import socket3import ssl4import typing56import urllib37from urllib3.exceptions import MaxRetryError, SSLError89from .._config import (10 DEFAULT_POOL_LIMITS,11 CertTypes,12 PoolLimits,13 Proxy,14 SSLConfig,15 Timeout,16 VerifyTypes,17)18from .._content_streams import IteratorStream19from .._models import Request, Response20from .._utils import as_network_error21from .base import SyncDispatcher222324class URLLib3Dispatcher(SyncDispatcher):25 def __init__(26 self,27 *,28 proxy: Proxy = None,29 verify: VerifyTypes = True,30 cert: CertTypes = None,31 trust_env: bool = None,32 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,33 ):34 ssl_config = SSLConfig(35 verify=verify, cert=cert, trust_env=trust_env, http2=False36 )37 hard_limit = pool_limits.hard_limit38 soft_limit = pool_limits.soft_limit3940 # Our connection pool configuration doesn't quite match up with urllib3's41 # controls, but we can put sensible mappings in place:42 if hard_limit is None:43 block = False44 if soft_limit is None:45 num_pools = 100046 maxsize = 100047 else:48 num_pools = int(math.sqrt(soft_limit))49 maxsize = int(math.sqrt(soft_limit))50 else:51 block = True52 num_pools = int(math.sqrt(hard_limit))53 maxsize = int(math.sqrt(hard_limit))5455 self.pool = self.init_pool_manager(56 proxy=proxy,57 ssl_context=ssl_config.ssl_context,58 num_pools=num_pools,59 maxsize=maxsize,60 block=block,61 )6263 def init_pool_manager(64 self,65 proxy: typing.Optional[Proxy],66 ssl_context: ssl.SSLContext,67 num_pools: int,68 maxsize: int,69 block: bool,70 ) -> typing.Union[urllib3.PoolManager, urllib3.ProxyManager]:71 if proxy is None:72 return urllib3.PoolManager(73 ssl_context=ssl_context,74 num_pools=num_pools,75 maxsize=maxsize,76 block=block,77 )78 else:79 return urllib3.ProxyManager(80 proxy_url=str(proxy.url),81 proxy_headers=dict(proxy.headers),82 ssl_context=ssl_context,83 num_pools=num_pools,84 maxsize=maxsize,85 block=block,86 )8788 def send(self, request: Request, timeout: Timeout = None) -> Response:89 timeout = Timeout() if timeout is None else timeout90 urllib3_timeout = urllib3.util.Timeout(91 connect=timeout.connect_timeout, read=timeout.read_timeout92 )93 chunked = request.headers.get("Transfer-Encoding") == "chunked"94 content_length = int(request.headers.get("Content-Length", "0"))95 body = request.stream if chunked or content_length else None9697 with as_network_error(MaxRetryError, SSLError, socket.error):98 conn = self.pool.urlopen(99 method=request.method,100 url=str(request.url),101 headers=dict(request.headers),102 body=body,103 redirect=False,104 assert_same_host=False,105 retries=0,106 preload_content=False,107 chunked=chunked,108 timeout=urllib3_timeout,109 pool_timeout=timeout.pool_timeout,110 )111112 def response_bytes() -> typing.Iterator[bytes]:113 with as_network_error(socket.error):114 for chunk in conn.stream(4096, decode_content=False):115 yield chunk116117 return Response(118 status_code=conn.status,119 http_version="HTTP/1.1",120 headers=list(conn.headers.items()),121 stream=IteratorStream(122 iterator=response_bytes(), close_func=conn.release_conn123 ),124 request=request,125 )126127 def close(self) -> None:128 self.pool.clear()
added:httpx/_dispatch/wsgi.py+103 added
1import io2import typing34from .._config import TimeoutTypes5from .._content_streams import IteratorStream6from .._models import Request, Response7from .base import SyncDispatcher8910class WSGIDispatch(SyncDispatcher):11 """12 A custom SyncDispatcher that handles sending requests directly to an WSGI app.13 The simplest way to use this functionality is to use the `app` argument.1415 ```16 client = httpx.Client(app=app)17 ```1819 Alternatively, you can setup the dispatch instance explicitly.20 This allows you to include any additional configuration arguments specific21 to the WSGIDispatch class:2223 ```24 dispatch = httpx.WSGIDispatch(25 app=app,26 script_name="/submount",27 remote_addr="1.2.3.4"28 )29 client = httpx.Client(dispatch=dispatch)30 ```3132 Arguments:3334 * `app` - The ASGI application.35 * `raise_app_exceptions` - Boolean indicating if exceptions in the application36 should be raised. Default to `True`. Can be set to `False` for use cases37 such as testing the content of a client 500 response.38 * `script_name` - The root path on which the ASGI application should be mounted.39 * `remote_addr` - A string indicating the client IP of incoming requests.40 ```41 """4243 def __init__(44 self,45 app: typing.Callable,46 raise_app_exceptions: bool = True,47 script_name: str = "",48 remote_addr: str = "127.0.0.1",49 ) -> None:50 self.app = app51 self.raise_app_exceptions = raise_app_exceptions52 self.script_name = script_name53 self.remote_addr = remote_addr5455 def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:56 environ = {57 "wsgi.version": (1, 0),58 "wsgi.url_scheme": request.url.scheme,59 "wsgi.input": io.BytesIO(request.read()),60 "wsgi.errors": io.BytesIO(),61 "wsgi.multithread": True,62 "wsgi.multiprocess": False,63 "wsgi.run_once": False,64 "REQUEST_METHOD": request.method,65 "SCRIPT_NAME": self.script_name,66 "PATH_INFO": request.url.path,67 "QUERY_STRING": request.url.query,68 "SERVER_NAME": request.url.host,69 "SERVER_PORT": str(request.url.port),70 "REMOTE_ADDR": self.remote_addr,71 }72 for key, value in request.headers.items():73 key = key.upper().replace("-", "_")74 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):75 key = "HTTP_" + key76 environ[key] = value7778 seen_status = None79 seen_response_headers = None80 seen_exc_info = None8182 def start_response(83 status: str, response_headers: list, exc_info: typing.Any = None84 ) -> None:85 nonlocal seen_status, seen_response_headers, seen_exc_info86 seen_status = status87 seen_response_headers = response_headers88 seen_exc_info = exc_info8990 result = self.app(environ, start_response)9192 assert seen_status is not None93 assert seen_response_headers is not None94 if seen_exc_info and self.raise_app_exceptions:95 raise seen_exc_info[1]9697 return Response(98 status_code=int(seen_status.split()[0]),99 http_version="HTTP/1.1",100 headers=seen_response_headers,101 stream=IteratorStream(chunk for chunk in result),102 request=request,103 )
deleted:httpx/backends/__init__.py
deleted:httpx/backends/asyncio.py-268 removed
1import asyncio2import ssl3import typing45from ..config import Timeout6from ..exceptions import ConnectTimeout, ReadTimeout, WriteTimeout7from ..utils import as_network_error8from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend910SSL_MONKEY_PATCH_APPLIED = False111213def ssl_monkey_patch() -> None:14 """15 Monkey-patch for https://bugs.python.org/issue367091617 This prevents console errors when outstanding HTTPS connections18 still exist at the point of exiting.1920 Clients which have been opened using a `with` block, or which have21 had `close()` closed, will not exhibit this issue in the first place.22 """23 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore2425 _write = MonkeyPatch.write2627 def _fixed_write(self, data: bytes) -> None: # type: ignore28 if self._loop and not self._loop.is_closed():29 _write(self, data)3031 MonkeyPatch.write = _fixed_write323334async def backport_start_tls(35 transport: asyncio.BaseTransport,36 protocol: asyncio.BaseProtocol,37 sslcontext: ssl.SSLContext = None,38 *,39 server_side: bool = False,40 server_hostname: str = None,41 ssl_handshake_timeout: float = None,42) -> asyncio.Transport: # pragma: nocover (Since it's not used on all Python versions.)43 """44 Python 3.6 asyncio doesn't have a start_tls() method on the loop45 so we use this function in place of the loop's start_tls() method.4647 Adapted from this comment:4849 https://github.com/urllib3/urllib3/issues/1323#issuecomment-36249483950 """51 import asyncio.sslproto5253 loop = asyncio.get_event_loop()54 waiter = loop.create_future()55 ssl_protocol = asyncio.sslproto.SSLProtocol(56 loop,57 protocol,58 sslcontext,59 waiter,60 server_side=False,61 server_hostname=server_hostname,62 call_connection_made=False,63 )6465 transport.set_protocol(ssl_protocol)66 loop.call_soon(ssl_protocol.connection_made, transport)67 loop.call_soon(transport.resume_reading) # type: ignore6869 await waiter70 return ssl_protocol._app_transport717273class SocketStream(BaseSocketStream):74 def __init__(75 self, stream_reader: asyncio.StreamReader, stream_writer: asyncio.StreamWriter,76 ):77 self.stream_reader = stream_reader78 self.stream_writer = stream_writer79 self.read_lock = asyncio.Lock()80 self.write_lock = asyncio.Lock()8182 self._inner: typing.Optional[SocketStream] = None8384 async def start_tls(85 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout86 ) -> "SocketStream":87 loop = asyncio.get_event_loop()8889 stream_reader = asyncio.StreamReader()90 protocol = asyncio.StreamReaderProtocol(stream_reader)91 transport = self.stream_writer.transport9293 loop_start_tls = getattr(loop, "start_tls", backport_start_tls)9495 transport = await asyncio.wait_for(96 loop_start_tls(97 transport=transport,98 protocol=protocol,99 sslcontext=ssl_context,100 server_hostname=hostname,101 ),102 timeout=timeout.connect_timeout,103 )104105 stream_reader.set_transport(transport)106 stream_writer = asyncio.StreamWriter(107 transport=transport, protocol=protocol, reader=stream_reader, loop=loop108 )109110 ssl_stream = SocketStream(stream_reader, stream_writer)111 # When we return a new SocketStream with new StreamReader/StreamWriter instances112 # we need to keep references to the old StreamReader/StreamWriter so that they113 # are not garbage collected and closed while we're still using them.114 ssl_stream._inner = self115 return ssl_stream116117 def get_http_version(self) -> str:118 ssl_object = self.stream_writer.get_extra_info("ssl_object")119120 if ssl_object is None:121 return "HTTP/1.1"122123 ident = ssl_object.selected_alpn_protocol()124 return "HTTP/2" if ident == "h2" else "HTTP/1.1"125126 async def read(self, n: int, timeout: Timeout) -> bytes:127 try:128 async with self.read_lock:129 with as_network_error(OSError):130 return await asyncio.wait_for(131 self.stream_reader.read(n), timeout.read_timeout132 )133 except asyncio.TimeoutError:134 raise ReadTimeout() from None135136 async def write(self, data: bytes, timeout: Timeout) -> None:137 if not data:138 return139140 try:141 async with self.write_lock:142 with as_network_error(OSError):143 self.stream_writer.write(data)144 return await asyncio.wait_for(145 self.stream_writer.drain(), timeout.write_timeout146 )147 except asyncio.TimeoutError:148 raise WriteTimeout() from None149150 def is_connection_dropped(self) -> bool:151 # Counter-intuitively, what we really want to know here is whether the socket is152 # *readable*, i.e. whether it would return immediately with empty bytes if we153 # called `.recv()` on it, indicating that the other end has closed the socket.154 # See: https://github.com/encode/httpx/pull/143#issuecomment-515181778155 #156 # As it turns out, asyncio checks for readability in the background157 # (see: https://github.com/encode/httpx/pull/276#discussion_r322000402),158 # so checking for EOF or readability here would yield the same result.159 #160 # At the cost of rigour, we check for EOF instead of readability because asyncio161 # does not expose any public API to check for readability.162 # (For a solution that uses private asyncio APIs, see:163 # https://github.com/encode/httpx/pull/143#issuecomment-515202982)164165 return self.stream_reader.at_eof()166167 async def close(self) -> None:168 # NOTE: StreamWriter instances expose a '.wait_closed()' coroutine function,169 # but using it has caused compatibility issues with certain sites in170 # the past (see https://github.com/encode/httpx/issues/634), which is171 # why we don't call it here.172 # This is fine, though, because '.close()' schedules the actual closing of the173 # stream, meaning that at best it will happen during the next event loop174 # iteration, and at worst asyncio will take care of it on program exit.175 async with self.write_lock:176 with as_network_error(OSError):177 self.stream_writer.close()178179180class AsyncioBackend(ConcurrencyBackend):181 def __init__(self) -> None:182 global SSL_MONKEY_PATCH_APPLIED183184 if not SSL_MONKEY_PATCH_APPLIED:185 ssl_monkey_patch()186 SSL_MONKEY_PATCH_APPLIED = True187188 async def open_tcp_stream(189 self,190 hostname: str,191 port: int,192 ssl_context: typing.Optional[ssl.SSLContext],193 timeout: Timeout,194 ) -> SocketStream:195 try:196 with as_network_error(OSError):197 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore198 asyncio.open_connection(hostname, port, ssl=ssl_context),199 timeout.connect_timeout,200 )201 except asyncio.TimeoutError:202 raise ConnectTimeout()203204 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)205206 async def open_uds_stream(207 self,208 path: str,209 hostname: typing.Optional[str],210 ssl_context: typing.Optional[ssl.SSLContext],211 timeout: Timeout,212 ) -> SocketStream:213 server_hostname = hostname if ssl_context else None214215 try:216 with as_network_error(OSError):217 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore218 asyncio.open_unix_connection(219 path, ssl=ssl_context, server_hostname=server_hostname220 ),221 timeout.connect_timeout,222 )223 except asyncio.TimeoutError:224 raise ConnectTimeout()225226 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)227228 def time(self) -> float:229 loop = asyncio.get_event_loop()230 return loop.time()231232 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:233 return Semaphore(max_value, exc_class)234235 def create_lock(self) -> BaseLock:236 return Lock()237238239class Lock(BaseLock):240 def __init__(self) -> None:241 self._lock = asyncio.Lock()242243 def release(self) -> None:244 self._lock.release()245246 async def acquire(self) -> None:247 await self._lock.acquire()248249250class Semaphore(BaseSemaphore):251 def __init__(self, max_value: int, exc_class: type) -> None:252 self.max_value = max_value253 self.exc_class = exc_class254255 @property256 def semaphore(self) -> asyncio.BoundedSemaphore:257 if not hasattr(self, "_semaphore"):258 self._semaphore = asyncio.BoundedSemaphore(value=self.max_value)259 return self._semaphore260261 async def acquire(self, timeout: float = None) -> None:262 try:263 await asyncio.wait_for(self.semaphore.acquire(), timeout)264 except asyncio.TimeoutError:265 raise self.exc_class()266267 def release(self) -> None:268 self.semaphore.release()
deleted:httpx/backends/auto.py-51 removed
1import ssl2import typing34import sniffio56from ..config import Timeout7from .base import (8 BaseLock,9 BaseSemaphore,10 BaseSocketStream,11 ConcurrencyBackend,12 lookup_backend,13)141516class AutoBackend(ConcurrencyBackend):17 @property18 def backend(self) -> ConcurrencyBackend:19 if not hasattr(self, "_backend_implementation"):20 backend = sniffio.current_async_library()21 if backend not in ("asyncio", "trio"): # pragma: nocover22 raise RuntimeError(f"Unsupported concurrency backend {backend!r}")23 self._backend_implementation = lookup_backend(backend)24 return self._backend_implementation2526 async def open_tcp_stream(27 self,28 hostname: str,29 port: int,30 ssl_context: typing.Optional[ssl.SSLContext],31 timeout: Timeout,32 ) -> BaseSocketStream:33 return await self.backend.open_tcp_stream(hostname, port, ssl_context, timeout)3435 async def open_uds_stream(36 self,37 path: str,38 hostname: typing.Optional[str],39 ssl_context: typing.Optional[ssl.SSLContext],40 timeout: Timeout,41 ) -> BaseSocketStream:42 return await self.backend.open_uds_stream(path, hostname, ssl_context, timeout)4344 def time(self) -> float:45 return self.backend.time()4647 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:48 return self.backend.create_semaphore(max_value, exc_class)4950 def create_lock(self) -> BaseLock:51 return self.backend.create_lock()
deleted:httpx/backends/base.py-121 removed
1import ssl2import typing3from types import TracebackType45from ..config import Timeout678def lookup_backend(9 backend: typing.Union[str, "ConcurrencyBackend"] = "auto"10) -> "ConcurrencyBackend":11 if not isinstance(backend, str):12 return backend1314 if backend == "auto":15 from .auto import AutoBackend1617 return AutoBackend()18 elif backend == "asyncio":19 from .asyncio import AsyncioBackend2021 return AsyncioBackend()22 elif backend == "trio":23 from .trio import TrioBackend2425 return TrioBackend()2627 raise RuntimeError(f"Unknown or unsupported concurrency backend {backend!r}")282930class BaseSocketStream:31 """32 A socket stream with read/write operations. Abstracts away any asyncio-specific33 interfaces into a more generic base class, that we can use with alternate34 backends, or for stand-alone test cases.35 """3637 def get_http_version(self) -> str:38 raise NotImplementedError() # pragma: no cover3940 async def start_tls(41 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout42 ) -> "BaseSocketStream":43 raise NotImplementedError() # pragma: no cover4445 async def read(self, n: int, timeout: Timeout) -> bytes:46 raise NotImplementedError() # pragma: no cover4748 async def write(self, data: bytes, timeout: Timeout) -> None:49 raise NotImplementedError() # pragma: no cover5051 async def close(self) -> None:52 raise NotImplementedError() # pragma: no cover5354 def is_connection_dropped(self) -> bool:55 raise NotImplementedError() # pragma: no cover565758class BaseLock:59 """60 An abstract interface for Lock classes.61 Abstracts away any asyncio-specific interfaces.62 """6364 async def __aenter__(self) -> None:65 await self.acquire()6667 async def __aexit__(68 self,69 exc_type: typing.Type[BaseException] = None,70 exc_value: BaseException = None,71 traceback: TracebackType = None,72 ) -> None:73 self.release()7475 def release(self) -> None:76 raise NotImplementedError() # pragma: no cover7778 async def acquire(self) -> None:79 raise NotImplementedError() # pragma: no cover808182class BaseSemaphore:83 """84 An abstract interface for Semaphore classes.85 Abstracts away any asyncio-specific interfaces.86 """8788 async def acquire(self, timeout: float = None) -> None:89 raise NotImplementedError() # pragma: no cover9091 def release(self) -> None:92 raise NotImplementedError() # pragma: no cover939495class ConcurrencyBackend:96 async def open_tcp_stream(97 self,98 hostname: str,99 port: int,100 ssl_context: typing.Optional[ssl.SSLContext],101 timeout: Timeout,102 ) -> BaseSocketStream:103 raise NotImplementedError() # pragma: no cover104105 async def open_uds_stream(106 self,107 path: str,108 hostname: typing.Optional[str],109 ssl_context: typing.Optional[ssl.SSLContext],110 timeout: Timeout,111 ) -> BaseSocketStream:112 raise NotImplementedError() # pragma: no cover113114 def time(self) -> float:115 raise NotImplementedError() # pragma: no cover116117 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:118 raise NotImplementedError() # pragma: no cover119120 def create_lock(self) -> BaseLock:121 raise NotImplementedError() # pragma: no cover
deleted:httpx/backends/trio.py-176 removed
1import ssl2import typing34import trio56from ..config import Timeout7from ..exceptions import ConnectTimeout, ReadTimeout, WriteTimeout8from ..utils import as_network_error9from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend101112def none_as_inf(value: typing.Optional[float]) -> float:13 return value if value is not None else float("inf")141516class SocketStream(BaseSocketStream):17 def __init__(18 self, stream: typing.Union[trio.SocketStream, trio.SSLStream],19 ) -> None:20 self.stream = stream21 self.read_lock = trio.Lock()22 self.write_lock = trio.Lock()2324 async def start_tls(25 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout26 ) -> "SocketStream":27 connect_timeout = none_as_inf(timeout.connect_timeout)28 ssl_stream = trio.SSLStream(29 self.stream, ssl_context=ssl_context, server_hostname=hostname30 )3132 with trio.move_on_after(connect_timeout):33 with as_network_error(trio.BrokenResourceError):34 await ssl_stream.do_handshake()35 return SocketStream(ssl_stream)3637 raise ConnectTimeout()3839 def get_http_version(self) -> str:40 if not isinstance(self.stream, trio.SSLStream):41 return "HTTP/1.1"4243 ident = self.stream.selected_alpn_protocol()44 return "HTTP/2" if ident == "h2" else "HTTP/1.1"4546 async def read(self, n: int, timeout: Timeout) -> bytes:47 read_timeout = none_as_inf(timeout.read_timeout)4849 with trio.move_on_after(read_timeout):50 async with self.read_lock:51 with as_network_error(trio.BrokenResourceError):52 return await self.stream.receive_some(max_bytes=n)5354 raise ReadTimeout()5556 async def write(self, data: bytes, timeout: Timeout) -> None:57 if not data:58 return5960 write_timeout = none_as_inf(timeout.write_timeout)6162 with trio.move_on_after(write_timeout):63 async with self.write_lock:64 with as_network_error(trio.BrokenResourceError):65 return await self.stream.send_all(data)6667 raise WriteTimeout()6869 def is_connection_dropped(self) -> bool:70 # Adapted from: https://github.com/encode/httpx/pull/143#issuecomment-51520298271 stream = self.stream7273 # Peek through any SSLStream wrappers to get the underlying SocketStream.74 while hasattr(stream, "transport_stream"):75 stream = stream.transport_stream76 assert isinstance(stream, trio.SocketStream)7778 # Counter-intuitively, what we really want to know here is whether the socket is79 # *readable*, i.e. whether it would return immediately with empty bytes if we80 # called `.recv()` on it, indicating that the other end has closed the socket.81 # See: https://github.com/encode/httpx/pull/143#issuecomment-51518177882 return stream.socket.is_readable()8384 async def close(self) -> None:85 async with self.write_lock:86 await self.stream.aclose()878889class TrioBackend(ConcurrencyBackend):90 async def open_tcp_stream(91 self,92 hostname: str,93 port: int,94 ssl_context: typing.Optional[ssl.SSLContext],95 timeout: Timeout,96 ) -> SocketStream:97 connect_timeout = none_as_inf(timeout.connect_timeout)9899 with trio.move_on_after(connect_timeout):100 with as_network_error(OSError):101 stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)102103 if ssl_context is not None:104 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)105 with as_network_error(trio.BrokenResourceError):106 await stream.do_handshake()107108 return SocketStream(stream=stream)109110 raise ConnectTimeout()111112 async def open_uds_stream(113 self,114 path: str,115 hostname: typing.Optional[str],116 ssl_context: typing.Optional[ssl.SSLContext],117 timeout: Timeout,118 ) -> SocketStream:119 connect_timeout = none_as_inf(timeout.connect_timeout)120121 with trio.move_on_after(connect_timeout):122 with as_network_error(OSError):123 stream: trio.SocketStream = await trio.open_unix_socket(path)124125 if ssl_context is not None:126 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)127 with as_network_error(trio.BrokenResourceError):128 await stream.do_handshake()129130 return SocketStream(stream=stream)131132 raise ConnectTimeout()133134 def time(self) -> float:135 return trio.current_time()136137 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:138 return Semaphore(max_value, exc_class)139140 def create_lock(self) -> BaseLock:141 return Lock()142143144class Semaphore(BaseSemaphore):145 def __init__(self, max_value: int, exc_class: type):146 self.max_value = max_value147 self.exc_class = exc_class148149 @property150 def semaphore(self) -> trio.Semaphore:151 if not hasattr(self, "_semaphore"):152 self._semaphore = trio.Semaphore(self.max_value, max_value=self.max_value)153 return self._semaphore154155 async def acquire(self, timeout: float = None) -> None:156 timeout = none_as_inf(timeout)157158 with trio.move_on_after(timeout):159 await self.semaphore.acquire()160 return161162 raise self.exc_class()163164 def release(self) -> None:165 self.semaphore.release()166167168class Lock(BaseLock):169 def __init__(self) -> None:170 self._lock = trio.Lock()171172 def release(self) -> None:173 self._lock.release()174175 async def acquire(self) -> None:176 await self._lock.acquire()
deleted:httpx/dispatch/__init__.py
deleted:httpx/dispatch/asgi.py-123 removed
1import typing23from ..config import TimeoutTypes4from ..content_streams import ByteStream5from ..models import Request, Response6from .base import AsyncDispatcher789class ASGIDispatch(AsyncDispatcher):10 """11 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.12 The simplest way to use this functionality is to use the `app` argument.1314 ```15 client = httpx.AsyncClient(app=app)16 ```1718 Alternatively, you can setup the dispatch instance explicitly.19 This allows you to include any additional configuration arguments specific20 to the ASGIDispatch class:2122 ```23 dispatch = httpx.ASGIDispatch(24 app=app,25 root_path="/submount",26 client=("1.2.3.4", 123)27 )28 client = httpx.AsyncClient(dispatch=dispatch)29 ```3031 Arguments:3233 * `app` - The ASGI application.34 * `raise_app_exceptions` - Boolean indicating if exceptions in the application35 should be raised. Default to `True`. Can be set to `False` for use cases36 such as testing the content of a client 500 response.37 * `root_path` - The root path on which the ASGI application should be mounted.38 * `client` - A two-tuple indicating the client IP and port of incoming requests.39 ```40 """4142 def __init__(43 self,44 app: typing.Callable,45 raise_app_exceptions: bool = True,46 root_path: str = "",47 client: typing.Tuple[str, int] = ("127.0.0.1", 123),48 ) -> None:49 self.app = app50 self.raise_app_exceptions = raise_app_exceptions51 self.root_path = root_path52 self.client = client5354 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:55 scope = {56 "type": "http",57 "asgi": {"version": "3.0"},58 "http_version": "1.1",59 "method": request.method,60 "headers": request.headers.raw,61 "scheme": request.url.scheme,62 "path": request.url.path,63 "query_string": request.url.query.encode("ascii"),64 "server": request.url.host,65 "client": self.client,66 "root_path": self.root_path,67 }68 status_code = None69 headers = None70 body_parts = []71 response_started = False72 response_complete = False7374 request_body_chunks = request.stream.__aiter__()7576 async def receive() -> dict:77 try:78 body = await request_body_chunks.__anext__()79 except StopAsyncIteration:80 return {"type": "http.request", "body": b"", "more_body": False}81 return {"type": "http.request", "body": body, "more_body": True}8283 async def send(message: dict) -> None:84 nonlocal status_code, headers, body_parts85 nonlocal response_started, response_complete8687 if message["type"] == "http.response.start":88 assert not response_started8990 status_code = message["status"]91 headers = message.get("headers", [])92 response_started = True9394 elif message["type"] == "http.response.body":95 assert not response_complete96 body = message.get("body", b"")97 more_body = message.get("more_body", False)9899 if body and request.method != "HEAD":100 body_parts.append(body)101102 if not more_body:103 response_complete = True104105 try:106 await self.app(scope, receive, send)107 except Exception:108 if self.raise_app_exceptions or not response_complete:109 raise110111 assert response_complete112 assert status_code is not None113 assert headers is not None114115 stream = ByteStream(b"".join(body_parts))116117 return Response(118 status_code=status_code,119 http_version="HTTP/1.1",120 headers=headers,121 stream=stream,122 request=request,123 )
deleted:httpx/dispatch/base.py-64 removed
1import typing2from types import TracebackType34from ..config import Timeout5from ..models import (6 HeaderTypes,7 QueryParamTypes,8 Request,9 RequestData,10 Response,11 URLTypes,12)131415class SyncDispatcher:16 """17 Base class for Dispatcher classes, that handle sending the request.18 """1920 def send(self, request: Request, timeout: Timeout = None) -> Response:21 raise NotImplementedError() # pragma: nocover2223 def close(self) -> None:24 pass # pragma: nocover252627class AsyncDispatcher:28 """29 Base class for AsyncDispatcher classes, that handle sending the request.3031 Stubs out the interface, as well as providing a `.request()` convenience32 implementation, to make it easy to use or test stand-alone AsyncDispatchers,33 without requiring a complete `AsyncClient` instance.34 """3536 async def request(37 self,38 method: str,39 url: URLTypes,40 *,41 data: RequestData = b"",42 params: QueryParamTypes = None,43 headers: HeaderTypes = None,44 timeout: Timeout = None,45 ) -> Response:46 request = Request(method, url, data=data, params=params, headers=headers)47 return await self.send(request, timeout=timeout)4849 async def send(self, request: Request, timeout: Timeout = None) -> Response:50 raise NotImplementedError() # pragma: nocover5152 async def close(self) -> None:53 pass # pragma: nocover5455 async def __aenter__(self) -> "AsyncDispatcher":56 return self5758 async def __aexit__(59 self,60 exc_type: typing.Type[BaseException] = None,61 exc_value: BaseException = None,62 traceback: TracebackType = None,63 ) -> None:64 await self.close()
deleted:httpx/dispatch/connection_pool.py-221 removed
1import typing23from ..backends.base import BaseSemaphore, ConcurrencyBackend, lookup_backend4from ..config import (5 DEFAULT_POOL_LIMITS,6 CertTypes,7 PoolLimits,8 SSLConfig,9 Timeout,10 VerifyTypes,11)12from ..exceptions import PoolTimeout13from ..models import Origin, Request, Response14from ..utils import get_logger15from .base import AsyncDispatcher16from .connection import HTTPConnection1718CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]192021logger = get_logger(__name__)222324class NullSemaphore(BaseSemaphore):25 async def acquire(self, timeout: float = None) -> None:26 return2728 def release(self) -> None:29 return303132class ConnectionStore:33 """34 We need to maintain collections of connections in a way that allows us to:3536 * Lookup connections by origin.37 * Iterate over connections by insertion time.38 * Return the total number of connections.39 """4041 def __init__(self) -> None:42 self.all: typing.Dict[HTTPConnection, float] = {}43 self.by_origin: typing.Dict[Origin, typing.Dict[HTTPConnection, float]] = {}4445 def pop_by_origin(46 self, origin: Origin, http2_only: bool = False47 ) -> typing.Optional[HTTPConnection]:48 try:49 connections = self.by_origin[origin]50 except KeyError:51 return None5253 connection = next(reversed(list(connections.keys())))54 if http2_only and not connection.is_http2:55 return None5657 del connections[connection]58 if not connections:59 del self.by_origin[origin]60 del self.all[connection]6162 return connection6364 def add(self, connection: HTTPConnection) -> None:65 self.all[connection] = 0.066 try:67 self.by_origin[connection.origin][connection] = 0.068 except KeyError:69 self.by_origin[connection.origin] = {connection: 0.0}7071 def remove(self, connection: HTTPConnection) -> None:72 del self.all[connection]73 del self.by_origin[connection.origin][connection]74 if not self.by_origin[connection.origin]:75 del self.by_origin[connection.origin]7677 def clear(self) -> None:78 self.all.clear()79 self.by_origin.clear()8081 def __iter__(self) -> typing.Iterator[HTTPConnection]:82 return iter(self.all.keys())8384 def __len__(self) -> int:85 return len(self.all)868788class ConnectionPool(AsyncDispatcher):89 KEEP_ALIVE_EXPIRY = 5.09091 def __init__(92 self,93 *,94 verify: VerifyTypes = True,95 cert: CertTypes = None,96 trust_env: bool = None,97 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,98 http2: bool = False,99 backend: typing.Union[str, ConcurrencyBackend] = "auto",100 uds: typing.Optional[str] = None,101 ):102 self.ssl = SSLConfig(verify=verify, cert=cert, trust_env=trust_env, http2=http2)103 self.pool_limits = pool_limits104 self.is_closed = False105 self.uds = uds106107 self.keepalive_connections = ConnectionStore()108 self.active_connections = ConnectionStore()109110 self.backend = lookup_backend(backend)111 self.next_keepalive_check = 0.0112113 @property114 def max_connections(self) -> BaseSemaphore:115 # We do this lazily, to make sure backend autodetection always116 # runs within an async context.117 if not hasattr(self, "_max_connections"):118 limit = self.pool_limits.hard_limit119 if limit:120 self._max_connections = self.backend.create_semaphore(121 limit, exc_class=PoolTimeout122 )123 else:124 self._max_connections = NullSemaphore()125126 return self._max_connections127128 @property129 def num_connections(self) -> int:130 return len(self.keepalive_connections) + len(self.active_connections)131132 async def check_keepalive_expiry(self) -> None:133 now = self.backend.time()134 if now < self.next_keepalive_check:135 return136 self.next_keepalive_check = now + 1.0137138 # Iterate through all the keep alive connections.139 # We create a list here to avoid any 'changed during iteration' errors.140 keepalives = list(self.keepalive_connections.all.keys())141 for connection in keepalives:142 if connection.expires_at is not None and now > connection.expires_at:143 self.keepalive_connections.remove(connection)144 self.max_connections.release()145 await connection.close()146147 async def send(self, request: Request, timeout: Timeout = None) -> Response:148 await self.check_keepalive_expiry()149 connection = await self.acquire_connection(150 origin=Origin(request.url), timeout=timeout151 )152 try:153 response = await connection.send(request, timeout=timeout)154 except BaseException as exc:155 self.active_connections.remove(connection)156 self.max_connections.release()157 raise exc158159 return response160161 async def acquire_connection(162 self, origin: Origin, timeout: Timeout = None163 ) -> HTTPConnection:164 logger.trace(f"acquire_connection origin={origin!r}")165 connection = self.pop_connection(origin)166167 if connection is None:168 pool_timeout = None if timeout is None else timeout.pool_timeout169170 await self.max_connections.acquire(timeout=pool_timeout)171 connection = HTTPConnection(172 origin,173 ssl=self.ssl,174 backend=self.backend,175 release_func=self.release_connection,176 uds=self.uds,177 )178 logger.trace(f"new_connection connection={connection!r}")179 else:180 logger.trace(f"reuse_connection connection={connection!r}")181182 self.active_connections.add(connection)183184 return connection185186 async def release_connection(self, connection: HTTPConnection) -> None:187 logger.trace(f"release_connection connection={connection!r}")188 if connection.is_closed:189 self.active_connections.remove(connection)190 self.max_connections.release()191 elif (192 self.pool_limits.soft_limit is not None193 and self.num_connections > self.pool_limits.soft_limit194 ):195 self.active_connections.remove(connection)196 self.max_connections.release()197 await connection.close()198 else:199 now = self.backend.time()200 connection.expires_at = now + self.KEEP_ALIVE_EXPIRY201 self.active_connections.remove(connection)202 self.keepalive_connections.add(connection)203204 async def close(self) -> None:205 self.is_closed = True206 connections = list(self.keepalive_connections)207 self.keepalive_connections.clear()208 for connection in connections:209 self.max_connections.release()210 await connection.close()211212 def pop_connection(self, origin: Origin) -> typing.Optional[HTTPConnection]:213 connection = self.active_connections.pop_by_origin(origin, http2_only=True)214 if connection is None:215 connection = self.keepalive_connections.pop_by_origin(origin)216217 if connection is not None and connection.is_connection_dropped():218 self.max_connections.release()219 connection = None220221 return connection
deleted:httpx/dispatch/connection.py-149 removed
1import functools2import typing34import h1156from ..backends.base import ConcurrencyBackend, lookup_backend7from ..config import SSLConfig, Timeout8from ..models import URL, Origin, Request, Response9from ..utils import get_logger10from .base import AsyncDispatcher11from .http2 import HTTP2Connection12from .http11 import HTTP11Connection1314# Callback signature: async def callback(conn: HTTPConnection) -> None15ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]161718logger = get_logger(__name__)192021class HTTPConnection(AsyncDispatcher):22 def __init__(23 self,24 origin: typing.Union[str, Origin],25 ssl: SSLConfig = None,26 backend: typing.Union[str, ConcurrencyBackend] = "auto",27 release_func: typing.Optional[ReleaseCallback] = None,28 uds: typing.Optional[str] = None,29 ):30 self.origin = Origin(origin) if isinstance(origin, str) else origin31 self.ssl = SSLConfig() if ssl is None else ssl32 self.backend = lookup_backend(backend)33 self.release_func = release_func34 self.uds = uds35 self.connection: typing.Union[None, HTTP11Connection, HTTP2Connection] = None36 self.expires_at: typing.Optional[float] = None3738 async def send(self, request: Request, timeout: Timeout = None) -> Response:39 timeout = Timeout() if timeout is None else timeout4041 if self.connection is None:42 self.connection = await self.connect(timeout=timeout)4344 return await self.connection.send(request, timeout=timeout)4546 async def connect(47 self, timeout: Timeout48 ) -> typing.Union[HTTP11Connection, HTTP2Connection]:49 host = self.origin.host50 port = self.origin.port51 ssl_context = None if not self.origin.is_ssl else self.ssl.ssl_context5253 if self.release_func is None:54 on_release = None55 else:56 on_release = functools.partial(self.release_func, self)5758 if self.uds is None:59 logger.trace(60 f"start_connect tcp host={host!r} port={port!r} timeout={timeout!r}"61 )62 socket = await self.backend.open_tcp_stream(63 host, port, ssl_context, timeout64 )65 else:66 logger.trace(67 f"start_connect uds path={self.uds!r} host={host!r} timeout={timeout!r}"68 )69 socket = await self.backend.open_uds_stream(70 self.uds, host, ssl_context, timeout71 )7273 http_version = socket.get_http_version()74 logger.trace(f"connected http_version={http_version!r}")7576 if http_version == "HTTP/2":77 return HTTP2Connection(socket, self.backend, on_release=on_release)78 return HTTP11Connection(socket, on_release=on_release)7980 async def tunnel_start_tls(81 self, origin: Origin, proxy_url: URL, timeout: Timeout = None,82 ) -> None:83 """84 Upgrade this connection to use TLS, assuming it represents a TCP tunnel.85 """86 timeout = Timeout() if timeout is None else timeout8788 # First, check that we are in the correct state to start TLS, i.e. we've89 # just agreed to switch protocols with the server via HTTP/1.1.90 assert isinstance(self.connection, HTTP11Connection)91 h11_connection = self.connection92 assert h11_connection is not None93 assert h11_connection.h11_state.our_state == h11.SWITCHED_PROTOCOL9495 # Store this information here so that we can transfer96 # it to the new internal connection object after97 # the old one goes to 'SWITCHED_PROTOCOL'.98 # Note that the negotiated 'http_version' may change after the TLS upgrade.99 http_version = "HTTP/1.1"100 socket = h11_connection.socket101 on_release = h11_connection.on_release102103 if origin.is_ssl:104 # Pull the socket stream off the internal HTTP connection object,105 # and run start_tls().106 ssl_context = self.ssl.ssl_context107108 logger.trace(f"tunnel_start_tls proxy_url={proxy_url!r} origin={origin!r}")109 socket = await socket.start_tls(110 hostname=origin.host, ssl_context=ssl_context, timeout=timeout111 )112 http_version = socket.get_http_version()113 logger.trace(114 f"tunnel_tls_complete "115 f"proxy_url={proxy_url!r} "116 f"origin={origin!r} "117 f"http_version={http_version!r}"118 )119 else:120 # User requested the use of a tunnel, but they're performing a plain-text121 # HTTP request. Don't try to upgrade to TLS in this case.122 pass123124 if http_version == "HTTP/2":125 self.connection = HTTP2Connection(126 socket, self.backend, on_release=on_release127 )128 else:129 self.connection = HTTP11Connection(socket, on_release=on_release)130131 async def close(self) -> None:132 logger.trace("close_connection")133 if self.connection is not None:134 await self.connection.close()135136 @property137 def is_http2(self) -> bool:138 return self.connection is not None and self.connection.is_http2139140 @property141 def is_closed(self) -> bool:142 return self.connection is not None and self.connection.is_closed143144 def is_connection_dropped(self) -> bool:145 return self.connection is not None and self.connection.is_connection_dropped()146147 def __repr__(self) -> str:148 class_name = self.__class__.__name__149 return f"{class_name}(origin={self.origin!r})"
deleted:httpx/dispatch/http11.py-206 removed
1import typing23import h1145from ..backends.base import BaseSocketStream6from ..config import Timeout7from ..content_streams import AsyncIteratorStream8from ..exceptions import ConnectionClosed, ProtocolError9from ..models import Request, Response10from ..utils import get_logger1112H11Event = typing.Union[13 h11.Request,14 h11.Response,15 h11.InformationalResponse,16 h11.Data,17 h11.EndOfMessage,18 h11.ConnectionClosed,19]202122# Callback signature: async def callback() -> None23# In practice the callback will be a functools partial, which binds24# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.25OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]262728logger = get_logger(__name__)293031class HTTP11Connection:32 READ_NUM_BYTES = 40963334 def __init__(35 self,36 socket: BaseSocketStream,37 on_release: typing.Optional[OnReleaseCallback] = None,38 ):39 self.socket = socket40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)4243 @property44 def is_http2(self) -> bool:45 return False4647 async def send(self, request: Request, timeout: Timeout = None) -> Response:48 timeout = Timeout() if timeout is None else timeout4950 await self._send_request(request, timeout)51 await self._send_request_body(request, timeout)52 http_version, status_code, headers = await self._receive_response(timeout)53 stream = AsyncIteratorStream(54 aiterator=self._receive_response_data(timeout),55 close_func=self.response_closed,56 )5758 return Response(59 status_code=status_code,60 http_version=http_version,61 headers=headers,62 stream=stream,63 request=request,64 )6566 async def close(self) -> None:67 event = h11.ConnectionClosed()68 try:69 logger.trace(f"send_event event={event!r}")70 self.h11_state.send(event)71 except h11.LocalProtocolError: # pragma: no cover72 # Premature client disconnect73 pass74 await self.socket.close()7576 async def _send_request(self, request: Request, timeout: Timeout) -> None:77 """78 Send the request method, URL, and headers to the network.79 """80 logger.trace(81 f"send_headers method={request.method!r} "82 f"target={request.url.full_path!r} "83 f"headers={request.headers!r}"84 )8586 method = request.method.encode("ascii")87 target = request.url.full_path.encode("ascii")88 headers = request.headers.raw89 event = h11.Request(method=method, target=target, headers=headers)90 await self._send_event(event, timeout)9192 async def _send_request_body(self, request: Request, timeout: Timeout) -> None:93 """94 Send the request body to the network.95 """96 try:97 # Send the request body.98 async for chunk in request.stream:99 logger.trace(f"send_data data=Data(<{len(chunk)} bytes>)")100 event = h11.Data(data=chunk)101 await self._send_event(event, timeout)102103 # Finalize sending the request.104 event = h11.EndOfMessage()105 await self._send_event(event, timeout)106 except OSError: # pragma: nocover107 # Once we've sent the initial part of the request we don't actually108 # care about connection errors that occur when sending the body.109 # Ignore these, and defer to any exceptions on reading the response.110 self.h11_state.send_failed()111112 async def _send_event(self, event: H11Event, timeout: Timeout) -> None:113 """114 Send a single `h11` event to the network, waiting for the data to115 drain before returning.116 """117 bytes_to_send = self.h11_state.send(event)118 await self.socket.write(bytes_to_send, timeout)119120 async def _receive_response(121 self, timeout: Timeout122 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:123 """124 Read the response status and headers from the network.125 """126 while True:127 event = await self._receive_event(timeout)128 if isinstance(event, h11.InformationalResponse):129 continue130 else:131 assert isinstance(event, h11.Response)132 break # pragma: no cover133 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")134 return http_version, event.status_code, event.headers135136 async def _receive_response_data(137 self, timeout: Timeout138 ) -> typing.AsyncIterator[bytes]:139 """140 Read the response data from the network.141 """142 while True:143 event = await self._receive_event(timeout)144 if isinstance(event, h11.Data):145 yield bytes(event.data)146 else:147 assert isinstance(event, h11.EndOfMessage) or event is h11.PAUSED148 break # pragma: no cover149150 async def _receive_event(self, timeout: Timeout) -> H11Event:151 """152 Read a single `h11` event, reading more data from the network if needed.153 """154 while True:155 try:156 event = self.h11_state.next_event()157 except h11.RemoteProtocolError as e:158 logger.debug(159 "h11.RemoteProtocolError exception "160 + f"their_state={self.h11_state.their_state} "161 + f"error_status_hint={e.error_status_hint}"162 )163 if self.socket.is_connection_dropped():164 raise ConnectionClosed(e)165 raise ProtocolError(e)166167 if isinstance(event, h11.Data):168 logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")169 else:170 logger.trace(f"receive_event event={event!r}")171172 if event is h11.NEED_DATA:173 try:174 data = await self.socket.read(self.READ_NUM_BYTES, timeout)175 except OSError: # pragma: nocover176 data = b""177 self.h11_state.receive_data(data)178 else:179 assert event is not h11.NEED_DATA180 break # pragma: no cover181 return event182183 async def response_closed(self) -> None:184 logger.trace(185 f"response_closed "186 f"our_state={self.h11_state.our_state!r} "187 f"their_state={self.h11_state.their_state}"188 )189 if (190 self.h11_state.our_state is h11.DONE191 and self.h11_state.their_state is h11.DONE192 ):193 # Get ready for another request/response cycle.194 self.h11_state.start_next_cycle()195 else:196 await self.close()197198 if self.on_release is not None:199 await self.on_release()200201 @property202 def is_closed(self) -> bool:203 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)204205 def is_connection_dropped(self) -> bool:206 return self.socket.is_connection_dropped()
deleted:httpx/dispatch/http2.py-298 removed
1import typing23import h2.connection4import h2.events5from h2.config import H2Configuration6from h2.settings import SettingCodes, Settings78from ..backends.base import (9 BaseLock,10 BaseSocketStream,11 ConcurrencyBackend,12 lookup_backend,13)14from ..config import Timeout15from ..content_streams import AsyncIteratorStream16from ..exceptions import ProtocolError17from ..models import Request, Response18from ..utils import get_logger1920logger = get_logger(__name__)212223class HTTP2Connection:24 READ_NUM_BYTES = 409625 CONFIG = H2Configuration(validate_inbound_headers=False)2627 def __init__(28 self,29 socket: BaseSocketStream,30 backend: typing.Union[str, ConcurrencyBackend] = "auto",31 on_release: typing.Callable = None,32 ):33 self.socket = socket34 self.backend = lookup_backend(backend)35 self.on_release = on_release36 self.state = h2.connection.H2Connection(config=self.CONFIG)3738 self.streams = {} # type: typing.Dict[int, HTTP2Stream]39 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]4041 self.sent_connection_init = False4243 @property44 def is_http2(self) -> bool:45 return True4647 @property48 def init_lock(self) -> BaseLock:49 # We do this lazily, to make sure backend autodetection always50 # runs within an async context.51 if not hasattr(self, "_initialization_lock"):52 self._initialization_lock = self.backend.create_lock()53 return self._initialization_lock5455 async def send(self, request: Request, timeout: Timeout = None) -> Response:56 timeout = Timeout() if timeout is None else timeout5758 async with self.init_lock:59 if not self.sent_connection_init:60 # The very first stream is responsible for initiating the connection.61 await self.send_connection_init(timeout)62 self.sent_connection_init = True63 stream_id = self.state.get_next_available_stream_id()6465 stream = HTTP2Stream(stream_id=stream_id, connection=self)66 self.streams[stream_id] = stream67 self.events[stream_id] = []68 return await stream.send(request, timeout)6970 async def send_connection_init(self, timeout: Timeout) -> None:71 """72 The HTTP/2 connection requires some initial setup before we can start73 using individual request/response streams on it.74 """7576 # Need to set these manually here instead of manipulating via77 # __setitem__() otherwise the H2Connection will emit SettingsUpdate78 # frames in addition to sending the undesired defaults.79 self.state.local_settings = Settings(80 client=True,81 initial_values={82 # Disable PUSH_PROMISE frames from the server since we don't do anything83 # with them for now. Maybe when we support caching?84 SettingCodes.ENABLE_PUSH: 0,85 # These two are taken from h2 for safe defaults86 SettingCodes.MAX_CONCURRENT_STREAMS: 100,87 SettingCodes.MAX_HEADER_LIST_SIZE: 65536,88 },89 )9091 # Some websites (*cough* Yahoo *cough*) balk at this setting being92 # present in the initial handshake since it's not defined in the original93 # RFC despite the RFC mandating ignoring settings you don't know about.94 del self.state.local_settings[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL]9596 self.state.initiate_connection()97 self.state.increment_flow_control_window(2 ** 24)98 data_to_send = self.state.data_to_send()99 await self.socket.write(data_to_send, timeout)100101 @property102 def is_closed(self) -> bool:103 return False104105 def is_connection_dropped(self) -> bool:106 return self.socket.is_connection_dropped()107108 async def close(self) -> None:109 await self.socket.close()110111 async def wait_for_outgoing_flow(self, stream_id: int, timeout: Timeout) -> int:112 """113 Returns the maximum allowable outgoing flow for a given stream.114115 If the allowable flow is zero, then waits on the network until116 WindowUpdated frames have increased the flow rate.117118 https://tools.ietf.org/html/rfc7540#section-6.9119 """120 local_flow = self.state.local_flow_control_window(stream_id)121 connection_flow = self.state.max_outbound_frame_size122 flow = min(local_flow, connection_flow)123 while flow == 0:124 await self.receive_events(timeout)125 local_flow = self.state.local_flow_control_window(stream_id)126 connection_flow = self.state.max_outbound_frame_size127 flow = min(local_flow, connection_flow)128 return flow129130 async def wait_for_event(self, stream_id: int, timeout: Timeout) -> h2.events.Event:131 """132 Returns the next event for a given stream.133134 If no events are available yet, then waits on the network until135 an event is available.136 """137 while not self.events[stream_id]:138 await self.receive_events(timeout)139 return self.events[stream_id].pop(0)140141 async def receive_events(self, timeout: Timeout) -> None:142 """143 Read some data from the network, and update the H2 state.144 """145 data = await self.socket.read(self.READ_NUM_BYTES, timeout)146 events = self.state.receive_data(data)147 for event in events:148 event_stream_id = getattr(event, "stream_id", 0)149 logger.trace(f"receive_event stream_id={event_stream_id} event={event!r}")150151 if hasattr(event, "error_code"):152 raise ProtocolError(event)153154 if event_stream_id in self.events:155 self.events[event_stream_id].append(event)156157 data_to_send = self.state.data_to_send()158 await self.socket.write(data_to_send, timeout)159160 async def send_headers(161 self,162 stream_id: int,163 headers: typing.List[typing.Tuple[bytes, bytes]],164 end_stream: bool,165 timeout: Timeout,166 ) -> None:167 self.state.send_headers(stream_id, headers, end_stream=end_stream)168 self.state.increment_flow_control_window(2 ** 24, stream_id=stream_id)169 data_to_send = self.state.data_to_send()170 await self.socket.write(data_to_send, timeout)171172 async def send_data(self, stream_id: int, chunk: bytes, timeout: Timeout) -> None:173 self.state.send_data(stream_id, chunk)174 data_to_send = self.state.data_to_send()175 await self.socket.write(data_to_send, timeout)176177 async def end_stream(self, stream_id: int, timeout: Timeout) -> None:178 self.state.end_stream(stream_id)179 data_to_send = self.state.data_to_send()180 await self.socket.write(data_to_send, timeout)181182 async def acknowledge_received_data(183 self, stream_id: int, amount: int, timeout: Timeout184 ) -> None:185 self.state.acknowledge_received_data(amount, stream_id)186 data_to_send = self.state.data_to_send()187 await self.socket.write(data_to_send, timeout)188189 async def close_stream(self, stream_id: int) -> None:190 del self.streams[stream_id]191 del self.events[stream_id]192193 if not self.streams and self.on_release is not None:194 await self.on_release()195196197class HTTP2Stream:198 def __init__(self, stream_id: int, connection: HTTP2Connection) -> None:199 self.stream_id = stream_id200 self.connection = connection201202 async def send(self, request: Request, timeout: Timeout) -> Response:203 # Send the request.204 has_body = (205 "Content-Length" in request.headers206 or "Transfer-Encoding" in request.headers207 )208209 await self.send_headers(request, has_body, timeout)210 if has_body:211 await self.send_body(request, timeout)212213 # Receive the response.214 status_code, headers = await self.receive_response(timeout)215 stream = AsyncIteratorStream(216 aiterator=self.body_iter(timeout), close_func=self.close217 )218219 return Response(220 status_code=status_code,221 http_version="HTTP/2",222 headers=headers,223 stream=stream,224 request=request,225 )226227 async def send_headers(228 self, request: Request, has_body: bool, timeout: Timeout229 ) -> None:230 headers = [231 (b":method", request.method.encode("ascii")),232 (b":authority", request.url.authority.encode("ascii")),233 (b":scheme", request.url.scheme.encode("ascii")),234 (b":path", request.url.full_path.encode("ascii")),235 ] + [236 (k, v)237 for k, v in request.headers.raw238 if k not in (b"host", b"transfer-encoding")239 ]240 end_stream = not has_body241242 logger.trace(243 f"send_headers "244 f"stream_id={self.stream_id} "245 f"method={request.method!r} "246 f"target={request.url.full_path!r} "247 f"headers={headers!r}"248 )249 await self.connection.send_headers(self.stream_id, headers, end_stream, timeout)250251 async def send_body(self, request: Request, timeout: Timeout) -> None:252 logger.trace(f"send_body stream_id={self.stream_id}")253 async for data in request.stream:254 while data:255 max_flow = await self.connection.wait_for_outgoing_flow(256 self.stream_id, timeout257 )258 chunk_size = min(len(data), max_flow)259 chunk, data = data[:chunk_size], data[chunk_size:]260 await self.connection.send_data(self.stream_id, chunk, timeout)261262 await self.connection.end_stream(self.stream_id, timeout)263264 async def receive_response(265 self, timeout: Timeout266 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:267 """268 Read the response status and headers from the network.269 """270 while True:271 event = await self.connection.wait_for_event(self.stream_id, timeout)272 if isinstance(event, h2.events.ResponseReceived):273 break274275 status_code = 200276 headers = []277 for k, v in event.headers:278 if k == b":status":279 status_code = int(v.decode("ascii", errors="ignore"))280 elif not k.startswith(b":"):281 headers.append((k, v))282283 return (status_code, headers)284285 async def body_iter(self, timeout: Timeout) -> typing.AsyncIterator[bytes]:286 while True:287 event = await self.connection.wait_for_event(self.stream_id, timeout)288 if isinstance(event, h2.events.DataReceived):289 amount = event.flow_controlled_length290 await self.connection.acknowledge_received_data(291 self.stream_id, amount, timeout292 )293 yield event.data294 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):295 break296297 async def close(self) -> None:298 await self.connection.close_stream(self.stream_id)
deleted:httpx/dispatch/proxy_http.py-208 removed
1import enum2import typing3import warnings4from base64 import b64encode56from ..backends.base import ConcurrencyBackend7from ..config import (8 DEFAULT_POOL_LIMITS,9 CertTypes,10 PoolLimits,11 SSLConfig,12 Timeout,13 VerifyTypes,14)15from ..exceptions import ProxyError16from ..models import URL, Headers, HeaderTypes, Origin, Request, Response, URLTypes17from ..utils import get_logger18from .connection import HTTPConnection19from .connection_pool import ConnectionPool2021logger = get_logger(__name__)222324class HTTPProxyMode(enum.Enum):25 # This enum is pending deprecation in order to reduce API surface area,26 # but is currently still around for 0.8 backwards compat.27 DEFAULT = "DEFAULT"28 FORWARD_ONLY = "FORWARD_ONLY"29 TUNNEL_ONLY = "TUNNEL_ONLY"303132DEFAULT_MODE = "DEFAULT"33FORWARD_ONLY = "FORWARD_ONLY"34TUNNEL_ONLY = "TUNNEL_ONLY"353637class HTTPProxy(ConnectionPool):38 """A proxy that sends requests to the recipient server39 on behalf of the connecting client.40 """4142 def __init__(43 self,44 proxy_url: URLTypes,45 *,46 proxy_headers: HeaderTypes = None,47 proxy_mode: str = "DEFAULT",48 verify: VerifyTypes = True,49 cert: CertTypes = None,50 trust_env: bool = None,51 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,52 http2: bool = False,53 backend: typing.Union[str, ConcurrencyBackend] = "auto",54 ):5556 if isinstance(proxy_mode, HTTPProxyMode): # pragma: nocover57 warnings.warn(58 "The 'HTTPProxyMode' enum is pending deprecation. "59 "Use a plain string instead. proxy_mode='FORWARD_ONLY', or "60 "proxy_mode='TUNNEL_ONLY'."61 )62 proxy_mode = proxy_mode.value63 assert proxy_mode in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY")6465 self.tunnel_ssl = SSLConfig(66 verify=verify, cert=cert, trust_env=trust_env, http2=False67 )6869 super(HTTPProxy, self).__init__(70 verify=verify,71 cert=cert,72 pool_limits=pool_limits,73 backend=backend,74 trust_env=trust_env,75 http2=http2,76 )7778 self.proxy_url = URL(proxy_url)79 self.proxy_mode = proxy_mode80 self.proxy_headers = Headers(proxy_headers)8182 url = self.proxy_url83 if url.username or url.password:84 self.proxy_headers.setdefault(85 "Proxy-Authorization",86 self.build_auth_header(url.username, url.password),87 )88 # Remove userinfo from the URL authority, e.g.:89 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'90 credentials, _, authority = url.authority.rpartition("@")91 self.proxy_url = url.copy_with(authority=authority)9293 def build_auth_header(self, username: str, password: str) -> str:94 userpass = (username.encode("utf-8"), password.encode("utf-8"))95 token = b64encode(b":".join(userpass)).decode().strip()96 return f"Basic {token}"9798 async def acquire_connection(99 self, origin: Origin, timeout: Timeout = None100 ) -> HTTPConnection:101 if self.should_forward_origin(origin):102 logger.trace(103 f"forward_connection proxy_url={self.proxy_url!r} origin={origin!r}"104 )105 return await super().acquire_connection(Origin(self.proxy_url), timeout)106 else:107 logger.trace(108 f"tunnel_connection proxy_url={self.proxy_url!r} origin={origin!r}"109 )110 return await self.tunnel_connection(origin, timeout)111112 async def tunnel_connection(113 self, origin: Origin, timeout: Timeout = None114 ) -> HTTPConnection:115 """Creates a new HTTPConnection via the CONNECT method116 usually reserved for proxying HTTPS connections.117 """118 connection = self.pop_connection(origin)119120 if connection is None:121 connection = await self.request_tunnel_proxy_connection(origin)122123 # After we receive the 2XX response from the proxy that our124 # tunnel is open we switch the connection's origin125 # to the original so the tunnel can be re-used.126 self.active_connections.remove(connection)127 connection.origin = origin128 self.active_connections.add(connection)129130 await connection.tunnel_start_tls(131 origin=origin, proxy_url=self.proxy_url, timeout=timeout,132 )133 else:134 self.active_connections.add(connection)135136 return connection137138 async def request_tunnel_proxy_connection(self, origin: Origin) -> HTTPConnection:139 """Creates an HTTPConnection by setting up a TCP tunnel"""140 proxy_headers = self.proxy_headers.copy()141 proxy_headers.setdefault("Accept", "*/*")142 proxy_request = Request(143 method="CONNECT", url=self.proxy_url.copy_with(), headers=proxy_headers144 )145 proxy_request.url.full_path = f"{origin.host}:{origin.port}"146147 await self.max_connections.acquire()148149 connection = HTTPConnection(150 Origin(self.proxy_url),151 ssl=self.tunnel_ssl,152 backend=self.backend,153 release_func=self.release_connection,154 )155 self.active_connections.add(connection)156157 # See if our tunnel has been opened successfully158 proxy_response = await connection.send(proxy_request)159 logger.trace(160 f"tunnel_response "161 f"proxy_url={self.proxy_url!r} "162 f"origin={origin!r} "163 f"response={proxy_response!r}"164 )165 if not (200 <= proxy_response.status_code <= 299):166 await proxy_response.aread()167 raise ProxyError(168 f"Non-2XX response received from HTTP proxy "169 f"({proxy_response.status_code})",170 request=proxy_request,171 response=proxy_response,172 )173 else:174 # Hack to ingest the response, without closing it.175 async for chunk in proxy_response._raw_stream:176 pass177178 return connection179180 def should_forward_origin(self, origin: Origin) -> bool:181 """Determines if the given origin should182 be forwarded or tunneled. If 'proxy_mode' is 'DEFAULT'183 then the proxy will forward all 'HTTP' requests and184 tunnel all 'HTTPS' requests.185 """186 return (187 self.proxy_mode == DEFAULT_MODE and not origin.is_ssl188 ) or self.proxy_mode == FORWARD_ONLY189190 async def send(self, request: Request, timeout: Timeout = None) -> Response:191 if self.should_forward_origin(Origin(request.url)):192 # Change the request to have the target URL193 # as its full_path and switch the proxy URL194 # for where the request will be sent.195 target_url = str(request.url)196 request.url = self.proxy_url.copy_with()197 request.url.full_path = target_url198 for name, value in self.proxy_headers.items():199 request.headers.setdefault(name, value)200201 return await super().send(request=request, timeout=timeout)202203 def __repr__(self) -> str:204 return (205 f"HTTPProxy(proxy_url={self.proxy_url!r} "206 f"proxy_headers={self.proxy_headers!r} "207 f"proxy_mode={self.proxy_mode!r})"208 )
deleted:httpx/dispatch/urllib3.py-128 removed
1import math2import socket3import ssl4import typing56import urllib37from urllib3.exceptions import MaxRetryError, SSLError89from ..config import (10 DEFAULT_POOL_LIMITS,11 CertTypes,12 PoolLimits,13 Proxy,14 SSLConfig,15 Timeout,16 VerifyTypes,17)18from ..content_streams import IteratorStream19from ..models import Request, Response20from ..utils import as_network_error21from .base import SyncDispatcher222324class URLLib3Dispatcher(SyncDispatcher):25 def __init__(26 self,27 *,28 proxy: Proxy = None,29 verify: VerifyTypes = True,30 cert: CertTypes = None,31 trust_env: bool = None,32 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,33 ):34 ssl_config = SSLConfig(35 verify=verify, cert=cert, trust_env=trust_env, http2=False36 )37 hard_limit = pool_limits.hard_limit38 soft_limit = pool_limits.soft_limit3940 # Our connection pool configuration doesn't quite match up with urllib3's41 # controls, but we can put sensible mappings in place:42 if hard_limit is None:43 block = False44 if soft_limit is None:45 num_pools = 100046 maxsize = 100047 else:48 num_pools = int(math.sqrt(soft_limit))49 maxsize = int(math.sqrt(soft_limit))50 else:51 block = True52 num_pools = int(math.sqrt(hard_limit))53 maxsize = int(math.sqrt(hard_limit))5455 self.pool = self.init_pool_manager(56 proxy=proxy,57 ssl_context=ssl_config.ssl_context,58 num_pools=num_pools,59 maxsize=maxsize,60 block=block,61 )6263 def init_pool_manager(64 self,65 proxy: typing.Optional[Proxy],66 ssl_context: ssl.SSLContext,67 num_pools: int,68 maxsize: int,69 block: bool,70 ) -> typing.Union[urllib3.PoolManager, urllib3.ProxyManager]:71 if proxy is None:72 return urllib3.PoolManager(73 ssl_context=ssl_context,74 num_pools=num_pools,75 maxsize=maxsize,76 block=block,77 )78 else:79 return urllib3.ProxyManager(80 proxy_url=str(proxy.url),81 proxy_headers=dict(proxy.headers),82 ssl_context=ssl_context,83 num_pools=num_pools,84 maxsize=maxsize,85 block=block,86 )8788 def send(self, request: Request, timeout: Timeout = None) -> Response:89 timeout = Timeout() if timeout is None else timeout90 urllib3_timeout = urllib3.util.Timeout(91 connect=timeout.connect_timeout, read=timeout.read_timeout92 )93 chunked = request.headers.get("Transfer-Encoding") == "chunked"94 content_length = int(request.headers.get("Content-Length", "0"))95 body = request.stream if chunked or content_length else None9697 with as_network_error(MaxRetryError, SSLError, socket.error):98 conn = self.pool.urlopen(99 method=request.method,100 url=str(request.url),101 headers=dict(request.headers),102 body=body,103 redirect=False,104 assert_same_host=False,105 retries=0,106 preload_content=False,107 chunked=chunked,108 timeout=urllib3_timeout,109 pool_timeout=timeout.pool_timeout,110 )111112 def response_bytes() -> typing.Iterator[bytes]:113 with as_network_error(socket.error):114 for chunk in conn.stream(4096, decode_content=False):115 yield chunk116117 return Response(118 status_code=conn.status,119 http_version="HTTP/1.1",120 headers=list(conn.headers.items()),121 stream=IteratorStream(122 iterator=response_bytes(), close_func=conn.release_conn123 ),124 request=request,125 )126127 def close(self) -> None:128 self.pool.clear()
deleted:httpx/dispatch/wsgi.py-103 removed
1import io2import typing34from ..config import TimeoutTypes5from ..content_streams import IteratorStream6from ..models import Request, Response7from .base import SyncDispatcher8910class WSGIDispatch(SyncDispatcher):11 """12 A custom SyncDispatcher that handles sending requests directly to an WSGI app.13 The simplest way to use this functionality is to use the `app` argument.1415 ```16 client = httpx.Client(app=app)17 ```1819 Alternatively, you can setup the dispatch instance explicitly.20 This allows you to include any additional configuration arguments specific21 to the WSGIDispatch class:2223 ```24 dispatch = httpx.WSGIDispatch(25 app=app,26 script_name="/submount",27 remote_addr="1.2.3.4"28 )29 client = httpx.Client(dispatch=dispatch)30 ```3132 Arguments:3334 * `app` - The ASGI application.35 * `raise_app_exceptions` - Boolean indicating if exceptions in the application36 should be raised. Default to `True`. Can be set to `False` for use cases37 such as testing the content of a client 500 response.38 * `script_name` - The root path on which the ASGI application should be mounted.39 * `remote_addr` - A string indicating the client IP of incoming requests.40 ```41 """4243 def __init__(44 self,45 app: typing.Callable,46 raise_app_exceptions: bool = True,47 script_name: str = "",48 remote_addr: str = "127.0.0.1",49 ) -> None:50 self.app = app51 self.raise_app_exceptions = raise_app_exceptions52 self.script_name = script_name53 self.remote_addr = remote_addr5455 def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:56 environ = {57 "wsgi.version": (1, 0),58 "wsgi.url_scheme": request.url.scheme,59 "wsgi.input": io.BytesIO(request.read()),60 "wsgi.errors": io.BytesIO(),61 "wsgi.multithread": True,62 "wsgi.multiprocess": False,63 "wsgi.run_once": False,64 "REQUEST_METHOD": request.method,65 "SCRIPT_NAME": self.script_name,66 "PATH_INFO": request.url.path,67 "QUERY_STRING": request.url.query,68 "SERVER_NAME": request.url.host,69 "SERVER_PORT": str(request.url.port),70 "REMOTE_ADDR": self.remote_addr,71 }72 for key, value in request.headers.items():73 key = key.upper().replace("-", "_")74 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):75 key = "HTTP_" + key76 environ[key] = value7778 seen_status = None79 seen_response_headers = None80 seen_exc_info = None8182 def start_response(83 status: str, response_headers: list, exc_info: typing.Any = None84 ) -> None:85 nonlocal seen_status, seen_response_headers, seen_exc_info86 seen_status = status87 seen_response_headers = response_headers88 seen_exc_info = exc_info8990 result = self.app(environ, start_response)9192 assert seen_status is not None93 assert seen_response_headers is not None94 if seen_exc_info and self.raise_app_exceptions:95 raise seen_exc_info[1]9697 return Response(98 status_code=int(seen_status.split()[0]),99 http_version="HTTP/1.1",100 headers=seen_response_headers,101 stream=IteratorStream(chunk for chunk in result),102 request=request,103 )
modified:httpx/__init__.py+9 added-9 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request, stream3from .auth import Auth, BasicAuth, DigestAuth4from .client import AsyncClient, Client5from .config import PoolLimits, Proxy, Timeout6from .dispatch.asgi import ASGIDispatch7from .dispatch.wsgi import WSGIDispatch8from .exceptions import (2from ._api import delete, get, head, options, patch, post, put, request, stream3from ._auth import Auth, BasicAuth, DigestAuth4from ._client import AsyncClient, Client5from ._config import PoolLimits, Proxy, Timeout6from ._dispatch.asgi import ASGIDispatch7from ._dispatch.wsgi import WSGIDispatch8from ._exceptions import (9 ConnectionClosed,10 ConnectTimeout,11 CookieConflict,12 DecodingError,
13 unmodified lines
26 TimeoutException,27 TooManyRedirects,28 WriteTimeout,29)30from .models import URL, Cookies, Headers, QueryParams, Request, Response31from .status_codes import StatusCode, codes30from ._models import URL, Cookies, Headers, QueryParams, Request, Response31from ._status_codes import StatusCode, codes3233__all__ = [34 "__description__",35 "__title__",
51 unmodified lines
added:httpx/_api.py+398 added
1import typing23from ._auth import AuthTypes4from ._client import Client, StreamContextManager5from ._config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes6from ._models import (7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 Request,11 RequestData,12 RequestFiles,13 Response,14 URLTypes,15)161718def request(19 method: str,20 url: URLTypes,21 *,22 params: QueryParamTypes = None,23 data: RequestData = None,24 files: RequestFiles = None,25 json: typing.Any = None,26 headers: HeaderTypes = None,27 cookies: CookieTypes = None,28 auth: AuthTypes = None,29 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,30 allow_redirects: bool = True,31 verify: VerifyTypes = True,32 cert: CertTypes = None,33 trust_env: bool = True,34) -> Response:35 """36 Sends an HTTP request.3738 **Parameters:**3940 * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,41 `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.42 * **url** - URL for the new `Request` object.43 * **params** - *(optional)* Query parameters to include in the URL, as a44 string, dictionary, or list of two-tuples.45 * **data** - *(optional)* Data to include in the body of the request, as a46 dictionary47 * **files** - *(optional)* A dictionary of upload files to include in the48 body of the request.49 * **json** - *(optional)* A JSON serializable object to include in the body50 of the request.51 * **headers** - *(optional)* Dictionary of HTTP headers to include in the52 request.53 * **cookies** - *(optional)* Dictionary of Cookie items to include in the54 request.55 * **auth** - *(optional)* An authentication class to use when sending the56 request.57 * **timeout** - *(optional)* The timeout configuration to use when sending58 the request.59 * **allow_redirects** - *(optional)* Enables or disables HTTP redirects.60 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to61 verify the identity of requested hosts. Either `True` (default CA bundle),62 a path to an SSL certificate file, or `False` (disable verification).63 * **cert** - *(optional)* An SSL certificate used by the requested host64 to authenticate the client. Either a path to an SSL certificate file, or65 two-tuple of (certificate file, key file), or a three-tuple of (certificate66 file, key file, password).67 * **trust_env** - *(optional)* Enables or disables usage of environment68 variables for configuration.69 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy70 URLs.7172 **Returns:** `Response`7374 Usage:7576 ```77 >>> import httpx78 >>> response = httpx.request('GET', 'https://httpbin.org/get')79 >>> response80 <Response [200 OK]>81 ```82 """83 with Client(84 cert=cert, verify=verify, timeout=timeout, trust_env=trust_env,85 ) as client:86 return client.request(87 method=method,88 url=url,89 data=data,90 files=files,91 json=json,92 params=params,93 headers=headers,94 cookies=cookies,95 auth=auth,96 allow_redirects=allow_redirects,97 )9899100def stream(101 method: str,102 url: URLTypes,103 *,104 params: QueryParamTypes = None,105 data: RequestData = None,106 files: RequestFiles = None,107 json: typing.Any = None,108 headers: HeaderTypes = None,109 cookies: CookieTypes = None,110 auth: AuthTypes = None,111 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,112 allow_redirects: bool = True,113 verify: VerifyTypes = True,114 cert: CertTypes = None,115 trust_env: bool = True,116) -> StreamContextManager:117 client = Client(cert=cert, verify=verify, trust_env=trust_env)118 request = Request(119 method=method,120 url=url,121 params=params,122 data=data,123 files=files,124 json=json,125 headers=headers,126 cookies=cookies,127 )128 return StreamContextManager(129 client=client,130 request=request,131 auth=auth,132 timeout=timeout,133 allow_redirects=allow_redirects,134 close_client=True,135 )136137138def get(139 url: URLTypes,140 *,141 params: QueryParamTypes = None,142 headers: HeaderTypes = None,143 cookies: CookieTypes = None,144 auth: AuthTypes = None,145 allow_redirects: bool = True,146 cert: CertTypes = None,147 verify: VerifyTypes = True,148 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,149 trust_env: bool = True,150) -> Response:151 """152 Sends a `GET` request.153154 **Parameters**: See `httpx.request`.155156 Note that the `data`, `files`, and `json` parameters are not available on157 this function, as `GET` requests should not include a request body.158 """159 return request(160 "GET",161 url,162 params=params,163 headers=headers,164 cookies=cookies,165 auth=auth,166 allow_redirects=allow_redirects,167 cert=cert,168 verify=verify,169 timeout=timeout,170 trust_env=trust_env,171 )172173174def options(175 url: URLTypes,176 *,177 params: QueryParamTypes = None,178 headers: HeaderTypes = None,179 cookies: CookieTypes = None,180 auth: AuthTypes = None,181 allow_redirects: bool = True,182 cert: CertTypes = None,183 verify: VerifyTypes = True,184 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,185 trust_env: bool = True,186) -> Response:187 """188 Sends an `OPTIONS` request.189190 **Parameters**: See `httpx.request`.191192 Note that the `data`, `files`, and `json` parameters are not available on193 this function, as `OPTIONS` requests should not include a request body.194 """195 return request(196 "OPTIONS",197 url,198 params=params,199 headers=headers,200 cookies=cookies,201 auth=auth,202 allow_redirects=allow_redirects,203 cert=cert,204 verify=verify,205 timeout=timeout,206 trust_env=trust_env,207 )208209210def head(211 url: URLTypes,212 *,213 params: QueryParamTypes = None,214 headers: HeaderTypes = None,215 cookies: CookieTypes = None,216 auth: AuthTypes = None,217 allow_redirects: bool = False, # Note: Differs to usual default.218 cert: CertTypes = None,219 verify: VerifyTypes = True,220 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,221 trust_env: bool = True,222) -> Response:223 """224 Sends a `HEAD` request.225226 **Parameters**: See `httpx.request`.227228 Note that the `data`, `files`, and `json` parameters are not available on229 this function, as `HEAD` requests should not include a request body. The230 `HEAD` method also differs from the other cases in that `allow_redirects`231 defaults to `False`.232 """233 return request(234 "HEAD",235 url,236 params=params,237 headers=headers,238 cookies=cookies,239 auth=auth,240 allow_redirects=allow_redirects,241 cert=cert,242 verify=verify,243 timeout=timeout,244 trust_env=trust_env,245 )246247248def post(249 url: URLTypes,250 *,251 data: RequestData = None,252 files: RequestFiles = None,253 json: typing.Any = None,254 params: QueryParamTypes = None,255 headers: HeaderTypes = None,256 cookies: CookieTypes = None,257 auth: AuthTypes = None,258 allow_redirects: bool = True,259 cert: CertTypes = None,260 verify: VerifyTypes = True,261 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,262 trust_env: bool = True,263) -> Response:264 """265 Sends a `POST` request.266267 **Parameters**: See `httpx.request`.268 """269 return request(270 "POST",271 url,272 data=data,273 files=files,274 json=json,275 params=params,276 headers=headers,277 cookies=cookies,278 auth=auth,279 allow_redirects=allow_redirects,280 cert=cert,281 verify=verify,282 timeout=timeout,283 trust_env=trust_env,284 )285286287def put(288 url: URLTypes,289 *,290 data: RequestData = None,291 files: RequestFiles = None,292 json: typing.Any = None,293 params: QueryParamTypes = None,294 headers: HeaderTypes = None,295 cookies: CookieTypes = None,296 auth: AuthTypes = None,297 allow_redirects: bool = True,298 cert: CertTypes = None,299 verify: VerifyTypes = True,300 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,301 trust_env: bool = True,302) -> Response:303 """304 Sends a `PUT` request.305306 **Parameters**: See `httpx.request`.307 """308 return request(309 "PUT",310 url,311 data=data,312 files=files,313 json=json,314 params=params,315 headers=headers,316 cookies=cookies,317 auth=auth,318 allow_redirects=allow_redirects,319 cert=cert,320 verify=verify,321 timeout=timeout,322 trust_env=trust_env,323 )324325326def patch(327 url: URLTypes,328 *,329 data: RequestData = None,330 files: RequestFiles = None,331 json: typing.Any = None,332 params: QueryParamTypes = None,333 headers: HeaderTypes = None,334 cookies: CookieTypes = None,335 auth: AuthTypes = None,336 allow_redirects: bool = True,337 cert: CertTypes = None,338 verify: VerifyTypes = True,339 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,340 trust_env: bool = True,341) -> Response:342 """343 Sends a `PATCH` request.344345 **Parameters**: See `httpx.request`.346 """347 return request(348 "PATCH",349 url,350 data=data,351 files=files,352 json=json,353 params=params,354 headers=headers,355 cookies=cookies,356 auth=auth,357 allow_redirects=allow_redirects,358 cert=cert,359 verify=verify,360 timeout=timeout,361 trust_env=trust_env,362 )363364365def delete(366 url: URLTypes,367 *,368 params: QueryParamTypes = None,369 headers: HeaderTypes = None,370 cookies: CookieTypes = None,371 auth: AuthTypes = None,372 allow_redirects: bool = True,373 cert: CertTypes = None,374 verify: VerifyTypes = True,375 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,376 trust_env: bool = True,377) -> Response:378 """379 Sends a `DELETE` request.380381 **Parameters**: See `httpx.request`.382383 Note that the `data`, `files`, and `json` parameters are not available on384 this function, as `DELETE` requests should not include a request body.385 """386 return request(387 "DELETE",388 url,389 params=params,390 headers=headers,391 cookies=cookies,392 auth=auth,393 allow_redirects=allow_redirects,394 cert=cert,395 verify=verify,396 timeout=timeout,397 trust_env=trust_env,398 )
added:httpx/_auth.py+255 added
1import hashlib2import os3import re4import time5import typing6from base64 import b64encode7from urllib.request import parse_http_list89from ._exceptions import ProtocolError, RequestBodyUnavailable10from ._models import Request, Response11from ._utils import to_bytes, to_str, unquote1213AuthTypes = typing.Union[14 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],15 typing.Callable[["Request"], "Request"],16 "Auth",17]181920class Auth:21 """22 Base class for all authentication schemes.23 """2425 requires_request_body = False2627 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:28 """29 Execute the authentication flow.3031 To dispatch a request, `yield` it:3233 ```34 yield request35 ```3637 The client will `.send()` the response back into the flow generator. You can38 access it like so:3940 ```41 response = yield request42 ```4344 A `return` (or reaching the end of the generator) will result in the45 client returning the last response obtained from the server.4647 You can dispatch as many requests as is necessary.48 """49 yield request505152class FunctionAuth(Auth):53 """54 Allows the 'auth' argument to be passed as a simple callable function,55 that takes the request, and returns a new, modified request.56 """5758 def __init__(self, func: typing.Callable[[Request], Request]) -> None:59 self.func = func6061 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:62 yield self.func(request)636465class BasicAuth(Auth):66 """67 Allows the 'auth' argument to be passed as a (username, password) pair,68 and uses HTTP Basic authentication.69 """7071 def __init__(72 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]73 ):74 self.auth_header = self.build_auth_header(username, password)7576 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:77 request.headers["Authorization"] = self.auth_header78 yield request7980 def build_auth_header(81 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]82 ) -> str:83 userpass = b":".join((to_bytes(username), to_bytes(password)))84 token = b64encode(userpass).decode().strip()85 return f"Basic {token}"868788class DigestAuth(Auth):89 ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable] = {90 "MD5": hashlib.md5,91 "MD5-SESS": hashlib.md5,92 "SHA": hashlib.sha1,93 "SHA-SESS": hashlib.sha1,94 "SHA-256": hashlib.sha256,95 "SHA-256-SESS": hashlib.sha256,96 "SHA-512": hashlib.sha512,97 "SHA-512-SESS": hashlib.sha512,98 }99100 def __init__(101 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]102 ) -> None:103 self.username = to_bytes(username)104 self.password = to_bytes(password)105106 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:107 if not request.stream.can_replay():108 raise RequestBodyUnavailable("Request body is no longer available.")109 response = yield request110111 if response.status_code != 401 or "www-authenticate" not in response.headers:112 # If the response is not a 401 WWW-Authenticate, then we don't113 # need to build an authenticated request.114 return115116 header = response.headers["www-authenticate"]117 try:118 challenge = DigestAuthChallenge.from_header(header)119 except ValueError:120 raise ProtocolError("Malformed Digest authentication header")121122 request.headers["Authorization"] = self._build_auth_header(request, challenge)123 yield request124125 def _build_auth_header(126 self, request: Request, challenge: "DigestAuthChallenge"127 ) -> str:128 hash_func = self.ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]129130 def digest(data: bytes) -> bytes:131 return hash_func(data).hexdigest().encode()132133 A1 = b":".join((self.username, challenge.realm, self.password))134135 path = request.url.full_path.encode("utf-8")136 A2 = b":".join((request.method.encode(), path))137 # TODO: implement auth-int138 HA2 = digest(A2)139140 nonce_count = 1 # TODO: implement nonce counting141 nc_value = b"%08x" % nonce_count142 cnonce = self._get_client_nonce(nonce_count, challenge.nonce)143144 HA1 = digest(A1)145 if challenge.algorithm.lower().endswith("-sess"):146 HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))147148 qop = self._resolve_qop(challenge.qop)149 if qop is None:150 digest_data = [HA1, challenge.nonce, HA2]151 else:152 digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]153 key_digest = b":".join(digest_data)154155 format_args = {156 "username": self.username,157 "realm": challenge.realm,158 "nonce": challenge.nonce,159 "uri": path,160 "response": digest(b":".join((HA1, key_digest))),161 "algorithm": challenge.algorithm.encode(),162 }163 if challenge.opaque:164 format_args["opaque"] = challenge.opaque165 if qop:166 format_args["qop"] = b"auth"167 format_args["nc"] = nc_value168 format_args["cnonce"] = cnonce169170 return "Digest " + self._get_header_value(format_args)171172 def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:173 s = str(nonce_count).encode()174 s += nonce175 s += time.ctime().encode()176 s += os.urandom(8)177178 return hashlib.sha1(s).hexdigest()[:16].encode()179180 def _get_header_value(self, header_fields: typing.Dict[str, bytes]) -> str:181 NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")182 QUOTED_TEMPLATE = '{}="{}"'183 NON_QUOTED_TEMPLATE = "{}={}"184185 header_value = ""186 for i, (field, value) in enumerate(header_fields.items()):187 if i > 0:188 header_value += ", "189 template = (190 QUOTED_TEMPLATE191 if field not in NON_QUOTED_FIELDS192 else NON_QUOTED_TEMPLATE193 )194 header_value += template.format(field, to_str(value))195196 return header_value197198 def _resolve_qop(self, qop: typing.Optional[bytes]) -> typing.Optional[bytes]:199 if qop is None:200 return None201 qops = re.split(b", ?", qop)202 if b"auth" in qops:203 return b"auth"204205 if qops == [b"auth-int"]:206 raise NotImplementedError("Digest auth-int support is not yet implemented")207208 raise ProtocolError(f'Unexpected qop value "{qop!r}" in digest auth')209210211class DigestAuthChallenge:212 def __init__(213 self,214 realm: bytes,215 nonce: bytes,216 algorithm: str = None,217 opaque: typing.Optional[bytes] = None,218 qop: typing.Optional[bytes] = None,219 ) -> None:220 self.realm = realm221 self.nonce = nonce222 self.algorithm = algorithm or "MD5"223 self.opaque = opaque224 self.qop = qop225226 @classmethod227 def from_header(cls, header: str) -> "DigestAuthChallenge":228 """Returns a challenge from a Digest WWW-Authenticate header.229 These take the form of:230 `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`231 """232 scheme, _, fields = header.partition(" ")233 if scheme.lower() != "digest":234 raise ValueError("Header does not start with 'Digest'")235236 header_dict: typing.Dict[str, str] = {}237 for field in parse_http_list(fields):238 key, value = field.strip().split("=", 1)239 header_dict[key] = unquote(value)240241 try:242 return cls.from_header_dict(header_dict)243 except KeyError as exc:244 raise ValueError("Malformed Digest WWW-Authenticate header") from exc245246 @classmethod247 def from_header_dict(cls, header_dict: dict) -> "DigestAuthChallenge":248 realm = header_dict["realm"].encode()249 nonce = header_dict["nonce"].encode()250 qop = header_dict["qop"].encode() if "qop" in header_dict else None251 opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None252 algorithm = header_dict.get("algorithm")253 return cls(254 realm=realm, nonce=nonce, qop=qop, opaque=opaque, algorithm=algorithm255 )
added:httpx/_client.py+1472 added
1import functools2import typing3from types import TracebackType45import hstspreload67from ._auth import Auth, AuthTypes, BasicAuth, FunctionAuth8from ._backends.base import ConcurrencyBackend9from ._config import (10 DEFAULT_MAX_REDIRECTS,11 DEFAULT_POOL_LIMITS,12 DEFAULT_TIMEOUT_CONFIG,13 UNSET,14 CertTypes,15 PoolLimits,16 ProxiesTypes,17 Proxy,18 Timeout,19 TimeoutTypes,20 UnsetType,21 VerifyTypes,22)23from ._content_streams import ContentStream24from ._dispatch.asgi import ASGIDispatch25from ._dispatch.base import AsyncDispatcher, SyncDispatcher26from ._dispatch.connection_pool import ConnectionPool27from ._dispatch.proxy_http import HTTPProxy28from ._dispatch.urllib3 import URLLib3Dispatcher29from ._dispatch.wsgi import WSGIDispatch30from ._exceptions import (31 HTTPError,32 InvalidURL,33 RedirectLoop,34 RequestBodyUnavailable,35 TooManyRedirects,36)37from ._models import (38 URL,39 Cookies,40 CookieTypes,41 Headers,42 HeaderTypes,43 Origin,44 QueryParams,45 QueryParamTypes,46 Request,47 RequestData,48 RequestFiles,49 Response,50 URLTypes,51)52from ._status_codes import codes53from ._utils import NetRCInfo, get_environment_proxies, get_logger5455logger = get_logger(__name__)565758class BaseClient:59 def __init__(60 self,61 *,62 auth: AuthTypes = None,63 params: QueryParamTypes = None,64 headers: HeaderTypes = None,65 cookies: CookieTypes = None,66 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,67 max_redirects: int = DEFAULT_MAX_REDIRECTS,68 base_url: URLTypes = None,69 trust_env: bool = True,70 ):71 if base_url is None:72 self.base_url = URL("", allow_relative=True)73 else:74 self.base_url = URL(base_url)7576 if params is None:77 params = {}7879 self.auth = auth80 self._params = QueryParams(params)81 self._headers = Headers(headers)82 self._cookies = Cookies(cookies)83 self.timeout = Timeout(timeout)84 self.max_redirects = max_redirects85 self.trust_env = trust_env86 self.netrc = NetRCInfo()8788 def get_proxy_map(89 self, proxies: typing.Optional[ProxiesTypes], trust_env: bool,90 ) -> typing.Dict[str, Proxy]:91 if proxies is None:92 if trust_env:93 return {94 key: Proxy(url=url)95 for key, url in get_environment_proxies().items()96 }97 return {}98 elif isinstance(proxies, (str, URL, Proxy)):99 proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies100 return {"all": proxy}101 elif isinstance(proxies, AsyncDispatcher): # pragma: nocover102 raise RuntimeError(103 "Passing a dispatcher instance to 'proxies=' is no longer "104 "supported. Use `httpx.Proxy() instead.`"105 )106 else:107 new_proxies = {}108 for key, value in proxies.items():109 if isinstance(value, (str, URL, Proxy)):110 proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value111 new_proxies[str(key)] = proxy112 elif isinstance(value, AsyncDispatcher): # pragma: nocover113 raise RuntimeError(114 "Passing a dispatcher instance to 'proxies=' is "115 "no longer supported. Use `httpx.Proxy() instead.`"116 )117 return new_proxies118119 @property120 def headers(self) -> Headers:121 """122 HTTP headers to include when sending requests.123 """124 return self._headers125126 @headers.setter127 def headers(self, headers: HeaderTypes) -> None:128 self._headers = Headers(headers)129130 @property131 def cookies(self) -> Cookies:132 """133 Cookie values to include when sending requests.134 """135 return self._cookies136137 @cookies.setter138 def cookies(self, cookies: CookieTypes) -> None:139 self._cookies = Cookies(cookies)140141 @property142 def params(self) -> QueryParams:143 """144 Query parameters to include in the URL when sending requests.145 """146 return self._params147148 @params.setter149 def params(self, params: QueryParamTypes) -> None:150 self._params = QueryParams(params)151152 def stream(153 self,154 method: str,155 url: URLTypes,156 *,157 data: RequestData = None,158 files: RequestFiles = None,159 json: typing.Any = None,160 params: QueryParamTypes = None,161 headers: HeaderTypes = None,162 cookies: CookieTypes = None,163 auth: AuthTypes = None,164 allow_redirects: bool = True,165 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,166 ) -> "StreamContextManager":167 request = self.build_request(168 method=method,169 url=url,170 data=data,171 files=files,172 json=json,173 params=params,174 headers=headers,175 cookies=cookies,176 )177 return StreamContextManager(178 client=self,179 request=request,180 auth=auth,181 allow_redirects=allow_redirects,182 timeout=timeout,183 )184185 def build_request(186 self,187 method: str,188 url: URLTypes,189 *,190 data: RequestData = None,191 files: RequestFiles = None,192 json: typing.Any = None,193 params: QueryParamTypes = None,194 headers: HeaderTypes = None,195 cookies: CookieTypes = None,196 ) -> Request:197 """198 Build and return a request instance.199 """200 url = self.merge_url(url)201 headers = self.merge_headers(headers)202 cookies = self.merge_cookies(cookies)203 params = self.merge_queryparams(params)204 return Request(205 method,206 url,207 data=data,208 files=files,209 json=json,210 params=params,211 headers=headers,212 cookies=cookies,213 )214215 def merge_url(self, url: URLTypes) -> URL:216 """217 Merge a URL argument together with any 'base_url' on the client,218 to create the URL used for the outgoing request.219 """220 url = self.base_url.join(relative_url=url)221 if url.scheme == "http" and hstspreload.in_hsts_preload(url.host):222 port = None if url.port == 80 else url.port223 url = url.copy_with(scheme="https", port=port)224 return url225226 def merge_cookies(227 self, cookies: CookieTypes = None228 ) -> typing.Optional[CookieTypes]:229 """230 Merge a cookies argument together with any cookies on the client,231 to create the cookies used for the outgoing request.232 """233 if cookies or self.cookies:234 merged_cookies = Cookies(self.cookies)235 merged_cookies.update(cookies)236 return merged_cookies237 return cookies238239 def merge_headers(240 self, headers: HeaderTypes = None241 ) -> typing.Optional[HeaderTypes]:242 """243 Merge a headers argument together with any headers on the client,244 to create the headers used for the outgoing request.245 """246 if headers or self.headers:247 merged_headers = Headers(self.headers)248 merged_headers.update(headers)249 return merged_headers250 return headers251252 def merge_queryparams(253 self, params: QueryParamTypes = None254 ) -> typing.Optional[QueryParamTypes]:255 """256 Merge a queryparams argument together with any queryparams on the client,257 to create the queryparams used for the outgoing request.258 """259 if params or self.params:260 merged_queryparams = QueryParams(self.params)261 merged_queryparams.update(params)262 return merged_queryparams263 return params264265 def build_auth(self, request: Request, auth: AuthTypes = None) -> Auth:266 auth = self.auth if auth is None else auth267268 if auth is not None:269 if isinstance(auth, tuple):270 return BasicAuth(username=auth[0], password=auth[1])271 elif isinstance(auth, Auth):272 return auth273 elif callable(auth):274 return FunctionAuth(func=auth)275 raise TypeError('Invalid "auth" argument.')276277 username, password = request.url.username, request.url.password278 if username or password:279 return BasicAuth(username=username, password=password)280281 if self.trust_env and "Authorization" not in request.headers:282 credentials = self.netrc.get_credentials(request.url.authority)283 if credentials is not None:284 return BasicAuth(username=credentials[0], password=credentials[1])285286 return Auth()287288 def build_redirect_request(self, request: Request, response: Response) -> Request:289 """290 Given a request and a redirect response, return a new request that291 should be used to effect the redirect.292 """293 method = self.redirect_method(request, response)294 url = self.redirect_url(request, response)295 headers = self.redirect_headers(request, url, method)296 stream = self.redirect_stream(request, method)297 cookies = Cookies(self.cookies)298 return Request(299 method=method, url=url, headers=headers, cookies=cookies, stream=stream300 )301302 def redirect_method(self, request: Request, response: Response) -> str:303 """304 When being redirected we may want to change the method of the request305 based on certain specs or browser behavior.306 """307 method = request.method308309 # https://tools.ietf.org/html/rfc7231#section-6.4.4310 if response.status_code == codes.SEE_OTHER and method != "HEAD":311 method = "GET"312313 # Do what the browsers do, despite standards...314 # Turn 302s into GETs.315 if response.status_code == codes.FOUND and method != "HEAD":316 method = "GET"317318 # If a POST is responded to with a 301, turn it into a GET.319 # This bizarre behaviour is explained in 'requests' issue 1704.320 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":321 method = "GET"322323 return method324325 def redirect_url(self, request: Request, response: Response) -> URL:326 """327 Return the URL for the redirect to follow.328 """329 location = response.headers["Location"]330331 url = URL(location, allow_relative=True)332333 # Handle malformed 'Location' headers that are "absolute" form, have no host.334 # See: https://github.com/encode/httpx/issues/771335 if url.scheme and not url.host:336 url = url.copy_with(host=request.url.host)337338 # Facilitate relative 'Location' headers, as allowed by RFC 7231.339 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')340 if url.is_relative_url:341 url = request.url.join(url)342343 # Attach previous fragment if needed (RFC 7231 7.1.2)344 if request.url.fragment and not url.fragment:345 url = url.copy_with(fragment=request.url.fragment)346347 return url348349 def redirect_headers(self, request: Request, url: URL, method: str) -> Headers:350 """351 Return the headers that should be used for the redirect request.352 """353 headers = Headers(request.headers)354355 if Origin(url) != Origin(request.url):356 # Strip Authorization headers when responses are redirected away from357 # the origin.358 headers.pop("Authorization", None)359 headers["Host"] = url.authority360361 if method != request.method and method == "GET":362 # If we've switch to a 'GET' request, then strip any headers which363 # are only relevant to the request body.364 headers.pop("Content-Length", None)365 headers.pop("Transfer-Encoding", None)366367 # We should use the client cookie store to determine any cookie header,368 # rather than whatever was on the original outgoing request.369 headers.pop("Cookie", None)370371 return headers372373 def redirect_stream(374 self, request: Request, method: str375 ) -> typing.Optional[ContentStream]:376 """377 Return the body that should be used for the redirect request.378 """379 if method != request.method and method == "GET":380 return None381382 if not request.stream.can_replay():383 raise RequestBodyUnavailable(384 "Got a redirect response, but the request body was streaming "385 "and is no longer available."386 )387388 return request.stream389390391class Client(BaseClient):392 """393 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.394395 Usage:396397 ```python398 >>> client = httpx.Client()399 >>> response = client.get('https://example.org')400 ```401402 **Parameters:**403404 * **auth** - *(optional)* An authentication class to use when sending405 requests.406 * **params** - *(optional)* Query parameters to include in request URLs, as407 a string, dictionary, or list of two-tuples.408 * **headers** - *(optional)* Dictionary of HTTP headers to include when409 sending requests.410 * **cookies** - *(optional)* Dictionary of Cookie items to include when411 sending requests.412 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to413 verify the identity of requested hosts. Either `True` (default CA bundle),414 a path to an SSL certificate file, or `False` (disable verification).415 * **cert** - *(optional)* An SSL certificate used by the requested host416 to authenticate the client. Either a path to an SSL certificate file, or417 two-tuple of (certificate file, key file), or a three-tuple of (certificate418 file, key file, password).419 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy420 URLs.421 * **timeout** - *(optional)* The timeout configuration to use when sending422 requests.423 * **pool_limits** - *(optional)* The connection pool configuration to use424 when determining the maximum number of concurrently open HTTP connections.425 * **max_redirects** - *(optional)* The maximum number of redirect responses426 that should be followed.427 * **base_url** - *(optional)* A URL to use as the base when building428 request URLs.429 * **dispatch** - *(optional)* A dispatch class to use for sending requests430 over the network.431 * **app** - *(optional)* An ASGI application to send requests to,432 rather than sending actual network requests.433 * **trust_env** - *(optional)* Enables or disables usage of environment434 variables for configuration.435 """436437 def __init__(438 self,439 *,440 auth: AuthTypes = None,441 params: QueryParamTypes = None,442 headers: HeaderTypes = None,443 cookies: CookieTypes = None,444 verify: VerifyTypes = True,445 cert: CertTypes = None,446 proxies: ProxiesTypes = None,447 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,448 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,449 max_redirects: int = DEFAULT_MAX_REDIRECTS,450 base_url: URLTypes = None,451 dispatch: SyncDispatcher = None,452 app: typing.Callable = None,453 trust_env: bool = True,454 ):455 super().__init__(456 auth=auth,457 params=params,458 headers=headers,459 cookies=cookies,460 timeout=timeout,461 max_redirects=max_redirects,462 base_url=base_url,463 trust_env=trust_env,464 )465466 proxy_map = self.get_proxy_map(proxies, trust_env)467468 self.dispatch = self.init_dispatch(469 verify=verify,470 cert=cert,471 pool_limits=pool_limits,472 dispatch=dispatch,473 app=app,474 trust_env=trust_env,475 )476 self.proxies: typing.Dict[str, SyncDispatcher] = {477 key: self.init_proxy_dispatch(478 proxy,479 verify=verify,480 cert=cert,481 pool_limits=pool_limits,482 trust_env=trust_env,483 )484 for key, proxy in proxy_map.items()485 }486487 def init_dispatch(488 self,489 verify: VerifyTypes = True,490 cert: CertTypes = None,491 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,492 dispatch: SyncDispatcher = None,493 app: typing.Callable = None,494 trust_env: bool = True,495 ) -> SyncDispatcher:496 if dispatch is not None:497 return dispatch498499 if app is not None:500 return WSGIDispatch(app=app)501502 return URLLib3Dispatcher(503 verify=verify, cert=cert, pool_limits=pool_limits, trust_env=trust_env,504 )505506 def init_proxy_dispatch(507 self,508 proxy: Proxy,509 verify: VerifyTypes = True,510 cert: CertTypes = None,511 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,512 trust_env: bool = True,513 ) -> SyncDispatcher:514 return URLLib3Dispatcher(515 proxy=proxy,516 verify=verify,517 cert=cert,518 pool_limits=pool_limits,519 trust_env=trust_env,520 )521522 def dispatcher_for_url(self, url: URL) -> SyncDispatcher:523 """524 Returns the SyncDispatcher instance that should be used for a given URL.525 This will either be the standard connection pool, or a proxy.526 """527 if self.proxies:528 is_default_port = (url.scheme == "http" and url.port == 80) or (529 url.scheme == "https" and url.port == 443530 )531 hostname = f"{url.host}:{url.port}"532 proxy_keys = (533 f"{url.scheme}://{hostname}",534 f"{url.scheme}://{url.host}" if is_default_port else None,535 f"all://{hostname}",536 f"all://{url.host}" if is_default_port else None,537 url.scheme,538 "all",539 )540 for proxy_key in proxy_keys:541 if proxy_key and proxy_key in self.proxies:542 dispatcher = self.proxies[proxy_key]543 return dispatcher544545 return self.dispatch546547 def request(548 self,549 method: str,550 url: URLTypes,551 *,552 data: RequestData = None,553 files: RequestFiles = None,554 json: typing.Any = None,555 params: QueryParamTypes = None,556 headers: HeaderTypes = None,557 cookies: CookieTypes = None,558 auth: AuthTypes = None,559 allow_redirects: bool = True,560 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,561 ) -> Response:562 request = self.build_request(563 method=method,564 url=url,565 data=data,566 files=files,567 json=json,568 params=params,569 headers=headers,570 cookies=cookies,571 )572 return self.send(573 request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,574 )575576 def send(577 self,578 request: Request,579 *,580 stream: bool = False,581 auth: AuthTypes = None,582 allow_redirects: bool = True,583 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,584 ) -> Response:585 if request.url.scheme not in ("http", "https"):586 raise InvalidURL('URL scheme must be "http" or "https".')587588 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)589590 auth = self.build_auth(request, auth)591592 response = self.send_handling_redirects(593 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,594 )595596 if not stream:597 try:598 response.read()599 finally:600 response.close()601602 return response603604 def send_handling_redirects(605 self,606 request: Request,607 auth: Auth,608 timeout: Timeout,609 allow_redirects: bool = True,610 history: typing.List[Response] = None,611 ) -> Response:612 if history is None:613 history = []614615 while True:616 if len(history) > self.max_redirects:617 raise TooManyRedirects()618 urls = ((resp.request.method, resp.url) for resp in history)619 if (request.method, request.url) in urls:620 raise RedirectLoop()621622 response = self.send_handling_auth(623 request, auth=auth, timeout=timeout, history=history624 )625 response.history = list(history)626627 if not response.is_redirect:628 return response629630 if allow_redirects:631 response.read()632 request = self.build_redirect_request(request, response)633 history = history + [response]634635 if not allow_redirects:636 response.call_next = functools.partial(637 self.send_handling_redirects,638 request=request,639 auth=auth,640 timeout=timeout,641 allow_redirects=False,642 history=history,643 )644 return response645646 def send_handling_auth(647 self,648 request: Request,649 history: typing.List[Response],650 auth: Auth,651 timeout: Timeout,652 ) -> Response:653 if auth.requires_request_body:654 request.read()655656 auth_flow = auth.auth_flow(request)657 request = next(auth_flow)658 while True:659 response = self.send_single_request(request, timeout)660 try:661 next_request = auth_flow.send(response)662 except StopIteration:663 return response664 except BaseException as exc:665 response.close()666 raise exc from None667 else:668 response.history = list(history)669 response.read()670 request = next_request671 history.append(response)672673 def send_single_request(self, request: Request, timeout: Timeout,) -> Response:674 """675 Sends a single request, without handling any redirections.676 """677678 dispatcher = self.dispatcher_for_url(request.url)679680 try:681 response = dispatcher.send(request, timeout=timeout)682 except HTTPError as exc:683 # Add the original request to any HTTPError unless684 # there'a already a request attached in the case of685 # a ProxyError.686 if exc.request is None:687 exc.request = request688 raise689690 self.cookies.extract_cookies(response)691692 status = f"{response.status_code} {response.reason_phrase}"693 response_line = f"{response.http_version} {status}"694 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')695696 return response697698 def get(699 self,700 url: URLTypes,701 *,702 params: QueryParamTypes = None,703 headers: HeaderTypes = None,704 cookies: CookieTypes = None,705 auth: AuthTypes = None,706 allow_redirects: bool = True,707 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,708 ) -> Response:709 return self.request(710 "GET",711 url,712 params=params,713 headers=headers,714 cookies=cookies,715 auth=auth,716 allow_redirects=allow_redirects,717 timeout=timeout,718 )719720 def options(721 self,722 url: URLTypes,723 *,724 params: QueryParamTypes = None,725 headers: HeaderTypes = None,726 cookies: CookieTypes = None,727 auth: AuthTypes = None,728 allow_redirects: bool = True,729 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,730 ) -> Response:731 return self.request(732 "OPTIONS",733 url,734 params=params,735 headers=headers,736 cookies=cookies,737 auth=auth,738 allow_redirects=allow_redirects,739 timeout=timeout,740 )741742 def head(743 self,744 url: URLTypes,745 *,746 params: QueryParamTypes = None,747 headers: HeaderTypes = None,748 cookies: CookieTypes = None,749 auth: AuthTypes = None,750 allow_redirects: bool = False, # NOTE: Differs to usual default.751 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,752 ) -> Response:753 return self.request(754 "HEAD",755 url,756 params=params,757 headers=headers,758 cookies=cookies,759 auth=auth,760 allow_redirects=allow_redirects,761 timeout=timeout,762 )763764 def post(765 self,766 url: URLTypes,767 *,768 data: RequestData = None,769 files: RequestFiles = None,770 json: typing.Any = None,771 params: QueryParamTypes = None,772 headers: HeaderTypes = None,773 cookies: CookieTypes = None,774 auth: AuthTypes = None,775 allow_redirects: bool = True,776 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,777 ) -> Response:778 return self.request(779 "POST",780 url,781 data=data,782 files=files,783 json=json,784 params=params,785 headers=headers,786 cookies=cookies,787 auth=auth,788 allow_redirects=allow_redirects,789 timeout=timeout,790 )791792 def put(793 self,794 url: URLTypes,795 *,796 data: RequestData = None,797 files: RequestFiles = None,798 json: typing.Any = None,799 params: QueryParamTypes = None,800 headers: HeaderTypes = None,801 cookies: CookieTypes = None,802 auth: AuthTypes = None,803 allow_redirects: bool = True,804 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,805 ) -> Response:806 return self.request(807 "PUT",808 url,809 data=data,810 files=files,811 json=json,812 params=params,813 headers=headers,814 cookies=cookies,815 auth=auth,816 allow_redirects=allow_redirects,817 timeout=timeout,818 )819820 def patch(821 self,822 url: URLTypes,823 *,824 data: RequestData = None,825 files: RequestFiles = None,826 json: typing.Any = None,827 params: QueryParamTypes = None,828 headers: HeaderTypes = None,829 cookies: CookieTypes = None,830 auth: AuthTypes = None,831 allow_redirects: bool = True,832 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,833 ) -> Response:834 return self.request(835 "PATCH",836 url,837 data=data,838 files=files,839 json=json,840 params=params,841 headers=headers,842 cookies=cookies,843 auth=auth,844 allow_redirects=allow_redirects,845 timeout=timeout,846 )847848 def delete(849 self,850 url: URLTypes,851 *,852 params: QueryParamTypes = None,853 headers: HeaderTypes = None,854 cookies: CookieTypes = None,855 auth: AuthTypes = None,856 allow_redirects: bool = True,857 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,858 ) -> Response:859 return self.request(860 "DELETE",861 url,862 params=params,863 headers=headers,864 cookies=cookies,865 auth=auth,866 allow_redirects=allow_redirects,867 timeout=timeout,868 )869870 def close(self) -> None:871 self.dispatch.close()872873 def __enter__(self) -> "Client":874 return self875876 def __exit__(877 self,878 exc_type: typing.Type[BaseException] = None,879 exc_value: BaseException = None,880 traceback: TracebackType = None,881 ) -> None:882 self.close()883884885class AsyncClient(BaseClient):886 """887 An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,888 cookie persistence, etc.889890 Usage:891892 ```python893 >>> async with httpx.AsyncClient() as client:894 >>> response = await client.get('https://example.org')895 ```896897 **Parameters:**898899 * **auth** - *(optional)* An authentication class to use when sending900 requests.901 * **params** - *(optional)* Query parameters to include in request URLs, as902 a string, dictionary, or list of two-tuples.903 * **headers** - *(optional)* Dictionary of HTTP headers to include when904 sending requests.905 * **cookies** - *(optional)* Dictionary of Cookie items to include when906 sending requests.907 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to908 verify the identity of requested hosts. Either `True` (default CA bundle),909 a path to an SSL certificate file, or `False` (disable verification).910 * **cert** - *(optional)* An SSL certificate used by the requested host911 to authenticate the client. Either a path to an SSL certificate file, or912 two-tuple of (certificate file, key file), or a three-tuple of (certificate913 file, key file, password).914 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be915 enabled. Defaults to `False`.916 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy917 URLs.918 * **timeout** - *(optional)* The timeout configuration to use when sending919 requests.920 * **pool_limits** - *(optional)* The connection pool configuration to use921 when determining the maximum number of concurrently open HTTP connections.922 * **max_redirects** - *(optional)* The maximum number of redirect responses923 that should be followed.924 * **base_url** - *(optional)* A URL to use as the base when building925 request URLs.926 * **dispatch** - *(optional)* A dispatch class to use for sending requests927 over the network.928 * **app** - *(optional)* An ASGI application to send requests to,929 rather than sending actual network requests.930 * **backend** - *(optional)* A concurrency backend to use when issuing931 async requests. Either 'auto', 'asyncio', 'trio', or a `ConcurrencyBackend`932 instance. Defaults to 'auto', for autodetection.933 * **trust_env** - *(optional)* Enables or disables usage of environment934 variables for configuration.935 * **uds** - *(optional)* A path to a Unix domain socket to connect through.936 """937938 def __init__(939 self,940 *,941 auth: AuthTypes = None,942 params: QueryParamTypes = None,943 headers: HeaderTypes = None,944 cookies: CookieTypes = None,945 verify: VerifyTypes = True,946 cert: CertTypes = None,947 http2: bool = False,948 proxies: ProxiesTypes = None,949 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,950 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,951 max_redirects: int = DEFAULT_MAX_REDIRECTS,952 base_url: URLTypes = None,953 dispatch: AsyncDispatcher = None,954 app: typing.Callable = None,955 backend: typing.Union[str, ConcurrencyBackend] = "auto",956 trust_env: bool = True,957 uds: str = None,958 ):959 super().__init__(960 auth=auth,961 params=params,962 headers=headers,963 cookies=cookies,964 timeout=timeout,965 max_redirects=max_redirects,966 base_url=base_url,967 trust_env=trust_env,968 )969970 proxy_map = self.get_proxy_map(proxies, trust_env)971972 self.dispatch = self.init_dispatch(973 verify=verify,974 cert=cert,975 http2=http2,976 pool_limits=pool_limits,977 dispatch=dispatch,978 app=app,979 backend=backend,980 trust_env=trust_env,981 uds=uds,982 )983 self.proxies: typing.Dict[str, AsyncDispatcher] = {984 key: self.init_proxy_dispatch(985 proxy,986 verify=verify,987 cert=cert,988 http2=http2,989 pool_limits=pool_limits,990 backend=backend,991 trust_env=trust_env,992 )993 for key, proxy in proxy_map.items()994 }995996 def init_dispatch(997 self,998 verify: VerifyTypes = True,999 cert: CertTypes = None,1000 http2: bool = False,1001 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1002 dispatch: AsyncDispatcher = None,1003 app: typing.Callable = None,1004 backend: typing.Union[str, ConcurrencyBackend] = "auto",1005 trust_env: bool = True,1006 uds: str = None,1007 ) -> AsyncDispatcher:1008 if dispatch is not None:1009 return dispatch10101011 if app is not None:1012 return ASGIDispatch(app=app)10131014 return ConnectionPool(1015 verify=verify,1016 cert=cert,1017 http2=http2,1018 pool_limits=pool_limits,1019 backend=backend,1020 trust_env=trust_env,1021 uds=uds,1022 )10231024 def init_proxy_dispatch(1025 self,1026 proxy: Proxy,1027 verify: VerifyTypes = True,1028 cert: CertTypes = None,1029 http2: bool = False,1030 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1031 backend: typing.Union[str, ConcurrencyBackend] = "auto",1032 trust_env: bool = True,1033 ) -> AsyncDispatcher:1034 return HTTPProxy(1035 proxy_url=proxy.url,1036 proxy_headers=proxy.headers,1037 proxy_mode=proxy.mode,1038 verify=verify,1039 cert=cert,1040 http2=http2,1041 pool_limits=pool_limits,1042 backend=backend,1043 trust_env=trust_env,1044 )10451046 def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:1047 """1048 Returns the AsyncDispatcher instance that should be used for a given URL.1049 This will either be the standard connection pool, or a proxy.1050 """1051 if self.proxies:1052 is_default_port = (url.scheme == "http" and url.port == 80) or (1053 url.scheme == "https" and url.port == 4431054 )1055 hostname = f"{url.host}:{url.port}"1056 proxy_keys = (1057 f"{url.scheme}://{hostname}",1058 f"{url.scheme}://{url.host}" if is_default_port else None,1059 f"all://{hostname}",1060 f"all://{url.host}" if is_default_port else None,1061 url.scheme,1062 "all",1063 )1064 for proxy_key in proxy_keys:1065 if proxy_key and proxy_key in self.proxies:1066 dispatcher = self.proxies[proxy_key]1067 return dispatcher10681069 return self.dispatch10701071 async def request(1072 self,1073 method: str,1074 url: URLTypes,1075 *,1076 data: RequestData = None,1077 files: RequestFiles = None,1078 json: typing.Any = None,1079 params: QueryParamTypes = None,1080 headers: HeaderTypes = None,1081 cookies: CookieTypes = None,1082 auth: AuthTypes = None,1083 allow_redirects: bool = True,1084 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1085 ) -> Response:1086 request = self.build_request(1087 method=method,1088 url=url,1089 data=data,1090 files=files,1091 json=json,1092 params=params,1093 headers=headers,1094 cookies=cookies,1095 )1096 response = await self.send(1097 request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,1098 )1099 return response11001101 async def send(1102 self,1103 request: Request,1104 *,1105 stream: bool = False,1106 auth: AuthTypes = None,1107 allow_redirects: bool = True,1108 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1109 ) -> Response:1110 if request.url.scheme not in ("http", "https"):1111 raise InvalidURL('URL scheme must be "http" or "https".')11121113 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)11141115 auth = self.build_auth(request, auth)11161117 response = await self.send_handling_redirects(1118 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,1119 )11201121 if not stream:1122 try:1123 await response.aread()1124 finally:1125 await response.aclose()11261127 return response11281129 async def send_handling_redirects(1130 self,1131 request: Request,1132 auth: Auth,1133 timeout: Timeout,1134 allow_redirects: bool = True,1135 history: typing.List[Response] = None,1136 ) -> Response:1137 if history is None:1138 history = []11391140 while True:1141 if len(history) > self.max_redirects:1142 raise TooManyRedirects()1143 urls = ((resp.request.method, resp.url) for resp in history)1144 if (request.method, request.url) in urls:1145 raise RedirectLoop()11461147 response = await self.send_handling_auth(1148 request, auth=auth, timeout=timeout, history=history1149 )1150 response.history = list(history)11511152 if not response.is_redirect:1153 return response11541155 if allow_redirects:1156 await response.aread()1157 request = self.build_redirect_request(request, response)1158 history = history + [response]11591160 if not allow_redirects:1161 response.call_next = functools.partial(1162 self.send_handling_redirects,1163 request=request,1164 auth=auth,1165 timeout=timeout,1166 allow_redirects=False,1167 history=history,1168 )1169 return response11701171 async def send_handling_auth(1172 self,1173 request: Request,1174 history: typing.List[Response],1175 auth: Auth,1176 timeout: Timeout,1177 ) -> Response:1178 if auth.requires_request_body:1179 await request.aread()11801181 auth_flow = auth.auth_flow(request)1182 request = next(auth_flow)1183 while True:1184 response = await self.send_single_request(request, timeout)1185 try:1186 next_request = auth_flow.send(response)1187 except StopIteration:1188 return response1189 except BaseException as exc:1190 await response.aclose()1191 raise exc from None1192 else:1193 response.history = list(history)1194 await response.aread()1195 request = next_request1196 history.append(response)11971198 async def send_single_request(1199 self, request: Request, timeout: Timeout,1200 ) -> Response:1201 """1202 Sends a single request, without handling any redirections.1203 """12041205 dispatcher = self.dispatcher_for_url(request.url)12061207 try:1208 response = await dispatcher.send(request, timeout=timeout)1209 except HTTPError as exc:1210 # Add the original request to any HTTPError unless1211 # there'a already a request attached in the case of1212 # a ProxyError.1213 if exc.request is None:1214 exc.request = request1215 raise12161217 self.cookies.extract_cookies(response)12181219 status = f"{response.status_code} {response.reason_phrase}"1220 response_line = f"{response.http_version} {status}"1221 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')12221223 return response12241225 async def get(1226 self,1227 url: URLTypes,1228 *,1229 params: QueryParamTypes = None,1230 headers: HeaderTypes = None,1231 cookies: CookieTypes = None,1232 auth: AuthTypes = None,1233 allow_redirects: bool = True,1234 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1235 ) -> Response:1236 return await self.request(1237 "GET",1238 url,1239 params=params,1240 headers=headers,1241 cookies=cookies,1242 auth=auth,1243 allow_redirects=allow_redirects,1244 timeout=timeout,1245 )12461247 async def options(1248 self,1249 url: URLTypes,1250 *,1251 params: QueryParamTypes = None,1252 headers: HeaderTypes = None,1253 cookies: CookieTypes = None,1254 auth: AuthTypes = None,1255 allow_redirects: bool = True,1256 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1257 ) -> Response:1258 return await self.request(1259 "OPTIONS",1260 url,1261 params=params,1262 headers=headers,1263 cookies=cookies,1264 auth=auth,1265 allow_redirects=allow_redirects,1266 timeout=timeout,1267 )12681269 async def head(1270 self,1271 url: URLTypes,1272 *,1273 params: QueryParamTypes = None,1274 headers: HeaderTypes = None,1275 cookies: CookieTypes = None,1276 auth: AuthTypes = None,1277 allow_redirects: bool = False, # NOTE: Differs to usual default.1278 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1279 ) -> Response:1280 return await self.request(1281 "HEAD",1282 url,1283 params=params,1284 headers=headers,1285 cookies=cookies,1286 auth=auth,1287 allow_redirects=allow_redirects,1288 timeout=timeout,1289 )12901291 async def post(1292 self,1293 url: URLTypes,1294 *,1295 data: RequestData = None,1296 files: RequestFiles = None,1297 json: typing.Any = None,1298 params: QueryParamTypes = None,1299 headers: HeaderTypes = None,1300 cookies: CookieTypes = None,1301 auth: AuthTypes = None,1302 allow_redirects: bool = True,1303 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1304 ) -> Response:1305 return await self.request(1306 "POST",1307 url,1308 data=data,1309 files=files,1310 json=json,1311 params=params,1312 headers=headers,1313 cookies=cookies,1314 auth=auth,1315 allow_redirects=allow_redirects,1316 timeout=timeout,1317 )13181319 async def put(1320 self,1321 url: URLTypes,1322 *,1323 data: RequestData = None,1324 files: RequestFiles = None,1325 json: typing.Any = None,1326 params: QueryParamTypes = None,1327 headers: HeaderTypes = None,1328 cookies: CookieTypes = None,1329 auth: AuthTypes = None,1330 allow_redirects: bool = True,1331 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1332 ) -> Response:1333 return await self.request(1334 "PUT",1335 url,1336 data=data,1337 files=files,1338 json=json,1339 params=params,1340 headers=headers,1341 cookies=cookies,1342 auth=auth,1343 allow_redirects=allow_redirects,1344 timeout=timeout,1345 )13461347 async def patch(1348 self,1349 url: URLTypes,1350 *,1351 data: RequestData = None,1352 files: RequestFiles = None,1353 json: typing.Any = None,1354 params: QueryParamTypes = None,1355 headers: HeaderTypes = None,1356 cookies: CookieTypes = None,1357 auth: AuthTypes = None,1358 allow_redirects: bool = True,1359 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1360 ) -> Response:1361 return await self.request(1362 "PATCH",1363 url,1364 data=data,1365 files=files,1366 json=json,1367 params=params,1368 headers=headers,1369 cookies=cookies,1370 auth=auth,1371 allow_redirects=allow_redirects,1372 timeout=timeout,1373 )13741375 async def delete(1376 self,1377 url: URLTypes,1378 *,1379 params: QueryParamTypes = None,1380 headers: HeaderTypes = None,1381 cookies: CookieTypes = None,1382 auth: AuthTypes = None,1383 allow_redirects: bool = True,1384 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1385 ) -> Response:1386 return await self.request(1387 "DELETE",1388 url,1389 params=params,1390 headers=headers,1391 cookies=cookies,1392 auth=auth,1393 allow_redirects=allow_redirects,1394 timeout=timeout,1395 )13961397 async def aclose(self) -> None:1398 await self.dispatch.close()13991400 async def __aenter__(self) -> "AsyncClient":1401 return self14021403 async def __aexit__(1404 self,1405 exc_type: typing.Type[BaseException] = None,1406 exc_value: BaseException = None,1407 traceback: TracebackType = None,1408 ) -> None:1409 await self.aclose()141014111412class StreamContextManager:1413 def __init__(1414 self,1415 client: BaseClient,1416 request: Request,1417 *,1418 auth: AuthTypes = None,1419 allow_redirects: bool = True,1420 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1421 close_client: bool = False,1422 ) -> None:1423 self.client = client1424 self.request = request1425 self.auth = auth1426 self.allow_redirects = allow_redirects1427 self.timeout = timeout1428 self.close_client = close_client14291430 def __enter__(self) -> "Response":1431 assert isinstance(self.client, Client)1432 self.response = self.client.send(1433 request=self.request,1434 auth=self.auth,1435 allow_redirects=self.allow_redirects,1436 timeout=self.timeout,1437 stream=True,1438 )1439 return self.response14401441 def __exit__(1442 self,1443 exc_type: typing.Type[BaseException] = None,1444 exc_value: BaseException = None,1445 traceback: TracebackType = None,1446 ) -> None:1447 assert isinstance(self.client, Client)1448 self.response.close()1449 if self.close_client:1450 self.client.close()14511452 async def __aenter__(self) -> "Response":1453 assert isinstance(self.client, AsyncClient)1454 self.response = await self.client.send(1455 request=self.request,1456 auth=self.auth,1457 allow_redirects=self.allow_redirects,1458 timeout=self.timeout,1459 stream=True,1460 )1461 return self.response14621463 async def __aexit__(1464 self,1465 exc_type: typing.Type[BaseException] = None,1466 exc_value: BaseException = None,1467 traceback: TracebackType = None,1468 ) -> None:1469 assert isinstance(self.client, AsyncClient)1470 await self.response.aclose()1471 if self.close_client:1472 await self.client.aclose()
added:httpx/_config.py+357 added
1import os2import ssl3import typing4from base64 import b64encode5from pathlib import Path67import certifi89from ._models import URL, Headers, HeaderTypes, URLTypes10from ._utils import get_ca_bundle_from_env, get_logger1112CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]13VerifyTypes = typing.Union[str, bool, ssl.SSLContext]14TimeoutTypes = typing.Union[15 None, float, typing.Tuple[float, float, float, float], "Timeout"16]17ProxiesTypes = typing.Union[18 URLTypes, "Proxy", typing.Dict[URLTypes, typing.Union[URLTypes, "Proxy"]]19]202122DEFAULT_CIPHERS = ":".join(23 [24 "ECDHE+AESGCM",25 "ECDHE+CHACHA20",26 "DHE+AESGCM",27 "DHE+CHACHA20",28 "ECDH+AESGCM",29 "DH+AESGCM",30 "ECDH+AES",31 "DH+AES",32 "RSA+AESGCM",33 "RSA+AES",34 "!aNULL",35 "!eNULL",36 "!MD5",37 "!DSS",38 ]39)404142logger = get_logger(__name__)434445class UnsetType:46 pass # pragma: nocover474849UNSET = UnsetType()505152class SSLConfig:53 """54 SSL Configuration.55 """5657 DEFAULT_CA_BUNDLE_PATH = Path(certifi.where())5859 def __init__(60 self,61 *,62 cert: CertTypes = None,63 verify: VerifyTypes = True,64 trust_env: bool = None,65 http2: bool = False,66 ):67 self.cert = cert68 self.verify = verify69 self.trust_env = trust_env70 self.http2 = http271 self.ssl_context = self.load_ssl_context()7273 def __eq__(self, other: typing.Any) -> bool:74 return (75 isinstance(other, self.__class__)76 and self.cert == other.cert77 and self.verify == other.verify78 )7980 def __repr__(self) -> str:81 class_name = self.__class__.__name__82 return f"{class_name}(cert={self.cert}, verify={self.verify})"8384 def load_ssl_context(self) -> ssl.SSLContext:85 logger.trace(86 f"load_ssl_context "87 f"verify={self.verify!r} "88 f"cert={self.cert!r} "89 f"trust_env={self.trust_env!r} "90 f"http2={self.http2!r}"91 )9293 if self.verify:94 return self.load_ssl_context_verify()95 return self.load_ssl_context_no_verify()9697 def load_ssl_context_no_verify(self) -> ssl.SSLContext:98 """99 Return an SSL context for unverified connections.100 """101 context = self._create_default_ssl_context()102 context.verify_mode = ssl.CERT_NONE103 context.check_hostname = False104 return context105106 def load_ssl_context_verify(self) -> ssl.SSLContext:107 """108 Return an SSL context for verified connections.109 """110 if self.trust_env and self.verify is True:111 ca_bundle = get_ca_bundle_from_env()112 if ca_bundle is not None:113 self.verify = ca_bundle # type: ignore114115 if isinstance(self.verify, ssl.SSLContext):116 # Allow passing in our own SSLContext object that's pre-configured.117 context = self.verify118 self._load_client_certs(context)119 return context120 elif isinstance(self.verify, bool):121 ca_bundle_path = self.DEFAULT_CA_BUNDLE_PATH122 elif Path(self.verify).exists():123 ca_bundle_path = Path(self.verify)124 else:125 raise IOError(126 "Could not find a suitable TLS CA certificate bundle, "127 "invalid path: {}".format(self.verify)128 )129130 context = self._create_default_ssl_context()131 context.verify_mode = ssl.CERT_REQUIRED132 context.check_hostname = True133134 # Signal to server support for PHA in TLS 1.3. Raises an135 # AttributeError if only read-only access is implemented.136 try:137 context.post_handshake_auth = True # type: ignore138 except AttributeError: # pragma: nocover139 pass140141 # Disable using 'commonName' for SSLContext.check_hostname142 # when the 'subjectAltName' extension isn't available.143 try:144 context.hostname_checks_common_name = False # type: ignore145 except AttributeError: # pragma: nocover146 pass147148 if ca_bundle_path.is_file():149 logger.trace(f"load_verify_locations cafile={ca_bundle_path!s}")150 context.load_verify_locations(cafile=str(ca_bundle_path))151 elif ca_bundle_path.is_dir():152 logger.trace(f"load_verify_locations capath={ca_bundle_path!s}")153 context.load_verify_locations(capath=str(ca_bundle_path))154155 self._load_client_certs(context)156157 return context158159 def _create_default_ssl_context(self) -> ssl.SSLContext:160 """161 Creates the default SSLContext object that's used for both verified162 and unverified connections.163 """164 context = ssl.SSLContext(ssl.PROTOCOL_TLS)165 context.options |= ssl.OP_NO_SSLv2166 context.options |= ssl.OP_NO_SSLv3167 context.options |= ssl.OP_NO_TLSv1168 context.options |= ssl.OP_NO_TLSv1_1169 context.options |= ssl.OP_NO_COMPRESSION170 context.set_ciphers(DEFAULT_CIPHERS)171172 if ssl.HAS_ALPN:173 alpn_idents = ["http/1.1", "h2"] if self.http2 else ["http/1.1"]174 context.set_alpn_protocols(alpn_idents)175176 if hasattr(context, "keylog_filename"): # pragma: nocover (Available in 3.8+)177 keylogfile = os.environ.get("SSLKEYLOGFILE")178 if keylogfile and self.trust_env:179 context.keylog_filename = keylogfile # type: ignore180181 return context182183 def _load_client_certs(self, ssl_context: ssl.SSLContext) -> None:184 """185 Loads client certificates into our SSLContext object186 """187 if self.cert is not None:188 if isinstance(self.cert, str):189 ssl_context.load_cert_chain(certfile=self.cert)190 elif isinstance(self.cert, tuple) and len(self.cert) == 2:191 ssl_context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])192 elif isinstance(self.cert, tuple) and len(self.cert) == 3:193 ssl_context.load_cert_chain(194 certfile=self.cert[0],195 keyfile=self.cert[1],196 password=self.cert[2], # type: ignore197 )198199200class Timeout:201 """202 Timeout configuration.203204 **Usage**:205206 Timeout() # No timeout.207 Timeout(5.0) # 5s timeout on all operations.208 Timeout(connect_timeout=5.0) # 5s timeout on connect, no other timeouts.209 Timeout(5.0, connect_timeout=10.0) # 10s timeout on connect. 5s timeout elsewhere.210 Timeout(5.0, pool_timeout=None) # No timeout on acquiring connection from pool.211 # 5s timeout elsewhere.212 """213214 def __init__(215 self,216 timeout: TimeoutTypes = None,217 *,218 connect_timeout: typing.Union[None, float, UnsetType] = UNSET,219 read_timeout: typing.Union[None, float, UnsetType] = UNSET,220 write_timeout: typing.Union[None, float, UnsetType] = UNSET,221 pool_timeout: typing.Union[None, float, UnsetType] = UNSET,222 ):223 if isinstance(timeout, Timeout):224 # Passed as a single explicit Timeout.225 assert connect_timeout is UNSET226 assert read_timeout is UNSET227 assert write_timeout is UNSET228 assert pool_timeout is UNSET229 self.connect_timeout = (230 timeout.connect_timeout231 ) # type: typing.Optional[float]232 self.read_timeout = timeout.read_timeout # type: typing.Optional[float]233 self.write_timeout = timeout.write_timeout # type: typing.Optional[float]234 self.pool_timeout = timeout.pool_timeout # type: typing.Optional[float]235 elif isinstance(timeout, tuple):236 # Passed as a tuple.237 self.connect_timeout = timeout[0]238 self.read_timeout = timeout[1]239 self.write_timeout = None if len(timeout) < 3 else timeout[2]240 self.pool_timeout = None if len(timeout) < 4 else timeout[3]241 else:242 self.connect_timeout = (243 timeout if isinstance(connect_timeout, UnsetType) else connect_timeout244 )245 self.read_timeout = (246 timeout if isinstance(read_timeout, UnsetType) else read_timeout247 )248 self.write_timeout = (249 timeout if isinstance(write_timeout, UnsetType) else write_timeout250 )251 self.pool_timeout = (252 timeout if isinstance(pool_timeout, UnsetType) else pool_timeout253 )254255 def __eq__(self, other: typing.Any) -> bool:256 return (257 isinstance(other, self.__class__)258 and self.connect_timeout == other.connect_timeout259 and self.read_timeout == other.read_timeout260 and self.write_timeout == other.write_timeout261 and self.pool_timeout == other.pool_timeout262 )263264 def __repr__(self) -> str:265 class_name = self.__class__.__name__266 if (267 len(268 {269 self.connect_timeout,270 self.read_timeout,271 self.write_timeout,272 self.pool_timeout,273 }274 )275 == 1276 ):277 return f"{class_name}(timeout={self.connect_timeout})"278 return (279 f"{class_name}(connect_timeout={self.connect_timeout}, "280 f"read_timeout={self.read_timeout}, write_timeout={self.write_timeout}, "281 f"pool_timeout={self.pool_timeout})"282 )283284285class PoolLimits:286 """287 Limits on the number of connections in a connection pool.288289 **Parameters:**290291 * **soft_limit** - Allow the connection pool to maintain keep-alive connections292 below this point.293 * **hard_limit** - The maximum number of concurrenct connections that may be294 established.295 """296297 def __init__(298 self, *, soft_limit: int = None, hard_limit: int = None,299 ):300 self.soft_limit = soft_limit301 self.hard_limit = hard_limit302303 def __eq__(self, other: typing.Any) -> bool:304 return (305 isinstance(other, self.__class__)306 and self.soft_limit == other.soft_limit307 and self.hard_limit == other.hard_limit308 )309310 def __repr__(self) -> str:311 class_name = self.__class__.__name__312 return (313 f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"314 )315316317class Proxy:318 def __init__(319 self, url: URLTypes, *, headers: HeaderTypes = None, mode: str = "DEFAULT",320 ):321 url = URL(url)322 headers = Headers(headers)323324 if url.scheme not in ("http", "https"):325 raise ValueError(f"Unknown scheme for proxy URL {url!r}")326 if mode not in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY"):327 raise ValueError(f"Unknown proxy mode {mode!r}")328329 if url.username or url.password:330 headers.setdefault(331 "Proxy-Authorization",332 self.build_auth_header(url.username, url.password),333 )334 # Remove userinfo from the URL authority, e.g.:335 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'336 url = url.copy_with(username=None, password=None)337338 self.url = url339 self.headers = headers340 self.mode = mode341342 def build_auth_header(self, username: str, password: str) -> str:343 userpass = (username.encode("utf-8"), password.encode("utf-8"))344 token = b64encode(b":".join(userpass)).decode().strip()345 return f"Basic {token}"346347 def __repr__(self) -> str:348 return (349 f"Proxy(url={str(self.url)!r}, "350 f"headers={dict(self.headers)!r}, "351 f"mode={self.mode!r})"352 )353354355DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)356DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)357DEFAULT_MAX_REDIRECTS = 20
added:httpx/_content_streams.py+346 added
1import binascii2import mimetypes3import os4import typing5from io import BytesIO6from json import dumps as json_dumps7from pathlib import Path8from urllib.parse import urlencode910from ._exceptions import StreamConsumed11from ._utils import format_form_param1213RequestData = typing.Union[14 dict, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]15]1617RequestFiles = typing.Dict[18 str,19 typing.Union[20 # file (or str)21 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],22 # (filename, file (or str))23 typing.Tuple[24 typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],25 ],26 # (filename, file (or str), content_type)27 typing.Tuple[28 typing.Optional[str],29 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],30 typing.Optional[str],31 ],32 ],33]343536class ContentStream:37 def get_headers(self) -> typing.Dict[str, str]:38 """39 Return a dictionary of headers that are implied by the encoding.40 """41 return {}4243 def can_replay(self) -> bool:44 """45 Return `True` if `__aiter__` can be called multiple times.4647 We need this in cases such determining if we can re-issue a request48 body when we receive a redirect response.49 """50 return True5152 def __iter__(self) -> typing.Iterator[bytes]:53 yield b""5455 def close(self) -> None:56 pass5758 async def __aiter__(self) -> typing.AsyncIterator[bytes]:59 yield b""6061 async def aclose(self) -> None:62 pass636465class ByteStream(ContentStream):66 """67 Request content encoded as plain bytes.68 """6970 def __init__(self, body: typing.Union[str, bytes]) -> None:71 self.body = body.encode("utf-8") if isinstance(body, str) else body7273 def get_headers(self) -> typing.Dict[str, str]:74 if not self.body:75 return {}76 content_length = str(len(self.body))77 return {"Content-Length": content_length}7879 def __iter__(self) -> typing.Iterator[bytes]:80 yield self.body8182 async def __aiter__(self) -> typing.AsyncIterator[bytes]:83 yield self.body848586class IteratorStream(ContentStream):87 """88 Request content encoded as plain bytes, using an byte iterator.89 """9091 def __init__(92 self, iterator: typing.Iterator[bytes], close_func: typing.Callable = None93 ) -> None:94 self.iterator = iterator95 self.close_func = close_func96 self.is_stream_consumed = False9798 def can_replay(self) -> bool:99 return False100101 def get_headers(self) -> typing.Dict[str, str]:102 return {"Transfer-Encoding": "chunked"}103104 def __iter__(self) -> typing.Iterator[bytes]:105 if self.is_stream_consumed:106 raise StreamConsumed()107 self.is_stream_consumed = True108 for part in self.iterator:109 yield part110111 def __aiter__(self) -> typing.AsyncIterator[bytes]:112 raise RuntimeError("Attempted to call a async iterator on an sync stream.")113114 def close(self) -> None:115 if self.close_func is not None:116 self.close_func()117118119class AsyncIteratorStream(ContentStream):120 """121 Request content encoded as plain bytes, using an async byte iterator.122 """123124 def __init__(125 self, aiterator: typing.AsyncIterator[bytes], close_func: typing.Callable = None126 ) -> None:127 self.aiterator = aiterator128 self.close_func = close_func129 self.is_stream_consumed = False130131 def can_replay(self) -> bool:132 return False133134 def get_headers(self) -> typing.Dict[str, str]:135 return {"Transfer-Encoding": "chunked"}136137 def __iter__(self) -> typing.Iterator[bytes]:138 raise RuntimeError("Attempted to call a sync iterator on an async stream.")139140 async def __aiter__(self) -> typing.AsyncIterator[bytes]:141 if self.is_stream_consumed:142 raise StreamConsumed()143 self.is_stream_consumed = True144 async for part in self.aiterator:145 yield part146147 async def aclose(self) -> None:148 if self.close_func is not None:149 await self.close_func()150151152class JSONStream(ContentStream):153 """154 Request content encoded as JSON.155 """156157 def __init__(self, json: typing.Any) -> None:158 self.body = json_dumps(json).encode("utf-8")159160 def get_headers(self) -> typing.Dict[str, str]:161 content_length = str(len(self.body))162 content_type = "application/json"163 return {"Content-Length": content_length, "Content-Type": content_type}164165 def __iter__(self) -> typing.Iterator[bytes]:166 yield self.body167168 async def __aiter__(self) -> typing.AsyncIterator[bytes]:169 yield self.body170171172class URLEncodedStream(ContentStream):173 """174 Request content as URL encoded form data.175 """176177 def __init__(self, data: dict) -> None:178 self.body = urlencode(data, doseq=True).encode("utf-8")179180 def get_headers(self) -> typing.Dict[str, str]:181 content_length = str(len(self.body))182 content_type = "application/x-www-form-urlencoded"183 return {"Content-Length": content_length, "Content-Type": content_type}184185 def __iter__(self) -> typing.Iterator[bytes]:186 yield self.body187188 async def __aiter__(self) -> typing.AsyncIterator[bytes]:189 yield self.body190191192class MultipartStream(ContentStream):193 """194 Request content as multipart encoded form data.195 """196197 class DataField:198 """199 A single form field item, within a multipart form field.200 """201202 def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:203 if not isinstance(name, str):204 raise TypeError("Invalid type for name. Expected str.")205 if not isinstance(value, (str, bytes)):206 raise TypeError("Invalid type for value. Expected str or bytes.")207 self.name = name208 self.value = value209210 def render_headers(self) -> bytes:211 name = format_form_param("name", self.name)212 return b"".join([b"Content-Disposition: form-data; ", name, b"\r\n\r\n"])213214 def render_data(self) -> bytes:215 return (216 self.value217 if isinstance(self.value, bytes)218 else self.value.encode("utf-8")219 )220221 class FileField:222 """223 A single file field item, within a multipart form field.224 """225226 def __init__(227 self, name: str, value: typing.Union[typing.IO[typing.AnyStr], tuple]228 ) -> None:229 self.name = name230 if not isinstance(value, tuple):231 self.filename = Path(str(getattr(value, "name", "upload"))).name232 self.file = (233 value234 ) # type: typing.Union[typing.IO[str], typing.IO[bytes]]235 self.content_type = self.guess_content_type()236 else:237 self.filename = value[0]238 self.file = value[1]239 self.content_type = (240 value[2] if len(value) > 2 else self.guess_content_type()241 )242243 def guess_content_type(self) -> typing.Optional[str]:244 if self.filename:245 return (246 mimetypes.guess_type(self.filename)[0] or "application/octet-stream"247 )248 else:249 return None250251 def render_headers(self) -> bytes:252 parts = [253 b"Content-Disposition: form-data; ",254 format_form_param("name", self.name),255 ]256 if self.filename:257 filename = format_form_param("filename", self.filename)258 parts.extend([b"; ", filename])259 if self.content_type is not None:260 content_type = self.content_type.encode()261 parts.extend([b"\r\nContent-Type: ", content_type])262 parts.append(b"\r\n\r\n")263 return b"".join(parts)264265 def render_data(self) -> bytes:266 if isinstance(self.file, str):267 content = self.file268 else:269 content = self.file.read()270 return content.encode("utf-8") if isinstance(content, str) else content271272 def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:273 body = BytesIO()274 if boundary is None:275 boundary = binascii.hexlify(os.urandom(16))276277 for field in self.iter_fields(data, files):278 body.write(b"--%s\r\n" % boundary)279 body.write(field.render_headers())280 body.write(field.render_data())281 body.write(b"\r\n")282283 body.write(b"--%s--\r\n" % boundary)284285 self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(286 "ascii"287 )288 self.body = body.getvalue()289290 def iter_fields(291 self, data: dict, files: dict292 ) -> typing.Iterator[typing.Union["FileField", "DataField"]]:293 for name, value in data.items():294 if isinstance(value, (list, dict)):295 for item in value:296 yield self.DataField(name=name, value=item)297 else:298 yield self.DataField(name=name, value=value)299300 for name, value in files.items():301 yield self.FileField(name=name, value=value)302303 def get_headers(self) -> typing.Dict[str, str]:304 content_length = str(len(self.body))305 content_type = self.content_type306 return {"Content-Length": content_length, "Content-Type": content_type}307308 def __iter__(self) -> typing.Iterator[bytes]:309 yield self.body310311 async def __aiter__(self) -> typing.AsyncIterator[bytes]:312 yield self.body313314315def encode(316 data: RequestData = None,317 files: RequestFiles = None,318 json: typing.Any = None,319 boundary: bytes = None,320) -> ContentStream:321 """322 Handles encoding the given `data`, `files`, and `json`, returning323 a `ContentStream` implementation.324 """325 if data is None:326 if json is not None:327 return JSONStream(json=json)328 elif files:329 return MultipartStream(data={}, files=files, boundary=boundary)330 else:331 return ByteStream(body=b"")332 elif isinstance(data, dict):333 if files is not None:334 return MultipartStream(data=data, files=files, boundary=boundary)335 else:336 return URLEncodedStream(data=data)337 elif isinstance(data, (str, bytes)):338 return ByteStream(body=data)339 elif hasattr(data, "__aiter__"):340 data = typing.cast(typing.AsyncIterator[bytes], data)341 return AsyncIteratorStream(aiterator=data)342 elif hasattr(data, "__iter__"):343 data = typing.cast(typing.Iterator[bytes], data)344 return IteratorStream(iterator=data)345346 raise TypeError(f"Unexpected type for 'data', {type(data)!r}")
added:httpx/_decoders.py+290 added
1"""2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import codecs7import typing8import zlib910import chardet1112from ._exceptions import DecodingError1314try:15 import brotli16except ImportError: # pragma: nocover17 brotli = None181920class Decoder:21 def decode(self, data: bytes) -> bytes:22 raise NotImplementedError() # pragma: nocover2324 def flush(self) -> bytes:25 raise NotImplementedError() # pragma: nocover262728class IdentityDecoder(Decoder):29 """30 Handle unencoded data.31 """3233 def decode(self, data: bytes) -> bytes:34 return data3536 def flush(self) -> bytes:37 return b""383940class DeflateDecoder(Decoder):41 """42 Handle 'deflate' decoding.4344 See: https://stackoverflow.com/questions/183869945 """4647 def __init__(self) -> None:48 self.first_attempt = True49 self.decompressor = zlib.decompressobj()5051 def decode(self, data: bytes) -> bytes:52 was_first_attempt = self.first_attempt53 self.first_attempt = False54 try:55 return self.decompressor.decompress(data)56 except zlib.error as exc:57 if was_first_attempt:58 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)59 return self.decode(data)60 raise DecodingError from exc6162 def flush(self) -> bytes:63 try:64 return self.decompressor.flush()65 except zlib.error as exc: # pragma: nocover66 raise DecodingError from exc676869class GZipDecoder(Decoder):70 """71 Handle 'gzip' decoding.7273 See: https://stackoverflow.com/questions/183869974 """7576 def __init__(self) -> None:77 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)7879 def decode(self, data: bytes) -> bytes:80 try:81 return self.decompressor.decompress(data)82 except zlib.error as exc:83 raise DecodingError from exc8485 def flush(self) -> bytes:86 try:87 return self.decompressor.flush()88 except zlib.error as exc: # pragma: nocover89 raise DecodingError from exc909192class BrotliDecoder(Decoder):93 """94 Handle 'brotli' decoding.9596 Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/97 or `pip install brotli`. See https://github.com/google/brotli98 Supports both 'brotlipy' and 'Brotli' packages since they share an import99 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'100 """101102 def __init__(self) -> None:103 assert (104 brotli is not None105 ), "The 'brotlipy' or 'brotli' library must be installed to use 'BrotliDecoder'"106 self.decompressor = brotli.Decompressor()107 self.seen_data = False108109 def decode(self, data: bytes) -> bytes:110 if not data:111 return b""112 self.seen_data = True113 try:114 if hasattr(self.decompressor, "decompress"):115 return self.decompressor.decompress(data)116 return self.decompressor.process(data) # pragma: nocover117 except brotli.error as exc:118 raise DecodingError from exc119120 def flush(self) -> bytes:121 if not self.seen_data:122 return b""123 try:124 if hasattr(self.decompressor, "finish"):125 self.decompressor.finish()126 return b""127 except brotli.error as exc: # pragma: nocover128 raise DecodingError from exc129130131class MultiDecoder(Decoder):132 """133 Handle the case where multiple encodings have been applied.134 """135136 def __init__(self, children: typing.Sequence[Decoder]) -> None:137 """138 'children' should be a sequence of decoders in the order in which139 each was applied.140 """141 # Note that we reverse the order for decoding.142 self.children = list(reversed(children))143144 def decode(self, data: bytes) -> bytes:145 for child in self.children:146 data = child.decode(data)147 return data148149 def flush(self) -> bytes:150 data = b""151 for child in self.children:152 data = child.decode(data) + child.flush()153 return data154155156class TextDecoder:157 """158 Handles incrementally decoding bytes into text159 """160161 def __init__(self, encoding: typing.Optional[str] = None):162 self.decoder: typing.Optional[codecs.IncrementalDecoder] = (163 None if encoding is None else codecs.getincrementaldecoder(encoding)()164 )165 self.detector = chardet.universaldetector.UniversalDetector()166167 # This buffer is only needed if 'decoder' is 'None'168 # we want to trigger errors if data is getting added to169 # our internal buffer for some silly reason while170 # a decoder is discovered.171 self.buffer: typing.Optional[bytearray] = None if self.decoder else bytearray()172173 def decode(self, data: bytes) -> str:174 try:175 if self.decoder is not None:176 text = self.decoder.decode(data)177 else:178 assert self.buffer is not None179 text = ""180 self.detector.feed(data)181 self.buffer += data182183 # Should be more than enough data to process, we don't184 # want to buffer too long as chardet will wait until185 # detector.close() is used to give back common186 # encodings like 'utf-8'.187 if len(self.buffer) >= 4096:188 self.decoder = codecs.getincrementaldecoder(189 self._detector_result()190 )()191 text = self.decoder.decode(bytes(self.buffer), False)192 self.buffer = None193194 return text195 except UnicodeDecodeError: # pragma: nocover196 raise DecodingError() from None197198 def flush(self) -> str:199 try:200 if self.decoder is None:201 # Empty string case as chardet is guaranteed to not have a guess.202 assert self.buffer is not None203 if len(self.buffer) == 0:204 return ""205 return bytes(self.buffer).decode(self._detector_result())206207 return self.decoder.decode(b"", True)208 except UnicodeDecodeError: # pragma: nocover209 raise DecodingError() from None210211 def _detector_result(self) -> str:212 self.detector.close()213 result = self.detector.result["encoding"]214 if not result: # pragma: nocover215 raise DecodingError("Unable to determine encoding of content")216217 return result218219220class LineDecoder:221 """222 Handles incrementally reading lines from text.223224 Uses universal line decoding, supporting any of `\n`, `\r`, or `\r\n`225 as line endings, normalizing to `\n`.226 """227228 def __init__(self) -> None:229 self.buffer = ""230231 def decode(self, text: str) -> typing.List[str]:232 lines = []233234 if text.startswith("\n") and self.buffer and self.buffer[-1] == "\r":235 # Handle the case where we have an "\r\n" split across236 # our previous input, and our new chunk.237 lines.append(self.buffer[:-1] + "\n")238 self.buffer = ""239 text = text[1:]240241 while text:242 num_chars = len(text)243 for idx in range(num_chars):244 char = text[idx]245 next_char = None if idx + 1 == num_chars else text[idx + 1]246 if char == "\n":247 lines.append(self.buffer + text[: idx + 1])248 self.buffer = ""249 text = text[idx + 1 :]250 break251 elif char == "\r" and next_char == "\n":252 lines.append(self.buffer + text[:idx] + "\n")253 self.buffer = ""254 text = text[idx + 2 :]255 break256 elif char == "\r" and next_char is not None:257 lines.append(self.buffer + text[:idx] + "\n")258 self.buffer = ""259 text = text[idx + 1 :]260 break261 elif next_char is None:262 self.buffer = text263 text = ""264 break265266 return lines267268 def flush(self) -> typing.List[str]:269 if self.buffer.endswith("\r"):270 # Handle the case where we had a trailing '\r', which could have271 # been a '\r\n' pair.272 lines = [self.buffer[:-1] + "\n"]273 elif self.buffer:274 lines = [self.buffer]275 else:276 lines = []277 self.buffer = ""278 return lines279280281SUPPORTED_DECODERS = {282 "identity": IdentityDecoder,283 "gzip": GZipDecoder,284 "deflate": DeflateDecoder,285 "br": BrotliDecoder,286}287288289if brotli is None:290 SUPPORTED_DECODERS.pop("br") # pragma: nocover
added:httpx/_exceptions.py+174 added
1import typing23if typing.TYPE_CHECKING:4 from ._models import Request, Response # pragma: nocover567class HTTPError(Exception):8 """9 Base class for all httpx exceptions.10 """1112 def __init__(13 self, *args: typing.Any, request: "Request" = None, response: "Response" = None14 ) -> None:15 self.response = response16 self.request = request or getattr(self.response, "request", None)17 super().__init__(*args)181920# Timeout exceptions...212223class TimeoutException(HTTPError):24 """25 A base class for all timeouts.26 """272829class ConnectTimeout(TimeoutException):30 """31 Timeout while establishing a connection.32 """333435class ReadTimeout(TimeoutException):36 """37 Timeout while reading response data.38 """394041class WriteTimeout(TimeoutException):42 """43 Timeout while writing request data.44 """454647class PoolTimeout(TimeoutException):48 """49 Timeout while waiting to acquire a connection from the pool.50 """515253class ProxyError(HTTPError):54 """55 Error from within a proxy56 """575859# HTTP exceptions...606162class ProtocolError(HTTPError):63 """64 Malformed HTTP.65 """666768class DecodingError(HTTPError):69 """70 Decoding of the response failed.71 """727374# Network exceptions...757677class NetworkError(HTTPError):78 """79 A failure occurred while trying to access the network.80 """818283class ConnectionClosed(NetworkError):84 """85 Expected more data from peer, but connection was closed.86 """878889# Redirect exceptions...909192class RedirectError(HTTPError):93 """94 Base class for HTTP redirect errors.95 """969798class TooManyRedirects(RedirectError):99 """100 Too many redirects.101 """102103104class RedirectLoop(RedirectError):105 """106 Infinite redirect loop.107 """108109110class NotRedirectResponse(RedirectError):111 """112 Response was not a redirect response.113 """114115116# Stream exceptions...117118119class StreamError(HTTPError):120 """121 The base class for stream exceptions.122123 The developer made an error in accessing the request stream in124 an invalid way.125 """126127128class RequestBodyUnavailable(StreamError):129 """130 Had to send the request again, but the request body was streaming, and is131 no longer available.132 """133134135class StreamConsumed(StreamError):136 """137 Attempted to read or stream response content, but the content has already138 been streamed.139 """140141142class ResponseNotRead(StreamError):143 """144 Attempted to access response content, without having called `read()`145 after a streaming response.146 """147148149class RequestNotRead(StreamError):150 """151 Attempted to access request content, without having called `read()`.152 """153154155class ResponseClosed(StreamError):156 """157 Attempted to read or stream response content, but the request has been158 closed.159 """160161162# Other cases...163164165class InvalidURL(HTTPError):166 """167 URL was missing a hostname, or was not one of HTTP/HTTPS.168 """169170171class CookieConflict(HTTPError):172 """173 Attempted to lookup a cookie by name, but multiple cookies existed.174 """
added:httpx/_models.py+1207 added
1import cgi2import datetime3import email.message4import json as jsonlib5import typing6import urllib.request7import warnings8from collections.abc import MutableMapping9from http.cookiejar import Cookie, CookieJar10from urllib.parse import parse_qsl, urlencode1112import chardet13import rfc39861415from .__version__ import __version__16from ._content_streams import (17 ByteStream,18 ContentStream,19 RequestData,20 RequestFiles,21 encode,22)23from ._decoders import (24 SUPPORTED_DECODERS,25 Decoder,26 IdentityDecoder,27 LineDecoder,28 MultiDecoder,29 TextDecoder,30)31from ._exceptions import (32 CookieConflict,33 HTTPError,34 InvalidURL,35 NotRedirectResponse,36 RequestNotRead,37 ResponseClosed,38 ResponseNotRead,39 StreamConsumed,40)41from ._status_codes import StatusCode42from ._utils import (43 ElapsedTimer,44 flatten_queryparams,45 guess_json_utf,46 is_known_encoding,47 normalize_header_key,48 normalize_header_value,49 obfuscate_sensitive_headers,50 parse_header_links,51 str_query_param,52)5354if typing.TYPE_CHECKING: # pragma: no cover55 from ._dispatch.base import AsyncDispatcher # noqa: F4015657PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]5859URLTypes = typing.Union["URL", str]6061QueryParamTypes = typing.Union[62 "QueryParams",63 typing.Mapping[str, typing.Union[PrimitiveData, typing.Sequence[PrimitiveData]]],64 typing.List[typing.Tuple[str, PrimitiveData]],65 str,66]6768HeaderTypes = typing.Union[69 "Headers",70 typing.Dict[typing.AnyStr, typing.AnyStr],71 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],72]7374CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]757677class URL:78 def __init__(79 self,80 url: URLTypes,81 allow_relative: bool = False,82 params: QueryParamTypes = None,83 ) -> None:84 if isinstance(url, str):85 self._uri_reference = rfc3986.api.iri_reference(url).encode()86 else:87 self._uri_reference = url._uri_reference8889 # Normalize scheme and domain name.90 if self.is_absolute_url:91 self._uri_reference = self._uri_reference.normalize()9293 # Add any query parameters, merging with any in the URL if needed.94 if params:95 if self._uri_reference.query:96 url_params = QueryParams(self._uri_reference.query)97 url_params.update(params)98 query_string = str(url_params)99 else:100 query_string = str(QueryParams(params))101 self._uri_reference = self._uri_reference.copy_with(query=query_string)102103 # Enforce absolute URLs by default.104 if not allow_relative:105 if not self.scheme:106 raise InvalidURL("No scheme included in URL.")107 if not self.host:108 raise InvalidURL("No host included in URL.")109110 # Allow setting full_path to custom attributes requests111 # like OPTIONS, CONNECT, and forwarding proxy requests.112 self._full_path: typing.Optional[str] = None113114 @property115 def scheme(self) -> str:116 return self._uri_reference.scheme or ""117118 @property119 def authority(self) -> str:120 port_str = self._uri_reference.port121 default_port_str = {"https": "443", "http": "80"}.get(self.scheme, "")122 if port_str is None or port_str == default_port_str:123 return self._uri_reference.host or ""124 return self._uri_reference.authority or ""125126 @property127 def userinfo(self) -> str:128 return self._uri_reference.userinfo or ""129130 @property131 def username(self) -> str:132 userinfo = self._uri_reference.userinfo or ""133 return userinfo.partition(":")[0]134135 @property136 def password(self) -> str:137 userinfo = self._uri_reference.userinfo or ""138 return userinfo.partition(":")[2]139140 @property141 def host(self) -> str:142 return self._uri_reference.host or ""143144 @property145 def port(self) -> int:146 port = self._uri_reference.port147 if port is None:148 return {"https": 443, "http": 80}[self.scheme]149 return int(port)150151 @property152 def path(self) -> str:153 return self._uri_reference.path or "/"154155 @property156 def query(self) -> str:157 return self._uri_reference.query or ""158159 @property160 def full_path(self) -> str:161 if self._full_path is not None:162 return self._full_path163 path = self.path164 if self.query:165 path += "?" + self.query166 return path167168 @full_path.setter169 def full_path(self, value: typing.Optional[str]) -> None:170 self._full_path = value171172 @property173 def fragment(self) -> str:174 return self._uri_reference.fragment or ""175176 @property177 def is_ssl(self) -> bool:178 return self.scheme == "https"179180 @property181 def is_absolute_url(self) -> bool:182 """183 Return `True` for absolute URLs such as 'http://example.com/path',184 and `False` for relative URLs such as '/path'.185 """186 # We don't use `.is_absolute` from `rfc3986` because it treats187 # URLs with a fragment portion as not absolute.188 # What we actually care about is if the URL provides189 # a scheme and hostname to which connections should be made.190 return bool(self.scheme and self.host)191192 @property193 def is_relative_url(self) -> bool:194 return not self.is_absolute_url195196 def copy_with(self, **kwargs: typing.Any) -> "URL":197 if (198 "username" in kwargs199 or "password" in kwargs200 or "host" in kwargs201 or "port" in kwargs202 ):203 host = kwargs.pop("host", self.host)204 port = kwargs.pop("port", None if self.is_relative_url else self.port)205 username = kwargs.pop("username", self.username)206 password = kwargs.pop("password", self.password)207208 authority = host209 if port is not None:210 authority += f":{port}"211 if username:212 userpass = username213 if password:214 userpass += f":{password}"215 authority = f"{userpass}@{authority}"216217 kwargs["authority"] = authority218219 return URL(220 self._uri_reference.copy_with(**kwargs).unsplit(),221 allow_relative=self.is_relative_url,222 )223224 def join(self, relative_url: URLTypes) -> "URL":225 """226 Return an absolute URL, using given this URL as the base.227 """228 if self.is_relative_url:229 return URL(relative_url)230231 # We drop any fragment portion, because RFC 3986 strictly232 # treats URLs with a fragment portion as not being absolute URLs.233 base_uri = self._uri_reference.copy_with(fragment=None)234 relative_url = URL(relative_url, allow_relative=True)235 return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())236237 def __hash__(self) -> int:238 return hash(str(self))239240 def __eq__(self, other: typing.Any) -> bool:241 return isinstance(other, (URL, str)) and str(self) == str(other)242243 def __str__(self) -> str:244 return self._uri_reference.unsplit()245246 def __repr__(self) -> str:247 class_name = self.__class__.__name__248 url_str = str(self)249 if self._uri_reference.userinfo:250 url_str = (251 rfc3986.urlparse(url_str)252 .copy_with(userinfo=f"{self.username}:[secure]")253 .unsplit()254 )255 return f"{class_name}({url_str!r})"256257258class Origin:259 """260 The URL scheme and authority information, as a comparable, hashable object.261 """262263 def __init__(self, url: URLTypes) -> None:264 if not isinstance(url, URL):265 url = URL(url)266 self.scheme = url.scheme267 self.is_ssl = url.is_ssl268 self.host = url.host269 self.port = url.port270271 def __eq__(self, other: typing.Any) -> bool:272 return (273 isinstance(other, self.__class__)274 and self.scheme == other.scheme275 and self.host == other.host276 and self.port == other.port277 )278279 def __hash__(self) -> int:280 return hash((self.scheme, self.host, self.port))281282 def __repr__(self) -> str:283 class_name = self.__class__.__name__284 return (285 f"{class_name}(scheme={self.scheme!r} host={self.host!r} port={self.port})"286 )287288289class QueryParams(typing.Mapping[str, str]):290 """291 URL query parameters, as a multi-dict.292 """293294 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:295 assert len(args) < 2, "Too many arguments."296 assert not (args and kwargs), "Cannot mix named and unnamed arguments."297298 value = args[0] if args else kwargs299300 items: typing.Sequence[typing.Tuple[str, PrimitiveData]]301 if isinstance(value, str):302 items = parse_qsl(value)303 elif isinstance(value, QueryParams):304 items = value.multi_items()305 elif isinstance(value, list):306 items = value307 else:308 items = flatten_queryparams(value)309310 self._list = [(str(k), str_query_param(v)) for k, v in items]311 self._dict = {str(k): str_query_param(v) for k, v in items}312313 def getlist(self, key: typing.Any) -> typing.List[str]:314 return [item_value for item_key, item_value in self._list if item_key == key]315316 def keys(self) -> typing.KeysView:317 return self._dict.keys()318319 def values(self) -> typing.ValuesView:320 return self._dict.values()321322 def items(self) -> typing.ItemsView:323 return self._dict.items()324325 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:326 return list(self._list)327328 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:329 if key in self._dict:330 return self._dict[key]331 return default332333 def update(self, params: QueryParamTypes = None) -> None: # type: ignore334 if not params:335 return336337 params = QueryParams(params)338 for param in params:339 item, *extras = params.getlist(param)340 self[param] = item341 if extras:342 self._list.extend((param, e) for e in extras)343 # ensure getter matches merged QueryParams getter344 self._dict[param] = params[param]345346 def __getitem__(self, key: typing.Any) -> str:347 return self._dict[key]348349 def __setitem__(self, key: str, value: str) -> None:350 self._dict[key] = value351352 found_indexes = []353 for idx, (item_key, _) in enumerate(self._list):354 if item_key == key:355 found_indexes.append(idx)356357 for idx in reversed(found_indexes[1:]):358 del self._list[idx]359360 if found_indexes:361 idx = found_indexes[0]362 self._list[idx] = (key, value)363 else:364 self._list.append((key, value))365366 def __contains__(self, key: typing.Any) -> bool:367 return key in self._dict368369 def __iter__(self) -> typing.Iterator[typing.Any]:370 return iter(self.keys())371372 def __len__(self) -> int:373 return len(self._dict)374375 def __eq__(self, other: typing.Any) -> bool:376 if not isinstance(other, self.__class__):377 return False378 return sorted(self._list) == sorted(other._list)379380 def __str__(self) -> str:381 return urlencode(self._list)382383 def __repr__(self) -> str:384 class_name = self.__class__.__name__385 query_string = str(self)386 return f"{class_name}({query_string!r})"387388389class Headers(typing.MutableMapping[str, str]):390 """391 HTTP headers, as a case-insensitive multi-dict.392 """393394 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:395 if headers is None:396 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]397 elif isinstance(headers, Headers):398 self._list = list(headers.raw)399 elif isinstance(headers, dict):400 self._list = [401 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))402 for k, v in headers.items()403 ]404 else:405 self._list = [406 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))407 for k, v in headers408 ]409 self._encoding = encoding410411 @property412 def encoding(self) -> str:413 """414 Header encoding is mandated as ascii, but we allow fallbacks to utf-8415 or iso-8859-1.416 """417 if self._encoding is None:418 for encoding in ["ascii", "utf-8"]:419 for key, value in self.raw:420 try:421 key.decode(encoding)422 value.decode(encoding)423 except UnicodeDecodeError:424 break425 else:426 # The else block runs if 'break' did not occur, meaning427 # all values fitted the encoding.428 self._encoding = encoding429 break430 else:431 # The ISO-8859-1 encoding covers all 256 code points in a byte,432 # so will never raise decode errors.433 self._encoding = "iso-8859-1"434 return self._encoding435436 @encoding.setter437 def encoding(self, value: str) -> None:438 self._encoding = value439440 @property441 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:442 """443 Returns a list of the raw header items, as byte pairs.444 May be mutated in-place.445 """446 return self._list447448 def keys(self) -> typing.List[str]: # type: ignore449 return [key.decode(self.encoding) for key, value in self._list]450451 def values(self) -> typing.List[str]: # type: ignore452 return [value.decode(self.encoding) for key, value in self._list]453454 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore455 return [456 (key.decode(self.encoding), value.decode(self.encoding))457 for key, value in self._list458 ]459460 def get(self, key: str, default: typing.Any = None) -> typing.Any:461 try:462 return self[key]463 except KeyError:464 return default465466 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:467 """468 Return multiple header values.469 """470 get_header_key = key.lower().encode(self.encoding)471472 values = [473 item_value.decode(self.encoding)474 for item_key, item_value in self._list475 if item_key == get_header_key476 ]477478 if not split_commas:479 return values480481 split_values = []482 for value in values:483 split_values.extend([item.strip() for item in value.split(",")])484 return split_values485486 def update(self, headers: HeaderTypes = None) -> None: # type: ignore487 headers = Headers(headers)488 for header in headers:489 self[header] = headers[header]490491 def copy(self) -> "Headers":492 return Headers(self.items(), encoding=self.encoding)493494 def __getitem__(self, key: str) -> str:495 """496 Return a single header value.497498 If there are multiple headers with the same key, then we concatenate499 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2500 """501 normalized_key = key.lower().encode(self.encoding)502503 items = []504 for header_key, header_value in self._list:505 if header_key == normalized_key:506 items.append(header_value.decode(self.encoding))507508 if items:509 return ", ".join(items)510511 raise KeyError(key)512513 def __setitem__(self, key: str, value: str) -> None:514 """515 Set the header `key` to `value`, removing any duplicate entries.516 Retains insertion order.517 """518 set_key = key.lower().encode(self.encoding)519 set_value = value.encode(self.encoding)520521 found_indexes = []522 for idx, (item_key, _) in enumerate(self._list):523 if item_key == set_key:524 found_indexes.append(idx)525526 for idx in reversed(found_indexes[1:]):527 del self._list[idx]528529 if found_indexes:530 idx = found_indexes[0]531 self._list[idx] = (set_key, set_value)532 else:533 self._list.append((set_key, set_value))534535 def __delitem__(self, key: str) -> None:536 """537 Remove the header `key`.538 """539 del_key = key.lower().encode(self.encoding)540541 pop_indexes = []542 for idx, (item_key, _) in enumerate(self._list):543 if item_key == del_key:544 pop_indexes.append(idx)545 if not pop_indexes:546 raise KeyError(key)547548 for idx in reversed(pop_indexes):549 del self._list[idx]550551 def __contains__(self, key: typing.Any) -> bool:552 get_header_key = key.lower().encode(self.encoding)553 for header_key, _ in self._list:554 if header_key == get_header_key:555 return True556 return False557558 def __iter__(self) -> typing.Iterator[typing.Any]:559 return iter(self.keys())560561 def __len__(self) -> int:562 return len(self._list)563564 def __eq__(self, other: typing.Any) -> bool:565 if not isinstance(other, Headers):566 return False567 return sorted(self._list) == sorted(other._list)568569 def __repr__(self) -> str:570 class_name = self.__class__.__name__571572 encoding_str = ""573 if self.encoding != "ascii":574 encoding_str = f", encoding={self.encoding!r}"575576 as_list = list(obfuscate_sensitive_headers(self.items()))577 as_dict = dict(as_list)578579 no_duplicate_keys = len(as_dict) == len(as_list)580 if no_duplicate_keys:581 return f"{class_name}({as_dict!r}{encoding_str})"582 return f"{class_name}({as_list!r}{encoding_str})"583584585USER_AGENT = f"python-httpx/{__version__}"586ACCEPT_ENCODING = ", ".join(587 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]588)589590591class Request:592 def __init__(593 self,594 method: str,595 url: typing.Union[str, URL],596 *,597 params: QueryParamTypes = None,598 headers: HeaderTypes = None,599 cookies: CookieTypes = None,600 data: RequestData = None,601 files: RequestFiles = None,602 json: typing.Any = None,603 stream: ContentStream = None,604 ):605 self.method = method.upper()606 self.url = URL(url, params=params)607 self.headers = Headers(headers)608 if cookies:609 Cookies(cookies).set_cookie_header(self)610611 if stream is not None:612 self.stream = stream613 else:614 self.stream = encode(data, files, json)615616 self.timer = ElapsedTimer()617 self.prepare()618619 def prepare(self) -> None:620 for key, value in self.stream.get_headers().items():621 self.headers.setdefault(key, value)622623 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []624625 has_host = "host" in self.headers626 has_user_agent = "user-agent" in self.headers627 has_accept = "accept" in self.headers628 has_accept_encoding = "accept-encoding" in self.headers629 has_connection = "connection" in self.headers630631 if not has_host:632 url = self.url633 if url.userinfo:634 url = url.copy_with(username=None, password=None)635 auto_headers.append((b"host", url.authority.encode("ascii")))636 if not has_user_agent:637 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))638 if not has_accept:639 auto_headers.append((b"accept", b"*/*"))640 if not has_accept_encoding:641 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))642 if not has_connection:643 auto_headers.append((b"connection", b"keep-alive"))644645 for item in reversed(auto_headers):646 self.headers.raw.insert(0, item)647648 @property649 def content(self) -> bytes:650 if not hasattr(self, "_content"):651 raise RequestNotRead()652 return self._content653654 def read(self) -> bytes:655 """656 Read and return the request content.657 """658 if not hasattr(self, "_content"):659 self._content = b"".join([part for part in self.stream])660 # If a streaming request has been read entirely into memory, then661 # we can replace the stream with a raw bytes implementation,662 # to ensure that any non-replayable streams can still be used.663 self.stream = ByteStream(self._content)664 return self._content665666 async def aread(self) -> bytes:667 """668 Read and return the request content.669 """670 if not hasattr(self, "_content"):671 self._content = b"".join([part async for part in self.stream])672 # If a streaming request has been read entirely into memory, then673 # we can replace the stream with a raw bytes implementation,674 # to ensure that any non-replayable streams can still be used.675 self.stream = ByteStream(self._content)676 return self._content677678 def __repr__(self) -> str:679 class_name = self.__class__.__name__680 url = str(self.url)681 return f"<{class_name}({self.method!r}, {url!r})>"682683684class Response:685 def __init__(686 self,687 status_code: int,688 *,689 request: Request,690 http_version: str = None,691 headers: HeaderTypes = None,692 stream: ContentStream = None,693 content: bytes = None,694 history: typing.List["Response"] = None,695 ):696 self.status_code = status_code697 self.http_version = http_version698 self.headers = Headers(headers)699700 self.request = request701 self.call_next: typing.Optional[typing.Callable] = None702703 self.history = [] if history is None else list(history)704705 self.is_closed = False706 self.is_stream_consumed = False707 if stream is not None:708 self._raw_stream = stream709 else:710 self._raw_stream = ByteStream(body=content or b"")711 self.read()712713 @property714 def elapsed(self) -> datetime.timedelta:715 """716 Returns the time taken for the complete request/response717 cycle to complete.718 """719 if not hasattr(self, "_elapsed"):720 raise RuntimeError(721 "'.elapsed' may only be accessed after the response "722 "has been read or closed."723 )724 return self._elapsed725726 @property727 def reason_phrase(self) -> str:728 return StatusCode.get_reason_phrase(self.status_code)729730 @property731 def url(self) -> typing.Optional[URL]:732 """733 Returns the URL for which the request was made.734 """735 return self.request.url736737 @property738 def content(self) -> bytes:739 if not hasattr(self, "_content"):740 raise ResponseNotRead()741 return self._content742743 @property744 def text(self) -> str:745 if not hasattr(self, "_text"):746 content = self.content747 if not content:748 self._text = ""749 else:750 encoding = self.encoding751 self._text = content.decode(encoding, errors="replace")752 return self._text753754 @property755 def encoding(self) -> str:756 if not hasattr(self, "_encoding"):757 encoding = self.charset_encoding758 if encoding is None or not is_known_encoding(encoding):759 encoding = self.apparent_encoding760 if encoding is None or not is_known_encoding(encoding):761 encoding = "utf-8"762 self._encoding = encoding763 return self._encoding764765 @encoding.setter766 def encoding(self, value: str) -> None:767 self._encoding = value768769 @property770 def charset_encoding(self) -> typing.Optional[str]:771 """772 Return the encoding, as specified by the Content-Type header.773 """774 content_type = self.headers.get("Content-Type")775 if content_type is None:776 return None777778 parsed = cgi.parse_header(content_type)779 media_type, params = parsed[0], parsed[-1]780 if "charset" in params:781 return params["charset"].strip("'\"")782783 # RFC 2616 specifies that 'iso-8859-1' should be used as the default784 # for 'text/*' media types, if no charset is provided.785 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1786 if media_type.startswith("text/"):787 return "iso-8859-1"788789 return None790791 @property792 def apparent_encoding(self) -> typing.Optional[str]:793 """794 Return the encoding, as it appears to autodetection.795 """796 return chardet.detect(self.content)["encoding"]797798 @property799 def decoder(self) -> Decoder:800 """801 Returns a decoder instance which can be used to decode the raw byte802 content, depending on the Content-Encoding used in the response.803 """804 if not hasattr(self, "_decoder"):805 decoders: typing.List[Decoder] = []806 values = self.headers.getlist("content-encoding", split_commas=True)807 for value in values:808 value = value.strip().lower()809 try:810 decoder_cls = SUPPORTED_DECODERS[value]811 decoders.append(decoder_cls())812 except KeyError:813 continue814815 if len(decoders) == 1:816 self._decoder = decoders[0]817 elif len(decoders) > 1:818 self._decoder = MultiDecoder(decoders)819 else:820 self._decoder = IdentityDecoder()821822 return self._decoder823824 @property825 def is_error(self) -> bool:826 return StatusCode.is_error(self.status_code)827828 @property829 def is_redirect(self) -> bool:830 return StatusCode.is_redirect(self.status_code) and "location" in self.headers831832 def raise_for_status(self) -> None:833 """834 Raise the `HttpError` if one occurred.835 """836 message = (837 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"838 "For more information check: https://httpstatuses.com/{0.status_code}"839 )840841 if StatusCode.is_client_error(self.status_code):842 message = message.format(self, error_type="Client Error")843 raise HTTPError(message, response=self)844 elif StatusCode.is_server_error(self.status_code):845 message = message.format(self, error_type="Server Error")846 raise HTTPError(message, response=self)847848 def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:849 if self.charset_encoding is None and self.content and len(self.content) > 3:850 encoding = guess_json_utf(self.content)851 if encoding is not None:852 try:853 return jsonlib.loads(self.content.decode(encoding), **kwargs)854 except UnicodeDecodeError:855 pass856 return jsonlib.loads(self.text, **kwargs)857858 @property859 def cookies(self) -> "Cookies":860 if not hasattr(self, "_cookies"):861 self._cookies = Cookies()862 self._cookies.extract_cookies(self)863 return self._cookies864865 @property866 def links(self) -> typing.Dict[typing.Optional[str], typing.Dict[str, str]]:867 """868 Returns the parsed header links of the response, if any869 """870 header = self.headers.get("link")871 ldict = {}872 if header:873 links = parse_header_links(header)874 for link in links:875 key = link.get("rel") or link.get("url")876 ldict[key] = link877 return ldict878879 def __repr__(self) -> str:880 return f"<Response [{self.status_code} {self.reason_phrase}]>"881882 @property883 def stream(self): # type: ignore884 warnings.warn( # pragma: nocover885 "Response.stream() is due to be deprecated. "886 "Use Response.aiter_bytes() instead."887 )888 return self.aiter_bytes # pragma: nocover889890 @property891 def raw(self): # type: ignore892 warnings.warn( # pragma: nocover893 "Response.raw() is due to be deprecated. "894 "Use Response.aiter_raw() instead."895 )896 return self.aiter_raw # pragma: nocover897898 def read(self) -> bytes:899 """900 Read and return the response content.901 """902 if not hasattr(self, "_content"):903 self._content = b"".join([part for part in self.iter_bytes()])904 return self._content905906 def iter_bytes(self) -> typing.Iterator[bytes]:907 """908 A byte-iterator over the decoded response content.909 This allows us to handle gzip, deflate, and brotli encoded responses.910 """911 if hasattr(self, "_content"):912 yield self._content913 else:914 for chunk in self.iter_raw():915 yield self.decoder.decode(chunk)916 yield self.decoder.flush()917918 def iter_text(self) -> typing.Iterator[str]:919 """920 A str-iterator over the decoded response content921 that handles both gzip, deflate, etc but also detects the content's922 string encoding.923 """924 decoder = TextDecoder(encoding=self.charset_encoding)925 for chunk in self.iter_bytes():926 yield decoder.decode(chunk)927 yield decoder.flush()928929 def iter_lines(self) -> typing.Iterator[str]:930 decoder = LineDecoder()931 for text in self.iter_text():932 for line in decoder.decode(text):933 yield line934 for line in decoder.flush():935 yield line936937 def iter_raw(self) -> typing.Iterator[bytes]:938 """939 A byte-iterator over the raw response content.940 """941 if self.is_stream_consumed:942 raise StreamConsumed()943 if self.is_closed:944 raise ResponseClosed()945946 self.is_stream_consumed = True947 for part in self._raw_stream:948 yield part949 self.close()950951 def close(self) -> None:952 """953 Close the response and release the connection.954 Automatically called if the response body is read to completion.955 """956 if not self.is_closed:957 self.is_closed = True958 self._elapsed = self.request.timer.elapsed959 if hasattr(self, "_raw_stream"):960 self._raw_stream.close()961962 async def aread(self) -> bytes:963 """964 Read and return the response content.965 """966 if not hasattr(self, "_content"):967 self._content = b"".join([part async for part in self.aiter_bytes()])968 return self._content969970 async def aiter_bytes(self) -> typing.AsyncIterator[bytes]:971 """972 A byte-iterator over the decoded response content.973 This allows us to handle gzip, deflate, and brotli encoded responses.974 """975 if hasattr(self, "_content"):976 yield self._content977 else:978 async for chunk in self.aiter_raw():979 yield self.decoder.decode(chunk)980 yield self.decoder.flush()981982 async def aiter_text(self) -> typing.AsyncIterator[str]:983 """984 A str-iterator over the decoded response content985 that handles both gzip, deflate, etc but also detects the content's986 string encoding.987 """988 decoder = TextDecoder(encoding=self.charset_encoding)989 async for chunk in self.aiter_bytes():990 yield decoder.decode(chunk)991 yield decoder.flush()992993 async def aiter_lines(self) -> typing.AsyncIterator[str]:994 decoder = LineDecoder()995 async for text in self.aiter_text():996 for line in decoder.decode(text):997 yield line998 for line in decoder.flush():999 yield line10001001 async def aiter_raw(self) -> typing.AsyncIterator[bytes]:1002 """1003 A byte-iterator over the raw response content.1004 """1005 if self.is_stream_consumed:1006 raise StreamConsumed()1007 if self.is_closed:1008 raise ResponseClosed()10091010 self.is_stream_consumed = True1011 async for part in self._raw_stream:1012 yield part1013 await self.aclose()10141015 async def anext(self) -> "Response":1016 """1017 Get the next response from a redirect response.1018 """1019 if not self.is_redirect:1020 raise NotRedirectResponse()1021 assert self.call_next is not None1022 return await self.call_next()10231024 async def aclose(self) -> None:1025 """1026 Close the response and release the connection.1027 Automatically called if the response body is read to completion.1028 """1029 if not self.is_closed:1030 self.is_closed = True1031 self._elapsed = self.request.timer.elapsed1032 if hasattr(self, "_raw_stream"):1033 await self._raw_stream.aclose()103410351036class Cookies(MutableMapping):1037 """1038 HTTP Cookies, as a mutable mapping.1039 """10401041 def __init__(self, cookies: CookieTypes = None) -> None:1042 if cookies is None or isinstance(cookies, dict):1043 self.jar = CookieJar()1044 if isinstance(cookies, dict):1045 for key, value in cookies.items():1046 self.set(key, value)1047 elif isinstance(cookies, Cookies):1048 self.jar = CookieJar()1049 for cookie in cookies.jar:1050 self.jar.set_cookie(cookie)1051 else:1052 self.jar = cookies10531054 def extract_cookies(self, response: Response) -> None:1055 """1056 Loads any cookies based on the response `Set-Cookie` headers.1057 """1058 urlib_response = self._CookieCompatResponse(response)1059 urllib_request = self._CookieCompatRequest(response.request)10601061 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore10621063 def set_cookie_header(self, request: Request) -> None:1064 """1065 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1066 """1067 urllib_request = self._CookieCompatRequest(request)1068 self.jar.add_cookie_header(urllib_request)10691070 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1071 """1072 Set a cookie value by name. May optionally include domain and path.1073 """1074 kwargs = {1075 "version": 0,1076 "name": name,1077 "value": value,1078 "port": None,1079 "port_specified": False,1080 "domain": domain,1081 "domain_specified": bool(domain),1082 "domain_initial_dot": domain.startswith("."),1083 "path": path,1084 "path_specified": bool(path),1085 "secure": False,1086 "expires": None,1087 "discard": True,1088 "comment": None,1089 "comment_url": None,1090 "rest": {"HttpOnly": None},1091 "rfc2109": False,1092 }1093 cookie = Cookie(**kwargs) # type: ignore1094 self.jar.set_cookie(cookie)10951096 def get( # type: ignore1097 self, name: str, default: str = None, domain: str = None, path: str = None1098 ) -> typing.Optional[str]:1099 """1100 Get a cookie by name. May optionally include domain and path1101 in order to specify exactly which cookie to retrieve.1102 """1103 value = None1104 for cookie in self.jar:1105 if cookie.name == name:1106 if domain is None or cookie.domain == domain: # type: ignore1107 if path is None or cookie.path == path:1108 if value is not None:1109 message = f"Multiple cookies exist with name={name}"1110 raise CookieConflict(message)1111 value = cookie.value11121113 if value is None:1114 return default1115 return value11161117 def delete(self, name: str, domain: str = None, path: str = None) -> None:1118 """1119 Delete a cookie by name. May optionally include domain and path1120 in order to specify exactly which cookie to delete.1121 """1122 if domain is not None and path is not None:1123 return self.jar.clear(domain, path, name)11241125 remove = []1126 for cookie in self.jar:1127 if cookie.name == name:1128 if domain is None or cookie.domain == domain: # type: ignore1129 if path is None or cookie.path == path:1130 remove.append(cookie)11311132 for cookie in remove:1133 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore11341135 def clear(self, domain: str = None, path: str = None) -> None:1136 """1137 Delete all cookies. Optionally include a domain and path in1138 order to only delete a subset of all the cookies.1139 """1140 args = []1141 if domain is not None:1142 args.append(domain)1143 if path is not None:1144 assert domain is not None1145 args.append(path)1146 self.jar.clear(*args)11471148 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1149 cookies = Cookies(cookies)1150 for cookie in cookies.jar:1151 self.jar.set_cookie(cookie)11521153 def __setitem__(self, name: str, value: str) -> None:1154 return self.set(name, value)11551156 def __getitem__(self, name: str) -> str:1157 value = self.get(name)1158 if value is None:1159 raise KeyError(name)1160 return value11611162 def __delitem__(self, name: str) -> None:1163 return self.delete(name)11641165 def __len__(self) -> int:1166 return len(self.jar)11671168 def __iter__(self) -> typing.Iterator[str]:1169 return (cookie.name for cookie in self.jar)11701171 def __bool__(self) -> bool:1172 for _ in self.jar:1173 return True1174 return False11751176 class _CookieCompatRequest(urllib.request.Request):1177 """1178 Wraps a `Request` instance up in a compatibility interface suitable1179 for use with `CookieJar` operations.1180 """11811182 def __init__(self, request: Request) -> None:1183 super().__init__(1184 url=str(request.url),1185 headers=dict(request.headers),1186 method=request.method,1187 )1188 self.request = request11891190 def add_unredirected_header(self, key: str, value: str) -> None:1191 super().add_unredirected_header(key, value)1192 self.request.headers[key] = value11931194 class _CookieCompatResponse:1195 """1196 Wraps a `Request` instance up in a compatibility interface suitable1197 for use with `CookieJar` operations.1198 """11991200 def __init__(self, response: Response):1201 self.response = response12021203 def info(self) -> email.message.Message:1204 info = email.message.Message()1205 for key, value in self.response.headers.items():1206 info[key] = value1207 return info
added:httpx/_status_codes.py+139 added
1from enum import IntEnum234class StatusCode(IntEnum):5 """HTTP status codes and reason phrases6 Status codes from the following RFCs are all observed:7 * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 26168 * RFC 6585: Additional HTTP Status Codes9 * RFC 3229: Delta encoding in HTTP10 * RFC 4918: HTTP Extensions for WebDAV, obsoletes 251811 * RFC 5842: Binding Extensions to WebDAV12 * RFC 7238: Permanent Redirect13 * RFC 2295: Transparent Content Negotiation in HTTP14 * RFC 2774: An HTTP Extension Framework15 * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)16 * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)17 * RFC 7725: An HTTP Status Code to Report Legal Obstacles18 """1920 def __new__(cls, value: int, phrase: str = "") -> "StatusCode":21 obj = int.__new__(cls, value) # type: ignore22 obj._value_ = value2324 obj.phrase = phrase25 return obj2627 def __str__(self) -> str:28 return str(self.value)2930 @classmethod31 def get_reason_phrase(cls, value: int) -> str:32 try:33 return StatusCode(value).phrase # type: ignore34 except ValueError:35 return ""3637 @classmethod38 def is_redirect(cls, value: int) -> bool:39 return value in (40 # 301 (Cacheable redirect. Method may change to GET.)41 StatusCode.MOVED_PERMANENTLY,42 # 302 (Uncacheable redirect. Method may change to GET.)43 StatusCode.FOUND,44 # 303 (Client should make a GET or HEAD request.)45 StatusCode.SEE_OTHER,46 # 307 (Equiv. 302, but retain method)47 StatusCode.TEMPORARY_REDIRECT,48 # 308 (Equiv. 301, but retain method)49 StatusCode.PERMANENT_REDIRECT,50 )5152 @classmethod53 def is_error(cls, value: int) -> bool:54 return 400 <= value <= 5995556 @classmethod57 def is_client_error(cls, value: int) -> bool:58 return 400 <= value <= 4995960 @classmethod61 def is_server_error(cls, value: int) -> bool:62 return 500 <= value <= 5996364 # informational65 CONTINUE = 100, "Continue"66 SWITCHING_PROTOCOLS = 101, "Switching Protocols"67 PROCESSING = 102, "Processing"6869 # success70 OK = 200, "OK"71 CREATED = 201, "Created"72 ACCEPTED = 202, "Accepted"73 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"74 NO_CONTENT = 204, "No Content"75 RESET_CONTENT = 205, "Reset Content"76 PARTIAL_CONTENT = 206, "Partial Content"77 MULTI_STATUS = 207, "Multi-Status"78 ALREADY_REPORTED = 208, "Already Reported"79 IM_USED = 226, "IM Used"8081 # redirection82 MULTIPLE_CHOICES = 300, "Multiple Choices"83 MOVED_PERMANENTLY = 301, "Moved Permanently"84 FOUND = 302, "Found"85 SEE_OTHER = 303, "See Other"86 NOT_MODIFIED = 304, "Not Modified"87 USE_PROXY = 305, "Use Proxy"88 TEMPORARY_REDIRECT = 307, "Temporary Redirect"89 PERMANENT_REDIRECT = 308, "Permanent Redirect"9091 # client error92 BAD_REQUEST = 400, "Bad Request"93 UNAUTHORIZED = 401, "Unauthorized"94 PAYMENT_REQUIRED = 402, "Payment Required"95 FORBIDDEN = 403, "Forbidden"96 NOT_FOUND = 404, "Not Found"97 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"98 NOT_ACCEPTABLE = 406, "Not Acceptable"99 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"100 REQUEST_TIMEOUT = 408, "Request Timeout"101 CONFLICT = 409, "Conflict"102 GONE = 410, "Gone"103 LENGTH_REQUIRED = 411, "Length Required"104 PRECONDITION_FAILED = 412, "Precondition Failed"105 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"106 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"107 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"108 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"109 EXPECTATION_FAILED = 417, "Expectation Failed"110 IM_A_TEAPOT = 418, "I'm a teapot"111 MISDIRECTED_REQUEST = 421, "Misdirected Request"112 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"113 LOCKED = 423, "Locked"114 FAILED_DEPENDENCY = 424, "Failed Dependency"115 UPGRADE_REQUIRED = 426, "Upgrade Required"116 PRECONDITION_REQUIRED = 428, "Precondition Required"117 TOO_MANY_REQUESTS = 429, "Too Many Requests"118 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"119 UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons"120121 # server errors122 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"123 NOT_IMPLEMENTED = 501, "Not Implemented"124 BAD_GATEWAY = 502, "Bad Gateway"125 SERVICE_UNAVAILABLE = 503, "Service Unavailable"126 GATEWAY_TIMEOUT = 504, "Gateway Timeout"127 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"128 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"129 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"130 LOOP_DETECTED = 508, "Loop Detected"131 NOT_EXTENDED = 510, "Not Extended"132 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"133134135codes = StatusCode136137#  Include lower-case styles for `requests` compatibility.138for code in codes:139 setattr(codes, code._name_.lower(), int(code))
added:httpx/_utils.py+369 added
1import codecs2import collections3import contextlib4import logging5import netrc6import os7import re8import sys9import typing10from datetime import timedelta11from pathlib import Path12from time import perf_counter13from types import TracebackType14from urllib.request import getproxies1516from ._exceptions import NetworkError1718if typing.TYPE_CHECKING: # pragma: no cover19 from ._models import PrimitiveData20 from ._models import URL212223_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}24_HTML5_FORM_ENCODING_REPLACEMENTS.update(25 {chr(c): "%{:02X}".format(c) for c in range(0x00, 0x1F + 1) if c != 0x1B}26)27_HTML5_FORM_ENCODING_RE = re.compile(28 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])29)303132def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:33 """34 Coerce str/bytes into a strictly byte-wise HTTP header key.35 """36 if isinstance(value, bytes):37 return value.lower()38 return value.encode(encoding or "ascii").lower()394041def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:42 """43 Coerce str/bytes into a strictly byte-wise HTTP header value.44 """45 if isinstance(value, bytes):46 return value47 return value.encode(encoding or "ascii")484950def str_query_param(value: "PrimitiveData") -> str:51 """52 Coerce a primitive data type into a string value for query params.5354 Note that we prefer JSON-style 'true'/'false' for boolean values here.55 """56 if value is True:57 return "true"58 elif value is False:59 return "false"60 elif value is None:61 return ""62 return str(value)636465def is_known_encoding(encoding: str) -> bool:66 """67 Return `True` if `encoding` is a known codec.68 """69 try:70 codecs.lookup(encoding)71 except LookupError:72 return False73 return True747576def format_form_param(name: str, value: typing.Union[str, bytes]) -> bytes:77 """78 Encode a name/value pair within a multipart form.79 """80 if isinstance(value, bytes):81 value = value.decode()8283 def replacer(match: typing.Match[str]) -> str:84 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]8586 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)87 return f'{name}="{value}"'.encode()888990# Null bytes; no need to recreate these on each call to guess_json_utf91_null = "\x00".encode("ascii") # encoding to ASCII for Python 392_null2 = _null * 293_null3 = _null * 3949596def guess_json_utf(data: bytes) -> typing.Optional[str]:97 # JSON always starts with two ASCII characters, so detection is as98 # easy as counting the nulls and from their location and count99 # determine the encoding. Also detect a BOM, if present.100 sample = data[:4]101 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):102 return "utf-32" # BOM included103 if sample[:3] == codecs.BOM_UTF8:104 return "utf-8-sig" # BOM included, MS style (discouraged)105 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):106 return "utf-16" # BOM included107 nullcount = sample.count(_null)108 if nullcount == 0:109 return "utf-8"110 if nullcount == 2:111 if sample[::2] == _null2: # 1st and 3rd are null112 return "utf-16-be"113 if sample[1::2] == _null2: # 2nd and 4th are null114 return "utf-16-le"115 # Did not detect 2 valid UTF-16 ascii-range characters116 if nullcount == 3:117 if sample[:3] == _null3:118 return "utf-32-be"119 if sample[1:] == _null3:120 return "utf-32-le"121 # Did not detect a valid UTF-32 ascii-range character122 return None123124125class NetRCInfo:126 def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:127 if files is None:128 files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]129 self.netrc_files = files130131 @property132 def netrc_info(self) -> typing.Optional[netrc.netrc]:133 if not hasattr(self, "_netrc_info"):134 self._netrc_info = None135 for file_path in self.netrc_files:136 expanded_path = Path(file_path).expanduser()137 if expanded_path.is_file():138 self._netrc_info = netrc.netrc(str(expanded_path))139 break140 return self._netrc_info141142 def get_credentials(143 self, authority: str144 ) -> typing.Optional[typing.Tuple[str, str]]:145 if self.netrc_info is None:146 return None147148 auth_info = self.netrc_info.authenticators(authority)149 if auth_info is None or auth_info[2] is None:150 return None151 return (auth_info[0], auth_info[2])152153154def get_ca_bundle_from_env() -> typing.Optional[str]:155 if "SSL_CERT_FILE" in os.environ:156 ssl_file = Path(os.environ["SSL_CERT_FILE"])157 if ssl_file.is_file():158 return str(ssl_file)159 if "SSL_CERT_DIR" in os.environ:160 ssl_path = Path(os.environ["SSL_CERT_DIR"])161 if ssl_path.is_dir():162 return str(ssl_path)163 return None164165166def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:167 """168 Returns a list of parsed link headers, for more info see:169 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link170 The generic syntax of those is:171 Link: < uri-reference >; param1=value1; param2="value2"172 So for instance:173 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'174 would return175 [176 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},177 {"url": "http://.../back.jpeg"},178 ]179 :param value: HTTP Link entity-header field180 :return: list of parsed link headers181 """182 links: typing.List[typing.Dict[str, str]] = []183 replace_chars = " '\""184 value = value.strip(replace_chars)185 if not value:186 return links187 for val in re.split(", *<", value):188 try:189 url, params = val.split(";", 1)190 except ValueError:191 url, params = val, ""192 link = {"url": url.strip("<> '\"")}193 for param in params.split(";"):194 try:195 key, value = param.split("=")196 except ValueError:197 break198 link[key.strip(replace_chars)] = value.strip(replace_chars)199 links.append(link)200 return links201202203SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}204205206def obfuscate_sensitive_headers(207 items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]208) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:209 for k, v in items:210 if to_str(k.lower()) in SENSITIVE_HEADERS:211 v = to_bytes_or_str("[secure]", match_type_of=v)212 yield k, v213214215_LOGGER_INITIALIZED = False216TRACE_LOG_LEVEL = 5217218219class Logger(logging.Logger):220 # Stub for type checkers.221 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:222 ... # pragma: nocover223224225def get_logger(name: str) -> Logger:226 """227 Get a `logging.Logger` instance, and optionally228 set up debug logging based on the HTTPX_LOG_LEVEL environment variable.229 """230 global _LOGGER_INITIALIZED231232 if not _LOGGER_INITIALIZED:233 _LOGGER_INITIALIZED = True234 logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")235236 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()237 if log_level in ("DEBUG", "TRACE"):238 logger = logging.getLogger("httpx")239 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)240 handler = logging.StreamHandler(sys.stderr)241 handler.setFormatter(242 logging.Formatter(243 fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",244 datefmt="%Y-%m-%d %H:%M:%S",245 )246 )247 logger.addHandler(handler)248249 logger = logging.getLogger(name)250251 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:252 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)253254 logger.trace = trace # type: ignore255256 return typing.cast(Logger, logger)257258259def should_not_be_proxied(url: "URL") -> bool:260 """ Return True if url should not be proxied,261 return False otherwise.262 """263 no_proxy = getproxies().get("no")264 if not no_proxy:265 return False266 no_proxy_list = [host.strip() for host in no_proxy.split(",")]267 for name in no_proxy_list:268 if name == "*":269 return True270 if name:271 name = name.lstrip(".") # ignore leading dots272 name = re.escape(name)273 pattern = r"(.+\.)?%s$" % name274 if re.match(pattern, url.host, re.I) or re.match(275 pattern, url.authority, re.I276 ):277 return True278 return False279280281def get_environment_proxies() -> typing.Dict[str, str]:282 """Gets proxy information from the environment"""283284 # urllib.request.getproxies() falls back on System285 # Registry and Config for proxies on Windows and macOS.286 # We don't want to propagate non-HTTP proxies into287 # our configuration such as 'TRAVIS_APT_PROXY'.288 supported_proxy_schemes = ("http", "https", "all")289 return {290 key: val291 for key, val in getproxies().items()292 if ("://" in key or key in supported_proxy_schemes)293 }294295296def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:297 return value.encode(encoding) if isinstance(value, str) else value298299300def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:301 return value if isinstance(value, str) else value.decode(encoding)302303304def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:305 return value if isinstance(match_type_of, str) else value.encode()306307308def unquote(value: str) -> str:309 return value[1:-1] if value[0] == value[-1] == '"' else value310311312def flatten_queryparams(313 queryparams: typing.Mapping[314 str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]315 ]316) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:317 """318 Convert a mapping of query params into a flat list of two-tuples319 representing each item.320321 Example:322 >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})323 [("q", "httpx), ("tag", "python"), ("tag", "dev")]324 """325 items = []326327 for k, v in queryparams.items():328 if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):329 for u in v:330 items.append((k, u))331 else:332 items.append((k, typing.cast("PrimitiveData", v)))333334 return items335336337class ElapsedTimer:338 def __init__(self) -> None:339 self.start: float = perf_counter()340 self.end: typing.Optional[float] = None341342 def __enter__(self) -> "ElapsedTimer":343 self.start = perf_counter()344 return self345346 def __exit__(347 self,348 exc_type: typing.Type[BaseException] = None,349 exc_value: BaseException = None,350 traceback: TracebackType = None,351 ) -> None:352 self.end = perf_counter()353354 @property355 def elapsed(self) -> timedelta:356 if self.end is None:357 return timedelta(seconds=perf_counter() - self.start)358 return timedelta(seconds=self.end - self.start)359360361@contextlib.contextmanager362def as_network_error(*exception_classes: type) -> typing.Iterator[None]:363 try:364 yield365 except BaseException as exc:366 for cls in exception_classes:367 if isinstance(exc, cls):368 raise NetworkError(exc) from exc369 raise
deleted:httpx/api.py-398 removed
1import typing23from .auth import AuthTypes4from .client import Client, StreamContextManager5from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes6from .models import (7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 Request,11 RequestData,12 RequestFiles,13 Response,14 URLTypes,15)161718def request(19 method: str,20 url: URLTypes,21 *,22 params: QueryParamTypes = None,23 data: RequestData = None,24 files: RequestFiles = None,25 json: typing.Any = None,26 headers: HeaderTypes = None,27 cookies: CookieTypes = None,28 auth: AuthTypes = None,29 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,30 allow_redirects: bool = True,31 verify: VerifyTypes = True,32 cert: CertTypes = None,33 trust_env: bool = True,34) -> Response:35 """36 Sends an HTTP request.3738 **Parameters:**3940 * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,41 `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.42 * **url** - URL for the new `Request` object.43 * **params** - *(optional)* Query parameters to include in the URL, as a44 string, dictionary, or list of two-tuples.45 * **data** - *(optional)* Data to include in the body of the request, as a46 dictionary47 * **files** - *(optional)* A dictionary of upload files to include in the48 body of the request.49 * **json** - *(optional)* A JSON serializable object to include in the body50 of the request.51 * **headers** - *(optional)* Dictionary of HTTP headers to include in the52 request.53 * **cookies** - *(optional)* Dictionary of Cookie items to include in the54 request.55 * **auth** - *(optional)* An authentication class to use when sending the56 request.57 * **timeout** - *(optional)* The timeout configuration to use when sending58 the request.59 * **allow_redirects** - *(optional)* Enables or disables HTTP redirects.60 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to61 verify the identity of requested hosts. Either `True` (default CA bundle),62 a path to an SSL certificate file, or `False` (disable verification).63 * **cert** - *(optional)* An SSL certificate used by the requested host64 to authenticate the client. Either a path to an SSL certificate file, or65 two-tuple of (certificate file, key file), or a three-tuple of (certificate66 file, key file, password).67 * **trust_env** - *(optional)* Enables or disables usage of environment68 variables for configuration.69 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy70 URLs.7172 **Returns:** `Response`7374 Usage:7576 ```77 >>> import httpx78 >>> response = httpx.request('GET', 'https://httpbin.org/get')79 >>> response80 <Response [200 OK]>81 ```82 """83 with Client(84 cert=cert, verify=verify, timeout=timeout, trust_env=trust_env,85 ) as client:86 return client.request(87 method=method,88 url=url,89 data=data,90 files=files,91 json=json,92 params=params,93 headers=headers,94 cookies=cookies,95 auth=auth,96 allow_redirects=allow_redirects,97 )9899100def stream(101 method: str,102 url: URLTypes,103 *,104 params: QueryParamTypes = None,105 data: RequestData = None,106 files: RequestFiles = None,107 json: typing.Any = None,108 headers: HeaderTypes = None,109 cookies: CookieTypes = None,110 auth: AuthTypes = None,111 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,112 allow_redirects: bool = True,113 verify: VerifyTypes = True,114 cert: CertTypes = None,115 trust_env: bool = True,116) -> StreamContextManager:117 client = Client(cert=cert, verify=verify, trust_env=trust_env)118 request = Request(119 method=method,120 url=url,121 params=params,122 data=data,123 files=files,124 json=json,125 headers=headers,126 cookies=cookies,127 )128 return StreamContextManager(129 client=client,130 request=request,131 auth=auth,132 timeout=timeout,133 allow_redirects=allow_redirects,134 close_client=True,135 )136137138def get(139 url: URLTypes,140 *,141 params: QueryParamTypes = None,142 headers: HeaderTypes = None,143 cookies: CookieTypes = None,144 auth: AuthTypes = None,145 allow_redirects: bool = True,146 cert: CertTypes = None,147 verify: VerifyTypes = True,148 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,149 trust_env: bool = True,150) -> Response:151 """152 Sends a `GET` request.153154 **Parameters**: See `httpx.request`.155156 Note that the `data`, `files`, and `json` parameters are not available on157 this function, as `GET` requests should not include a request body.158 """159 return request(160 "GET",161 url,162 params=params,163 headers=headers,164 cookies=cookies,165 auth=auth,166 allow_redirects=allow_redirects,167 cert=cert,168 verify=verify,169 timeout=timeout,170 trust_env=trust_env,171 )172173174def options(175 url: URLTypes,176 *,177 params: QueryParamTypes = None,178 headers: HeaderTypes = None,179 cookies: CookieTypes = None,180 auth: AuthTypes = None,181 allow_redirects: bool = True,182 cert: CertTypes = None,183 verify: VerifyTypes = True,184 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,185 trust_env: bool = True,186) -> Response:187 """188 Sends an `OPTIONS` request.189190 **Parameters**: See `httpx.request`.191192 Note that the `data`, `files`, and `json` parameters are not available on193 this function, as `OPTIONS` requests should not include a request body.194 """195 return request(196 "OPTIONS",197 url,198 params=params,199 headers=headers,200 cookies=cookies,201 auth=auth,202 allow_redirects=allow_redirects,203 cert=cert,204 verify=verify,205 timeout=timeout,206 trust_env=trust_env,207 )208209210def head(211 url: URLTypes,212 *,213 params: QueryParamTypes = None,214 headers: HeaderTypes = None,215 cookies: CookieTypes = None,216 auth: AuthTypes = None,217 allow_redirects: bool = False, # Note: Differs to usual default.218 cert: CertTypes = None,219 verify: VerifyTypes = True,220 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,221 trust_env: bool = True,222) -> Response:223 """224 Sends a `HEAD` request.225226 **Parameters**: See `httpx.request`.227228 Note that the `data`, `files`, and `json` parameters are not available on229 this function, as `HEAD` requests should not include a request body. The230 `HEAD` method also differs from the other cases in that `allow_redirects`231 defaults to `False`.232 """233 return request(234 "HEAD",235 url,236 params=params,237 headers=headers,238 cookies=cookies,239 auth=auth,240 allow_redirects=allow_redirects,241 cert=cert,242 verify=verify,243 timeout=timeout,244 trust_env=trust_env,245 )246247248def post(249 url: URLTypes,250 *,251 data: RequestData = None,252 files: RequestFiles = None,253 json: typing.Any = None,254 params: QueryParamTypes = None,255 headers: HeaderTypes = None,256 cookies: CookieTypes = None,257 auth: AuthTypes = None,258 allow_redirects: bool = True,259 cert: CertTypes = None,260 verify: VerifyTypes = True,261 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,262 trust_env: bool = True,263) -> Response:264 """265 Sends a `POST` request.266267 **Parameters**: See `httpx.request`.268 """269 return request(270 "POST",271 url,272 data=data,273 files=files,274 json=json,275 params=params,276 headers=headers,277 cookies=cookies,278 auth=auth,279 allow_redirects=allow_redirects,280 cert=cert,281 verify=verify,282 timeout=timeout,283 trust_env=trust_env,284 )285286287def put(288 url: URLTypes,289 *,290 data: RequestData = None,291 files: RequestFiles = None,292 json: typing.Any = None,293 params: QueryParamTypes = None,294 headers: HeaderTypes = None,295 cookies: CookieTypes = None,296 auth: AuthTypes = None,297 allow_redirects: bool = True,298 cert: CertTypes = None,299 verify: VerifyTypes = True,300 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,301 trust_env: bool = True,302) -> Response:303 """304 Sends a `PUT` request.305306 **Parameters**: See `httpx.request`.307 """308 return request(309 "PUT",310 url,311 data=data,312 files=files,313 json=json,314 params=params,315 headers=headers,316 cookies=cookies,317 auth=auth,318 allow_redirects=allow_redirects,319 cert=cert,320 verify=verify,321 timeout=timeout,322 trust_env=trust_env,323 )324325326def patch(327 url: URLTypes,328 *,329 data: RequestData = None,330 files: RequestFiles = None,331 json: typing.Any = None,332 params: QueryParamTypes = None,333 headers: HeaderTypes = None,334 cookies: CookieTypes = None,335 auth: AuthTypes = None,336 allow_redirects: bool = True,337 cert: CertTypes = None,338 verify: VerifyTypes = True,339 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,340 trust_env: bool = True,341) -> Response:342 """343 Sends a `PATCH` request.344345 **Parameters**: See `httpx.request`.346 """347 return request(348 "PATCH",349 url,350 data=data,351 files=files,352 json=json,353 params=params,354 headers=headers,355 cookies=cookies,356 auth=auth,357 allow_redirects=allow_redirects,358 cert=cert,359 verify=verify,360 timeout=timeout,361 trust_env=trust_env,362 )363364365def delete(366 url: URLTypes,367 *,368 params: QueryParamTypes = None,369 headers: HeaderTypes = None,370 cookies: CookieTypes = None,371 auth: AuthTypes = None,372 allow_redirects: bool = True,373 cert: CertTypes = None,374 verify: VerifyTypes = True,375 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,376 trust_env: bool = True,377) -> Response:378 """379 Sends a `DELETE` request.380381 **Parameters**: See `httpx.request`.382383 Note that the `data`, `files`, and `json` parameters are not available on384 this function, as `DELETE` requests should not include a request body.385 """386 return request(387 "DELETE",388 url,389 params=params,390 headers=headers,391 cookies=cookies,392 auth=auth,393 allow_redirects=allow_redirects,394 cert=cert,395 verify=verify,396 timeout=timeout,397 trust_env=trust_env,398 )
deleted:httpx/auth.py-255 removed
1import hashlib2import os3import re4import time5import typing6from base64 import b64encode7from urllib.request import parse_http_list89from .exceptions import ProtocolError, RequestBodyUnavailable10from .models import Request, Response11from .utils import to_bytes, to_str, unquote1213AuthTypes = typing.Union[14 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],15 typing.Callable[["Request"], "Request"],16 "Auth",17]181920class Auth:21 """22 Base class for all authentication schemes.23 """2425 requires_request_body = False2627 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:28 """29 Execute the authentication flow.3031 To dispatch a request, `yield` it:3233 ```34 yield request35 ```3637 The client will `.send()` the response back into the flow generator. You can38 access it like so:3940 ```41 response = yield request42 ```4344 A `return` (or reaching the end of the generator) will result in the45 client returning the last response obtained from the server.4647 You can dispatch as many requests as is necessary.48 """49 yield request505152class FunctionAuth(Auth):53 """54 Allows the 'auth' argument to be passed as a simple callable function,55 that takes the request, and returns a new, modified request.56 """5758 def __init__(self, func: typing.Callable[[Request], Request]) -> None:59 self.func = func6061 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:62 yield self.func(request)636465class BasicAuth(Auth):66 """67 Allows the 'auth' argument to be passed as a (username, password) pair,68 and uses HTTP Basic authentication.69 """7071 def __init__(72 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]73 ):74 self.auth_header = self.build_auth_header(username, password)7576 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:77 request.headers["Authorization"] = self.auth_header78 yield request7980 def build_auth_header(81 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]82 ) -> str:83 userpass = b":".join((to_bytes(username), to_bytes(password)))84 token = b64encode(userpass).decode().strip()85 return f"Basic {token}"868788class DigestAuth(Auth):89 ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable] = {90 "MD5": hashlib.md5,91 "MD5-SESS": hashlib.md5,92 "SHA": hashlib.sha1,93 "SHA-SESS": hashlib.sha1,94 "SHA-256": hashlib.sha256,95 "SHA-256-SESS": hashlib.sha256,96 "SHA-512": hashlib.sha512,97 "SHA-512-SESS": hashlib.sha512,98 }99100 def __init__(101 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]102 ) -> None:103 self.username = to_bytes(username)104 self.password = to_bytes(password)105106 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:107 if not request.stream.can_replay():108 raise RequestBodyUnavailable("Request body is no longer available.")109 response = yield request110111 if response.status_code != 401 or "www-authenticate" not in response.headers:112 # If the response is not a 401 WWW-Authenticate, then we don't113 # need to build an authenticated request.114 return115116 header = response.headers["www-authenticate"]117 try:118 challenge = DigestAuthChallenge.from_header(header)119 except ValueError:120 raise ProtocolError("Malformed Digest authentication header")121122 request.headers["Authorization"] = self._build_auth_header(request, challenge)123 yield request124125 def _build_auth_header(126 self, request: Request, challenge: "DigestAuthChallenge"127 ) -> str:128 hash_func = self.ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]129130 def digest(data: bytes) -> bytes:131 return hash_func(data).hexdigest().encode()132133 A1 = b":".join((self.username, challenge.realm, self.password))134135 path = request.url.full_path.encode("utf-8")136 A2 = b":".join((request.method.encode(), path))137 # TODO: implement auth-int138 HA2 = digest(A2)139140 nonce_count = 1 # TODO: implement nonce counting141 nc_value = b"%08x" % nonce_count142 cnonce = self._get_client_nonce(nonce_count, challenge.nonce)143144 HA1 = digest(A1)145 if challenge.algorithm.lower().endswith("-sess"):146 HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))147148 qop = self._resolve_qop(challenge.qop)149 if qop is None:150 digest_data = [HA1, challenge.nonce, HA2]151 else:152 digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]153 key_digest = b":".join(digest_data)154155 format_args = {156 "username": self.username,157 "realm": challenge.realm,158 "nonce": challenge.nonce,159 "uri": path,160 "response": digest(b":".join((HA1, key_digest))),161 "algorithm": challenge.algorithm.encode(),162 }163 if challenge.opaque:164 format_args["opaque"] = challenge.opaque165 if qop:166 format_args["qop"] = b"auth"167 format_args["nc"] = nc_value168 format_args["cnonce"] = cnonce169170 return "Digest " + self._get_header_value(format_args)171172 def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:173 s = str(nonce_count).encode()174 s += nonce175 s += time.ctime().encode()176 s += os.urandom(8)177178 return hashlib.sha1(s).hexdigest()[:16].encode()179180 def _get_header_value(self, header_fields: typing.Dict[str, bytes]) -> str:181 NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")182 QUOTED_TEMPLATE = '{}="{}"'183 NON_QUOTED_TEMPLATE = "{}={}"184185 header_value = ""186 for i, (field, value) in enumerate(header_fields.items()):187 if i > 0:188 header_value += ", "189 template = (190 QUOTED_TEMPLATE191 if field not in NON_QUOTED_FIELDS192 else NON_QUOTED_TEMPLATE193 )194 header_value += template.format(field, to_str(value))195196 return header_value197198 def _resolve_qop(self, qop: typing.Optional[bytes]) -> typing.Optional[bytes]:199 if qop is None:200 return None201 qops = re.split(b", ?", qop)202 if b"auth" in qops:203 return b"auth"204205 if qops == [b"auth-int"]:206 raise NotImplementedError("Digest auth-int support is not yet implemented")207208 raise ProtocolError(f'Unexpected qop value "{qop!r}" in digest auth')209210211class DigestAuthChallenge:212 def __init__(213 self,214 realm: bytes,215 nonce: bytes,216 algorithm: str = None,217 opaque: typing.Optional[bytes] = None,218 qop: typing.Optional[bytes] = None,219 ) -> None:220 self.realm = realm221 self.nonce = nonce222 self.algorithm = algorithm or "MD5"223 self.opaque = opaque224 self.qop = qop225226 @classmethod227 def from_header(cls, header: str) -> "DigestAuthChallenge":228 """Returns a challenge from a Digest WWW-Authenticate header.229 These take the form of:230 `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`231 """232 scheme, _, fields = header.partition(" ")233 if scheme.lower() != "digest":234 raise ValueError("Header does not start with 'Digest'")235236 header_dict: typing.Dict[str, str] = {}237 for field in parse_http_list(fields):238 key, value = field.strip().split("=", 1)239 header_dict[key] = unquote(value)240241 try:242 return cls.from_header_dict(header_dict)243 except KeyError as exc:244 raise ValueError("Malformed Digest WWW-Authenticate header") from exc245246 @classmethod247 def from_header_dict(cls, header_dict: dict) -> "DigestAuthChallenge":248 realm = header_dict["realm"].encode()249 nonce = header_dict["nonce"].encode()250 qop = header_dict["qop"].encode() if "qop" in header_dict else None251 opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None252 algorithm = header_dict.get("algorithm")253 return cls(254 realm=realm, nonce=nonce, qop=qop, opaque=opaque, algorithm=algorithm255 )
deleted:httpx/client.py-1472 removed
1import functools2import typing3from types import TracebackType45import hstspreload67from .auth import Auth, AuthTypes, BasicAuth, FunctionAuth8from .backends.base import ConcurrencyBackend9from .config import (10 DEFAULT_MAX_REDIRECTS,11 DEFAULT_POOL_LIMITS,12 DEFAULT_TIMEOUT_CONFIG,13 UNSET,14 CertTypes,15 PoolLimits,16 ProxiesTypes,17 Proxy,18 Timeout,19 TimeoutTypes,20 UnsetType,21 VerifyTypes,22)23from .content_streams import ContentStream24from .dispatch.asgi import ASGIDispatch25from .dispatch.base import AsyncDispatcher, SyncDispatcher26from .dispatch.connection_pool import ConnectionPool27from .dispatch.proxy_http import HTTPProxy28from .dispatch.urllib3 import URLLib3Dispatcher29from .dispatch.wsgi import WSGIDispatch30from .exceptions import (31 HTTPError,32 InvalidURL,33 RedirectLoop,34 RequestBodyUnavailable,35 TooManyRedirects,36)37from .models import (38 URL,39 Cookies,40 CookieTypes,41 Headers,42 HeaderTypes,43 Origin,44 QueryParams,45 QueryParamTypes,46 Request,47 RequestData,48 RequestFiles,49 Response,50 URLTypes,51)52from .status_codes import codes53from .utils import NetRCInfo, get_environment_proxies, get_logger5455logger = get_logger(__name__)565758class BaseClient:59 def __init__(60 self,61 *,62 auth: AuthTypes = None,63 params: QueryParamTypes = None,64 headers: HeaderTypes = None,65 cookies: CookieTypes = None,66 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,67 max_redirects: int = DEFAULT_MAX_REDIRECTS,68 base_url: URLTypes = None,69 trust_env: bool = True,70 ):71 if base_url is None:72 self.base_url = URL("", allow_relative=True)73 else:74 self.base_url = URL(base_url)7576 if params is None:77 params = {}7879 self.auth = auth80 self._params = QueryParams(params)81 self._headers = Headers(headers)82 self._cookies = Cookies(cookies)83 self.timeout = Timeout(timeout)84 self.max_redirects = max_redirects85 self.trust_env = trust_env86 self.netrc = NetRCInfo()8788 def get_proxy_map(89 self, proxies: typing.Optional[ProxiesTypes], trust_env: bool,90 ) -> typing.Dict[str, Proxy]:91 if proxies is None:92 if trust_env:93 return {94 key: Proxy(url=url)95 for key, url in get_environment_proxies().items()96 }97 return {}98 elif isinstance(proxies, (str, URL, Proxy)):99 proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies100 return {"all": proxy}101 elif isinstance(proxies, AsyncDispatcher): # pragma: nocover102 raise RuntimeError(103 "Passing a dispatcher instance to 'proxies=' is no longer "104 "supported. Use `httpx.Proxy() instead.`"105 )106 else:107 new_proxies = {}108 for key, value in proxies.items():109 if isinstance(value, (str, URL, Proxy)):110 proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value111 new_proxies[str(key)] = proxy112 elif isinstance(value, AsyncDispatcher): # pragma: nocover113 raise RuntimeError(114 "Passing a dispatcher instance to 'proxies=' is "115 "no longer supported. Use `httpx.Proxy() instead.`"116 )117 return new_proxies118119 @property120 def headers(self) -> Headers:121 """122 HTTP headers to include when sending requests.123 """124 return self._headers125126 @headers.setter127 def headers(self, headers: HeaderTypes) -> None:128 self._headers = Headers(headers)129130 @property131 def cookies(self) -> Cookies:132 """133 Cookie values to include when sending requests.134 """135 return self._cookies136137 @cookies.setter138 def cookies(self, cookies: CookieTypes) -> None:139 self._cookies = Cookies(cookies)140141 @property142 def params(self) -> QueryParams:143 """144 Query parameters to include in the URL when sending requests.145 """146 return self._params147148 @params.setter149 def params(self, params: QueryParamTypes) -> None:150 self._params = QueryParams(params)151152 def stream(153 self,154 method: str,155 url: URLTypes,156 *,157 data: RequestData = None,158 files: RequestFiles = None,159 json: typing.Any = None,160 params: QueryParamTypes = None,161 headers: HeaderTypes = None,162 cookies: CookieTypes = None,163 auth: AuthTypes = None,164 allow_redirects: bool = True,165 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,166 ) -> "StreamContextManager":167 request = self.build_request(168 method=method,169 url=url,170 data=data,171 files=files,172 json=json,173 params=params,174 headers=headers,175 cookies=cookies,176 )177 return StreamContextManager(178 client=self,179 request=request,180 auth=auth,181 allow_redirects=allow_redirects,182 timeout=timeout,183 )184185 def build_request(186 self,187 method: str,188 url: URLTypes,189 *,190 data: RequestData = None,191 files: RequestFiles = None,192 json: typing.Any = None,193 params: QueryParamTypes = None,194 headers: HeaderTypes = None,195 cookies: CookieTypes = None,196 ) -> Request:197 """198 Build and return a request instance.199 """200 url = self.merge_url(url)201 headers = self.merge_headers(headers)202 cookies = self.merge_cookies(cookies)203 params = self.merge_queryparams(params)204 return Request(205 method,206 url,207 data=data,208 files=files,209 json=json,210 params=params,211 headers=headers,212 cookies=cookies,213 )214215 def merge_url(self, url: URLTypes) -> URL:216 """217 Merge a URL argument together with any 'base_url' on the client,218 to create the URL used for the outgoing request.219 """220 url = self.base_url.join(relative_url=url)221 if url.scheme == "http" and hstspreload.in_hsts_preload(url.host):222 port = None if url.port == 80 else url.port223 url = url.copy_with(scheme="https", port=port)224 return url225226 def merge_cookies(227 self, cookies: CookieTypes = None228 ) -> typing.Optional[CookieTypes]:229 """230 Merge a cookies argument together with any cookies on the client,231 to create the cookies used for the outgoing request.232 """233 if cookies or self.cookies:234 merged_cookies = Cookies(self.cookies)235 merged_cookies.update(cookies)236 return merged_cookies237 return cookies238239 def merge_headers(240 self, headers: HeaderTypes = None241 ) -> typing.Optional[HeaderTypes]:242 """243 Merge a headers argument together with any headers on the client,244 to create the headers used for the outgoing request.245 """246 if headers or self.headers:247 merged_headers = Headers(self.headers)248 merged_headers.update(headers)249 return merged_headers250 return headers251252 def merge_queryparams(253 self, params: QueryParamTypes = None254 ) -> typing.Optional[QueryParamTypes]:255 """256 Merge a queryparams argument together with any queryparams on the client,257 to create the queryparams used for the outgoing request.258 """259 if params or self.params:260 merged_queryparams = QueryParams(self.params)261 merged_queryparams.update(params)262 return merged_queryparams263 return params264265 def build_auth(self, request: Request, auth: AuthTypes = None) -> Auth:266 auth = self.auth if auth is None else auth267268 if auth is not None:269 if isinstance(auth, tuple):270 return BasicAuth(username=auth[0], password=auth[1])271 elif isinstance(auth, Auth):272 return auth273 elif callable(auth):274 return FunctionAuth(func=auth)275 raise TypeError('Invalid "auth" argument.')276277 username, password = request.url.username, request.url.password278 if username or password:279 return BasicAuth(username=username, password=password)280281 if self.trust_env and "Authorization" not in request.headers:282 credentials = self.netrc.get_credentials(request.url.authority)283 if credentials is not None:284 return BasicAuth(username=credentials[0], password=credentials[1])285286 return Auth()287288 def build_redirect_request(self, request: Request, response: Response) -> Request:289 """290 Given a request and a redirect response, return a new request that291 should be used to effect the redirect.292 """293 method = self.redirect_method(request, response)294 url = self.redirect_url(request, response)295 headers = self.redirect_headers(request, url, method)296 stream = self.redirect_stream(request, method)297 cookies = Cookies(self.cookies)298 return Request(299 method=method, url=url, headers=headers, cookies=cookies, stream=stream300 )301302 def redirect_method(self, request: Request, response: Response) -> str:303 """304 When being redirected we may want to change the method of the request305 based on certain specs or browser behavior.306 """307 method = request.method308309 # https://tools.ietf.org/html/rfc7231#section-6.4.4310 if response.status_code == codes.SEE_OTHER and method != "HEAD":311 method = "GET"312313 # Do what the browsers do, despite standards...314 # Turn 302s into GETs.315 if response.status_code == codes.FOUND and method != "HEAD":316 method = "GET"317318 # If a POST is responded to with a 301, turn it into a GET.319 # This bizarre behaviour is explained in 'requests' issue 1704.320 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":321 method = "GET"322323 return method324325 def redirect_url(self, request: Request, response: Response) -> URL:326 """327 Return the URL for the redirect to follow.328 """329 location = response.headers["Location"]330331 url = URL(location, allow_relative=True)332333 # Handle malformed 'Location' headers that are "absolute" form, have no host.334 # See: https://github.com/encode/httpx/issues/771335 if url.scheme and not url.host:336 url = url.copy_with(host=request.url.host)337338 # Facilitate relative 'Location' headers, as allowed by RFC 7231.339 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')340 if url.is_relative_url:341 url = request.url.join(url)342343 # Attach previous fragment if needed (RFC 7231 7.1.2)344 if request.url.fragment and not url.fragment:345 url = url.copy_with(fragment=request.url.fragment)346347 return url348349 def redirect_headers(self, request: Request, url: URL, method: str) -> Headers:350 """351 Return the headers that should be used for the redirect request.352 """353 headers = Headers(request.headers)354355 if Origin(url) != Origin(request.url):356 # Strip Authorization headers when responses are redirected away from357 # the origin.358 headers.pop("Authorization", None)359 headers["Host"] = url.authority360361 if method != request.method and method == "GET":362 # If we've switch to a 'GET' request, then strip any headers which363 # are only relevant to the request body.364 headers.pop("Content-Length", None)365 headers.pop("Transfer-Encoding", None)366367 # We should use the client cookie store to determine any cookie header,368 # rather than whatever was on the original outgoing request.369 headers.pop("Cookie", None)370371 return headers372373 def redirect_stream(374 self, request: Request, method: str375 ) -> typing.Optional[ContentStream]:376 """377 Return the body that should be used for the redirect request.378 """379 if method != request.method and method == "GET":380 return None381382 if not request.stream.can_replay():383 raise RequestBodyUnavailable(384 "Got a redirect response, but the request body was streaming "385 "and is no longer available."386 )387388 return request.stream389390391class Client(BaseClient):392 """393 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.394395 Usage:396397 ```python398 >>> client = httpx.Client()399 >>> response = client.get('https://example.org')400 ```401402 **Parameters:**403404 * **auth** - *(optional)* An authentication class to use when sending405 requests.406 * **params** - *(optional)* Query parameters to include in request URLs, as407 a string, dictionary, or list of two-tuples.408 * **headers** - *(optional)* Dictionary of HTTP headers to include when409 sending requests.410 * **cookies** - *(optional)* Dictionary of Cookie items to include when411 sending requests.412 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to413 verify the identity of requested hosts. Either `True` (default CA bundle),414 a path to an SSL certificate file, or `False` (disable verification).415 * **cert** - *(optional)* An SSL certificate used by the requested host416 to authenticate the client. Either a path to an SSL certificate file, or417 two-tuple of (certificate file, key file), or a three-tuple of (certificate418 file, key file, password).419 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy420 URLs.421 * **timeout** - *(optional)* The timeout configuration to use when sending422 requests.423 * **pool_limits** - *(optional)* The connection pool configuration to use424 when determining the maximum number of concurrently open HTTP connections.425 * **max_redirects** - *(optional)* The maximum number of redirect responses426 that should be followed.427 * **base_url** - *(optional)* A URL to use as the base when building428 request URLs.429 * **dispatch** - *(optional)* A dispatch class to use for sending requests430 over the network.431 * **app** - *(optional)* An ASGI application to send requests to,432 rather than sending actual network requests.433 * **trust_env** - *(optional)* Enables or disables usage of environment434 variables for configuration.435 """436437 def __init__(438 self,439 *,440 auth: AuthTypes = None,441 params: QueryParamTypes = None,442 headers: HeaderTypes = None,443 cookies: CookieTypes = None,444 verify: VerifyTypes = True,445 cert: CertTypes = None,446 proxies: ProxiesTypes = None,447 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,448 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,449 max_redirects: int = DEFAULT_MAX_REDIRECTS,450 base_url: URLTypes = None,451 dispatch: SyncDispatcher = None,452 app: typing.Callable = None,453 trust_env: bool = True,454 ):455 super().__init__(456 auth=auth,457 params=params,458 headers=headers,459 cookies=cookies,460 timeout=timeout,461 max_redirects=max_redirects,462 base_url=base_url,463 trust_env=trust_env,464 )465466 proxy_map = self.get_proxy_map(proxies, trust_env)467468 self.dispatch = self.init_dispatch(469 verify=verify,470 cert=cert,471 pool_limits=pool_limits,472 dispatch=dispatch,473 app=app,474 trust_env=trust_env,475 )476 self.proxies: typing.Dict[str, SyncDispatcher] = {477 key: self.init_proxy_dispatch(478 proxy,479 verify=verify,480 cert=cert,481 pool_limits=pool_limits,482 trust_env=trust_env,483 )484 for key, proxy in proxy_map.items()485 }486487 def init_dispatch(488 self,489 verify: VerifyTypes = True,490 cert: CertTypes = None,491 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,492 dispatch: SyncDispatcher = None,493 app: typing.Callable = None,494 trust_env: bool = True,495 ) -> SyncDispatcher:496 if dispatch is not None:497 return dispatch498499 if app is not None:500 return WSGIDispatch(app=app)501502 return URLLib3Dispatcher(503 verify=verify, cert=cert, pool_limits=pool_limits, trust_env=trust_env,504 )505506 def init_proxy_dispatch(507 self,508 proxy: Proxy,509 verify: VerifyTypes = True,510 cert: CertTypes = None,511 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,512 trust_env: bool = True,513 ) -> SyncDispatcher:514 return URLLib3Dispatcher(515 proxy=proxy,516 verify=verify,517 cert=cert,518 pool_limits=pool_limits,519 trust_env=trust_env,520 )521522 def dispatcher_for_url(self, url: URL) -> SyncDispatcher:523 """524 Returns the SyncDispatcher instance that should be used for a given URL.525 This will either be the standard connection pool, or a proxy.526 """527 if self.proxies:528 is_default_port = (url.scheme == "http" and url.port == 80) or (529 url.scheme == "https" and url.port == 443530 )531 hostname = f"{url.host}:{url.port}"532 proxy_keys = (533 f"{url.scheme}://{hostname}",534 f"{url.scheme}://{url.host}" if is_default_port else None,535 f"all://{hostname}",536 f"all://{url.host}" if is_default_port else None,537 url.scheme,538 "all",539 )540 for proxy_key in proxy_keys:541 if proxy_key and proxy_key in self.proxies:542 dispatcher = self.proxies[proxy_key]543 return dispatcher544545 return self.dispatch546547 def request(548 self,549 method: str,550 url: URLTypes,551 *,552 data: RequestData = None,553 files: RequestFiles = None,554 json: typing.Any = None,555 params: QueryParamTypes = None,556 headers: HeaderTypes = None,557 cookies: CookieTypes = None,558 auth: AuthTypes = None,559 allow_redirects: bool = True,560 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,561 ) -> Response:562 request = self.build_request(563 method=method,564 url=url,565 data=data,566 files=files,567 json=json,568 params=params,569 headers=headers,570 cookies=cookies,571 )572 return self.send(573 request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,574 )575576 def send(577 self,578 request: Request,579 *,580 stream: bool = False,581 auth: AuthTypes = None,582 allow_redirects: bool = True,583 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,584 ) -> Response:585 if request.url.scheme not in ("http", "https"):586 raise InvalidURL('URL scheme must be "http" or "https".')587588 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)589590 auth = self.build_auth(request, auth)591592 response = self.send_handling_redirects(593 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,594 )595596 if not stream:597 try:598 response.read()599 finally:600 response.close()601602 return response603604 def send_handling_redirects(605 self,606 request: Request,607 auth: Auth,608 timeout: Timeout,609 allow_redirects: bool = True,610 history: typing.List[Response] = None,611 ) -> Response:612 if history is None:613 history = []614615 while True:616 if len(history) > self.max_redirects:617 raise TooManyRedirects()618 urls = ((resp.request.method, resp.url) for resp in history)619 if (request.method, request.url) in urls:620 raise RedirectLoop()621622 response = self.send_handling_auth(623 request, auth=auth, timeout=timeout, history=history624 )625 response.history = list(history)626627 if not response.is_redirect:628 return response629630 if allow_redirects:631 response.read()632 request = self.build_redirect_request(request, response)633 history = history + [response]634635 if not allow_redirects:636 response.call_next = functools.partial(637 self.send_handling_redirects,638 request=request,639 auth=auth,640 timeout=timeout,641 allow_redirects=False,642 history=history,643 )644 return response645646 def send_handling_auth(647 self,648 request: Request,649 history: typing.List[Response],650 auth: Auth,651 timeout: Timeout,652 ) -> Response:653 if auth.requires_request_body:654 request.read()655656 auth_flow = auth.auth_flow(request)657 request = next(auth_flow)658 while True:659 response = self.send_single_request(request, timeout)660 try:661 next_request = auth_flow.send(response)662 except StopIteration:663 return response664 except BaseException as exc:665 response.close()666 raise exc from None667 else:668 response.history = list(history)669 response.read()670 request = next_request671 history.append(response)672673 def send_single_request(self, request: Request, timeout: Timeout,) -> Response:674 """675 Sends a single request, without handling any redirections.676 """677678 dispatcher = self.dispatcher_for_url(request.url)679680 try:681 response = dispatcher.send(request, timeout=timeout)682 except HTTPError as exc:683 # Add the original request to any HTTPError unless684 # there'a already a request attached in the case of685 # a ProxyError.686 if exc.request is None:687 exc.request = request688 raise689690 self.cookies.extract_cookies(response)691692 status = f"{response.status_code} {response.reason_phrase}"693 response_line = f"{response.http_version} {status}"694 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')695696 return response697698 def get(699 self,700 url: URLTypes,701 *,702 params: QueryParamTypes = None,703 headers: HeaderTypes = None,704 cookies: CookieTypes = None,705 auth: AuthTypes = None,706 allow_redirects: bool = True,707 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,708 ) -> Response:709 return self.request(710 "GET",711 url,712 params=params,713 headers=headers,714 cookies=cookies,715 auth=auth,716 allow_redirects=allow_redirects,717 timeout=timeout,718 )719720 def options(721 self,722 url: URLTypes,723 *,724 params: QueryParamTypes = None,725 headers: HeaderTypes = None,726 cookies: CookieTypes = None,727 auth: AuthTypes = None,728 allow_redirects: bool = True,729 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,730 ) -> Response:731 return self.request(732 "OPTIONS",733 url,734 params=params,735 headers=headers,736 cookies=cookies,737 auth=auth,738 allow_redirects=allow_redirects,739 timeout=timeout,740 )741742 def head(743 self,744 url: URLTypes,745 *,746 params: QueryParamTypes = None,747 headers: HeaderTypes = None,748 cookies: CookieTypes = None,749 auth: AuthTypes = None,750 allow_redirects: bool = False, # NOTE: Differs to usual default.751 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,752 ) -> Response:753 return self.request(754 "HEAD",755 url,756 params=params,757 headers=headers,758 cookies=cookies,759 auth=auth,760 allow_redirects=allow_redirects,761 timeout=timeout,762 )763764 def post(765 self,766 url: URLTypes,767 *,768 data: RequestData = None,769 files: RequestFiles = None,770 json: typing.Any = None,771 params: QueryParamTypes = None,772 headers: HeaderTypes = None,773 cookies: CookieTypes = None,774 auth: AuthTypes = None,775 allow_redirects: bool = True,776 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,777 ) -> Response:778 return self.request(779 "POST",780 url,781 data=data,782 files=files,783 json=json,784 params=params,785 headers=headers,786 cookies=cookies,787 auth=auth,788 allow_redirects=allow_redirects,789 timeout=timeout,790 )791792 def put(793 self,794 url: URLTypes,795 *,796 data: RequestData = None,797 files: RequestFiles = None,798 json: typing.Any = None,799 params: QueryParamTypes = None,800 headers: HeaderTypes = None,801 cookies: CookieTypes = None,802 auth: AuthTypes = None,803 allow_redirects: bool = True,804 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,805 ) -> Response:806 return self.request(807 "PUT",808 url,809 data=data,810 files=files,811 json=json,812 params=params,813 headers=headers,814 cookies=cookies,815 auth=auth,816 allow_redirects=allow_redirects,817 timeout=timeout,818 )819820 def patch(821 self,822 url: URLTypes,823 *,824 data: RequestData = None,825 files: RequestFiles = None,826 json: typing.Any = None,827 params: QueryParamTypes = None,828 headers: HeaderTypes = None,829 cookies: CookieTypes = None,830 auth: AuthTypes = None,831 allow_redirects: bool = True,832 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,833 ) -> Response:834 return self.request(835 "PATCH",836 url,837 data=data,838 files=files,839 json=json,840 params=params,841 headers=headers,842 cookies=cookies,843 auth=auth,844 allow_redirects=allow_redirects,845 timeout=timeout,846 )847848 def delete(849 self,850 url: URLTypes,851 *,852 params: QueryParamTypes = None,853 headers: HeaderTypes = None,854 cookies: CookieTypes = None,855 auth: AuthTypes = None,856 allow_redirects: bool = True,857 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,858 ) -> Response:859 return self.request(860 "DELETE",861 url,862 params=params,863 headers=headers,864 cookies=cookies,865 auth=auth,866 allow_redirects=allow_redirects,867 timeout=timeout,868 )869870 def close(self) -> None:871 self.dispatch.close()872873 def __enter__(self) -> "Client":874 return self875876 def __exit__(877 self,878 exc_type: typing.Type[BaseException] = None,879 exc_value: BaseException = None,880 traceback: TracebackType = None,881 ) -> None:882 self.close()883884885class AsyncClient(BaseClient):886 """887 An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,888 cookie persistence, etc.889890 Usage:891892 ```python893 >>> async with httpx.AsyncClient() as client:894 >>> response = await client.get('https://example.org')895 ```896897 **Parameters:**898899 * **auth** - *(optional)* An authentication class to use when sending900 requests.901 * **params** - *(optional)* Query parameters to include in request URLs, as902 a string, dictionary, or list of two-tuples.903 * **headers** - *(optional)* Dictionary of HTTP headers to include when904 sending requests.905 * **cookies** - *(optional)* Dictionary of Cookie items to include when906 sending requests.907 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to908 verify the identity of requested hosts. Either `True` (default CA bundle),909 a path to an SSL certificate file, or `False` (disable verification).910 * **cert** - *(optional)* An SSL certificate used by the requested host911 to authenticate the client. Either a path to an SSL certificate file, or912 two-tuple of (certificate file, key file), or a three-tuple of (certificate913 file, key file, password).914 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be915 enabled. Defaults to `False`.916 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy917 URLs.918 * **timeout** - *(optional)* The timeout configuration to use when sending919 requests.920 * **pool_limits** - *(optional)* The connection pool configuration to use921 when determining the maximum number of concurrently open HTTP connections.922 * **max_redirects** - *(optional)* The maximum number of redirect responses923 that should be followed.924 * **base_url** - *(optional)* A URL to use as the base when building925 request URLs.926 * **dispatch** - *(optional)* A dispatch class to use for sending requests927 over the network.928 * **app** - *(optional)* An ASGI application to send requests to,929 rather than sending actual network requests.930 * **backend** - *(optional)* A concurrency backend to use when issuing931 async requests. Either 'auto', 'asyncio', 'trio', or a `ConcurrencyBackend`932 instance. Defaults to 'auto', for autodetection.933 * **trust_env** - *(optional)* Enables or disables usage of environment934 variables for configuration.935 * **uds** - *(optional)* A path to a Unix domain socket to connect through.936 """937938 def __init__(939 self,940 *,941 auth: AuthTypes = None,942 params: QueryParamTypes = None,943 headers: HeaderTypes = None,944 cookies: CookieTypes = None,945 verify: VerifyTypes = True,946 cert: CertTypes = None,947 http2: bool = False,948 proxies: ProxiesTypes = None,949 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,950 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,951 max_redirects: int = DEFAULT_MAX_REDIRECTS,952 base_url: URLTypes = None,953 dispatch: AsyncDispatcher = None,954 app: typing.Callable = None,955 backend: typing.Union[str, ConcurrencyBackend] = "auto",956 trust_env: bool = True,957 uds: str = None,958 ):959 super().__init__(960 auth=auth,961 params=params,962 headers=headers,963 cookies=cookies,964 timeout=timeout,965 max_redirects=max_redirects,966 base_url=base_url,967 trust_env=trust_env,968 )969970 proxy_map = self.get_proxy_map(proxies, trust_env)971972 self.dispatch = self.init_dispatch(973 verify=verify,974 cert=cert,975 http2=http2,976 pool_limits=pool_limits,977 dispatch=dispatch,978 app=app,979 backend=backend,980 trust_env=trust_env,981 uds=uds,982 )983 self.proxies: typing.Dict[str, AsyncDispatcher] = {984 key: self.init_proxy_dispatch(985 proxy,986 verify=verify,987 cert=cert,988 http2=http2,989 pool_limits=pool_limits,990 backend=backend,991 trust_env=trust_env,992 )993 for key, proxy in proxy_map.items()994 }995996 def init_dispatch(997 self,998 verify: VerifyTypes = True,999 cert: CertTypes = None,1000 http2: bool = False,1001 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1002 dispatch: AsyncDispatcher = None,1003 app: typing.Callable = None,1004 backend: typing.Union[str, ConcurrencyBackend] = "auto",1005 trust_env: bool = True,1006 uds: str = None,1007 ) -> AsyncDispatcher:1008 if dispatch is not None:1009 return dispatch10101011 if app is not None:1012 return ASGIDispatch(app=app)10131014 return ConnectionPool(1015 verify=verify,1016 cert=cert,1017 http2=http2,1018 pool_limits=pool_limits,1019 backend=backend,1020 trust_env=trust_env,1021 uds=uds,1022 )10231024 def init_proxy_dispatch(1025 self,1026 proxy: Proxy,1027 verify: VerifyTypes = True,1028 cert: CertTypes = None,1029 http2: bool = False,1030 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1031 backend: typing.Union[str, ConcurrencyBackend] = "auto",1032 trust_env: bool = True,1033 ) -> AsyncDispatcher:1034 return HTTPProxy(1035 proxy_url=proxy.url,1036 proxy_headers=proxy.headers,1037 proxy_mode=proxy.mode,1038 verify=verify,1039 cert=cert,1040 http2=http2,1041 pool_limits=pool_limits,1042 backend=backend,1043 trust_env=trust_env,1044 )10451046 def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:1047 """1048 Returns the AsyncDispatcher instance that should be used for a given URL.1049 This will either be the standard connection pool, or a proxy.1050 """1051 if self.proxies:1052 is_default_port = (url.scheme == "http" and url.port == 80) or (1053 url.scheme == "https" and url.port == 4431054 )1055 hostname = f"{url.host}:{url.port}"1056 proxy_keys = (1057 f"{url.scheme}://{hostname}",1058 f"{url.scheme}://{url.host}" if is_default_port else None,1059 f"all://{hostname}",1060 f"all://{url.host}" if is_default_port else None,1061 url.scheme,1062 "all",1063 )1064 for proxy_key in proxy_keys:1065 if proxy_key and proxy_key in self.proxies:1066 dispatcher = self.proxies[proxy_key]1067 return dispatcher10681069 return self.dispatch10701071 async def request(1072 self,1073 method: str,1074 url: URLTypes,1075 *,1076 data: RequestData = None,1077 files: RequestFiles = None,1078 json: typing.Any = None,1079 params: QueryParamTypes = None,1080 headers: HeaderTypes = None,1081 cookies: CookieTypes = None,1082 auth: AuthTypes = None,1083 allow_redirects: bool = True,1084 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1085 ) -> Response:1086 request = self.build_request(1087 method=method,1088 url=url,1089 data=data,1090 files=files,1091 json=json,1092 params=params,1093 headers=headers,1094 cookies=cookies,1095 )1096 response = await self.send(1097 request, auth=auth, allow_redirects=allow_redirects, timeout=timeout,1098 )1099 return response11001101 async def send(1102 self,1103 request: Request,1104 *,1105 stream: bool = False,1106 auth: AuthTypes = None,1107 allow_redirects: bool = True,1108 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1109 ) -> Response:1110 if request.url.scheme not in ("http", "https"):1111 raise InvalidURL('URL scheme must be "http" or "https".')11121113 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)11141115 auth = self.build_auth(request, auth)11161117 response = await self.send_handling_redirects(1118 request, auth=auth, timeout=timeout, allow_redirects=allow_redirects,1119 )11201121 if not stream:1122 try:1123 await response.aread()1124 finally:1125 await response.aclose()11261127 return response11281129 async def send_handling_redirects(1130 self,1131 request: Request,1132 auth: Auth,1133 timeout: Timeout,1134 allow_redirects: bool = True,1135 history: typing.List[Response] = None,1136 ) -> Response:1137 if history is None:1138 history = []11391140 while True:1141 if len(history) > self.max_redirects:1142 raise TooManyRedirects()1143 urls = ((resp.request.method, resp.url) for resp in history)1144 if (request.method, request.url) in urls:1145 raise RedirectLoop()11461147 response = await self.send_handling_auth(1148 request, auth=auth, timeout=timeout, history=history1149 )1150 response.history = list(history)11511152 if not response.is_redirect:1153 return response11541155 if allow_redirects:1156 await response.aread()1157 request = self.build_redirect_request(request, response)1158 history = history + [response]11591160 if not allow_redirects:1161 response.call_next = functools.partial(1162 self.send_handling_redirects,1163 request=request,1164 auth=auth,1165 timeout=timeout,1166 allow_redirects=False,1167 history=history,1168 )1169 return response11701171 async def send_handling_auth(1172 self,1173 request: Request,1174 history: typing.List[Response],1175 auth: Auth,1176 timeout: Timeout,1177 ) -> Response:1178 if auth.requires_request_body:1179 await request.aread()11801181 auth_flow = auth.auth_flow(request)1182 request = next(auth_flow)1183 while True:1184 response = await self.send_single_request(request, timeout)1185 try:1186 next_request = auth_flow.send(response)1187 except StopIteration:1188 return response1189 except BaseException as exc:1190 await response.aclose()1191 raise exc from None1192 else:1193 response.history = list(history)1194 await response.aread()1195 request = next_request1196 history.append(response)11971198 async def send_single_request(1199 self, request: Request, timeout: Timeout,1200 ) -> Response:1201 """1202 Sends a single request, without handling any redirections.1203 """12041205 dispatcher = self.dispatcher_for_url(request.url)12061207 try:1208 response = await dispatcher.send(request, timeout=timeout)1209 except HTTPError as exc:1210 # Add the original request to any HTTPError unless1211 # there'a already a request attached in the case of1212 # a ProxyError.1213 if exc.request is None:1214 exc.request = request1215 raise12161217 self.cookies.extract_cookies(response)12181219 status = f"{response.status_code} {response.reason_phrase}"1220 response_line = f"{response.http_version} {status}"1221 logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"')12221223 return response12241225 async def get(1226 self,1227 url: URLTypes,1228 *,1229 params: QueryParamTypes = None,1230 headers: HeaderTypes = None,1231 cookies: CookieTypes = None,1232 auth: AuthTypes = None,1233 allow_redirects: bool = True,1234 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1235 ) -> Response:1236 return await self.request(1237 "GET",1238 url,1239 params=params,1240 headers=headers,1241 cookies=cookies,1242 auth=auth,1243 allow_redirects=allow_redirects,1244 timeout=timeout,1245 )12461247 async def options(1248 self,1249 url: URLTypes,1250 *,1251 params: QueryParamTypes = None,1252 headers: HeaderTypes = None,1253 cookies: CookieTypes = None,1254 auth: AuthTypes = None,1255 allow_redirects: bool = True,1256 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1257 ) -> Response:1258 return await self.request(1259 "OPTIONS",1260 url,1261 params=params,1262 headers=headers,1263 cookies=cookies,1264 auth=auth,1265 allow_redirects=allow_redirects,1266 timeout=timeout,1267 )12681269 async def head(1270 self,1271 url: URLTypes,1272 *,1273 params: QueryParamTypes = None,1274 headers: HeaderTypes = None,1275 cookies: CookieTypes = None,1276 auth: AuthTypes = None,1277 allow_redirects: bool = False, # NOTE: Differs to usual default.1278 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1279 ) -> Response:1280 return await self.request(1281 "HEAD",1282 url,1283 params=params,1284 headers=headers,1285 cookies=cookies,1286 auth=auth,1287 allow_redirects=allow_redirects,1288 timeout=timeout,1289 )12901291 async def post(1292 self,1293 url: URLTypes,1294 *,1295 data: RequestData = None,1296 files: RequestFiles = None,1297 json: typing.Any = None,1298 params: QueryParamTypes = None,1299 headers: HeaderTypes = None,1300 cookies: CookieTypes = None,1301 auth: AuthTypes = None,1302 allow_redirects: bool = True,1303 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1304 ) -> Response:1305 return await self.request(1306 "POST",1307 url,1308 data=data,1309 files=files,1310 json=json,1311 params=params,1312 headers=headers,1313 cookies=cookies,1314 auth=auth,1315 allow_redirects=allow_redirects,1316 timeout=timeout,1317 )13181319 async def put(1320 self,1321 url: URLTypes,1322 *,1323 data: RequestData = None,1324 files: RequestFiles = None,1325 json: typing.Any = None,1326 params: QueryParamTypes = None,1327 headers: HeaderTypes = None,1328 cookies: CookieTypes = None,1329 auth: AuthTypes = None,1330 allow_redirects: bool = True,1331 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1332 ) -> Response:1333 return await self.request(1334 "PUT",1335 url,1336 data=data,1337 files=files,1338 json=json,1339 params=params,1340 headers=headers,1341 cookies=cookies,1342 auth=auth,1343 allow_redirects=allow_redirects,1344 timeout=timeout,1345 )13461347 async def patch(1348 self,1349 url: URLTypes,1350 *,1351 data: RequestData = None,1352 files: RequestFiles = None,1353 json: typing.Any = None,1354 params: QueryParamTypes = None,1355 headers: HeaderTypes = None,1356 cookies: CookieTypes = None,1357 auth: AuthTypes = None,1358 allow_redirects: bool = True,1359 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1360 ) -> Response:1361 return await self.request(1362 "PATCH",1363 url,1364 data=data,1365 files=files,1366 json=json,1367 params=params,1368 headers=headers,1369 cookies=cookies,1370 auth=auth,1371 allow_redirects=allow_redirects,1372 timeout=timeout,1373 )13741375 async def delete(1376 self,1377 url: URLTypes,1378 *,1379 params: QueryParamTypes = None,1380 headers: HeaderTypes = None,1381 cookies: CookieTypes = None,1382 auth: AuthTypes = None,1383 allow_redirects: bool = True,1384 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1385 ) -> Response:1386 return await self.request(1387 "DELETE",1388 url,1389 params=params,1390 headers=headers,1391 cookies=cookies,1392 auth=auth,1393 allow_redirects=allow_redirects,1394 timeout=timeout,1395 )13961397 async def aclose(self) -> None:1398 await self.dispatch.close()13991400 async def __aenter__(self) -> "AsyncClient":1401 return self14021403 async def __aexit__(1404 self,1405 exc_type: typing.Type[BaseException] = None,1406 exc_value: BaseException = None,1407 traceback: TracebackType = None,1408 ) -> None:1409 await self.aclose()141014111412class StreamContextManager:1413 def __init__(1414 self,1415 client: BaseClient,1416 request: Request,1417 *,1418 auth: AuthTypes = None,1419 allow_redirects: bool = True,1420 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1421 close_client: bool = False,1422 ) -> None:1423 self.client = client1424 self.request = request1425 self.auth = auth1426 self.allow_redirects = allow_redirects1427 self.timeout = timeout1428 self.close_client = close_client14291430 def __enter__(self) -> "Response":1431 assert isinstance(self.client, Client)1432 self.response = self.client.send(1433 request=self.request,1434 auth=self.auth,1435 allow_redirects=self.allow_redirects,1436 timeout=self.timeout,1437 stream=True,1438 )1439 return self.response14401441 def __exit__(1442 self,1443 exc_type: typing.Type[BaseException] = None,1444 exc_value: BaseException = None,1445 traceback: TracebackType = None,1446 ) -> None:1447 assert isinstance(self.client, Client)1448 self.response.close()1449 if self.close_client:1450 self.client.close()14511452 async def __aenter__(self) -> "Response":1453 assert isinstance(self.client, AsyncClient)1454 self.response = await self.client.send(1455 request=self.request,1456 auth=self.auth,1457 allow_redirects=self.allow_redirects,1458 timeout=self.timeout,1459 stream=True,1460 )1461 return self.response14621463 async def __aexit__(1464 self,1465 exc_type: typing.Type[BaseException] = None,1466 exc_value: BaseException = None,1467 traceback: TracebackType = None,1468 ) -> None:1469 assert isinstance(self.client, AsyncClient)1470 await self.response.aclose()1471 if self.close_client:1472 await self.client.aclose()
deleted:httpx/config.py-357 removed
1import os2import ssl3import typing4from base64 import b64encode5from pathlib import Path67import certifi89from .models import URL, Headers, HeaderTypes, URLTypes10from .utils import get_ca_bundle_from_env, get_logger1112CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]13VerifyTypes = typing.Union[str, bool, ssl.SSLContext]14TimeoutTypes = typing.Union[15 None, float, typing.Tuple[float, float, float, float], "Timeout"16]17ProxiesTypes = typing.Union[18 URLTypes, "Proxy", typing.Dict[URLTypes, typing.Union[URLTypes, "Proxy"]]19]202122DEFAULT_CIPHERS = ":".join(23 [24 "ECDHE+AESGCM",25 "ECDHE+CHACHA20",26 "DHE+AESGCM",27 "DHE+CHACHA20",28 "ECDH+AESGCM",29 "DH+AESGCM",30 "ECDH+AES",31 "DH+AES",32 "RSA+AESGCM",33 "RSA+AES",34 "!aNULL",35 "!eNULL",36 "!MD5",37 "!DSS",38 ]39)404142logger = get_logger(__name__)434445class UnsetType:46 pass # pragma: nocover474849UNSET = UnsetType()505152class SSLConfig:53 """54 SSL Configuration.55 """5657 DEFAULT_CA_BUNDLE_PATH = Path(certifi.where())5859 def __init__(60 self,61 *,62 cert: CertTypes = None,63 verify: VerifyTypes = True,64 trust_env: bool = None,65 http2: bool = False,66 ):67 self.cert = cert68 self.verify = verify69 self.trust_env = trust_env70 self.http2 = http271 self.ssl_context = self.load_ssl_context()7273 def __eq__(self, other: typing.Any) -> bool:74 return (75 isinstance(other, self.__class__)76 and self.cert == other.cert77 and self.verify == other.verify78 )7980 def __repr__(self) -> str:81 class_name = self.__class__.__name__82 return f"{class_name}(cert={self.cert}, verify={self.verify})"8384 def load_ssl_context(self) -> ssl.SSLContext:85 logger.trace(86 f"load_ssl_context "87 f"verify={self.verify!r} "88 f"cert={self.cert!r} "89 f"trust_env={self.trust_env!r} "90 f"http2={self.http2!r}"91 )9293 if self.verify:94 return self.load_ssl_context_verify()95 return self.load_ssl_context_no_verify()9697 def load_ssl_context_no_verify(self) -> ssl.SSLContext:98 """99 Return an SSL context for unverified connections.100 """101 context = self._create_default_ssl_context()102 context.verify_mode = ssl.CERT_NONE103 context.check_hostname = False104 return context105106 def load_ssl_context_verify(self) -> ssl.SSLContext:107 """108 Return an SSL context for verified connections.109 """110 if self.trust_env and self.verify is True:111 ca_bundle = get_ca_bundle_from_env()112 if ca_bundle is not None:113 self.verify = ca_bundle # type: ignore114115 if isinstance(self.verify, ssl.SSLContext):116 # Allow passing in our own SSLContext object that's pre-configured.117 context = self.verify118 self._load_client_certs(context)119 return context120 elif isinstance(self.verify, bool):121 ca_bundle_path = self.DEFAULT_CA_BUNDLE_PATH122 elif Path(self.verify).exists():123 ca_bundle_path = Path(self.verify)124 else:125 raise IOError(126 "Could not find a suitable TLS CA certificate bundle, "127 "invalid path: {}".format(self.verify)128 )129130 context = self._create_default_ssl_context()131 context.verify_mode = ssl.CERT_REQUIRED132 context.check_hostname = True133134 # Signal to server support for PHA in TLS 1.3. Raises an135 # AttributeError if only read-only access is implemented.136 try:137 context.post_handshake_auth = True # type: ignore138 except AttributeError: # pragma: nocover139 pass140141 # Disable using 'commonName' for SSLContext.check_hostname142 # when the 'subjectAltName' extension isn't available.143 try:144 context.hostname_checks_common_name = False # type: ignore145 except AttributeError: # pragma: nocover146 pass147148 if ca_bundle_path.is_file():149 logger.trace(f"load_verify_locations cafile={ca_bundle_path!s}")150 context.load_verify_locations(cafile=str(ca_bundle_path))151 elif ca_bundle_path.is_dir():152 logger.trace(f"load_verify_locations capath={ca_bundle_path!s}")153 context.load_verify_locations(capath=str(ca_bundle_path))154155 self._load_client_certs(context)156157 return context158159 def _create_default_ssl_context(self) -> ssl.SSLContext:160 """161 Creates the default SSLContext object that's used for both verified162 and unverified connections.163 """164 context = ssl.SSLContext(ssl.PROTOCOL_TLS)165 context.options |= ssl.OP_NO_SSLv2166 context.options |= ssl.OP_NO_SSLv3167 context.options |= ssl.OP_NO_TLSv1168 context.options |= ssl.OP_NO_TLSv1_1169 context.options |= ssl.OP_NO_COMPRESSION170 context.set_ciphers(DEFAULT_CIPHERS)171172 if ssl.HAS_ALPN:173 alpn_idents = ["http/1.1", "h2"] if self.http2 else ["http/1.1"]174 context.set_alpn_protocols(alpn_idents)175176 if hasattr(context, "keylog_filename"): # pragma: nocover (Available in 3.8+)177 keylogfile = os.environ.get("SSLKEYLOGFILE")178 if keylogfile and self.trust_env:179 context.keylog_filename = keylogfile # type: ignore180181 return context182183 def _load_client_certs(self, ssl_context: ssl.SSLContext) -> None:184 """185 Loads client certificates into our SSLContext object186 """187 if self.cert is not None:188 if isinstance(self.cert, str):189 ssl_context.load_cert_chain(certfile=self.cert)190 elif isinstance(self.cert, tuple) and len(self.cert) == 2:191 ssl_context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])192 elif isinstance(self.cert, tuple) and len(self.cert) == 3:193 ssl_context.load_cert_chain(194 certfile=self.cert[0],195 keyfile=self.cert[1],196 password=self.cert[2], # type: ignore197 )198199200class Timeout:201 """202 Timeout configuration.203204 **Usage**:205206 Timeout() # No timeout.207 Timeout(5.0) # 5s timeout on all operations.208 Timeout(connect_timeout=5.0) # 5s timeout on connect, no other timeouts.209 Timeout(5.0, connect_timeout=10.0) # 10s timeout on connect. 5s timeout elsewhere.210 Timeout(5.0, pool_timeout=None) # No timeout on acquiring connection from pool.211 # 5s timeout elsewhere.212 """213214 def __init__(215 self,216 timeout: TimeoutTypes = None,217 *,218 connect_timeout: typing.Union[None, float, UnsetType] = UNSET,219 read_timeout: typing.Union[None, float, UnsetType] = UNSET,220 write_timeout: typing.Union[None, float, UnsetType] = UNSET,221 pool_timeout: typing.Union[None, float, UnsetType] = UNSET,222 ):223 if isinstance(timeout, Timeout):224 # Passed as a single explicit Timeout.225 assert connect_timeout is UNSET226 assert read_timeout is UNSET227 assert write_timeout is UNSET228 assert pool_timeout is UNSET229 self.connect_timeout = (230 timeout.connect_timeout231 ) # type: typing.Optional[float]232 self.read_timeout = timeout.read_timeout # type: typing.Optional[float]233 self.write_timeout = timeout.write_timeout # type: typing.Optional[float]234 self.pool_timeout = timeout.pool_timeout # type: typing.Optional[float]235 elif isinstance(timeout, tuple):236 # Passed as a tuple.237 self.connect_timeout = timeout[0]238 self.read_timeout = timeout[1]239 self.write_timeout = None if len(timeout) < 3 else timeout[2]240 self.pool_timeout = None if len(timeout) < 4 else timeout[3]241 else:242 self.connect_timeout = (243 timeout if isinstance(connect_timeout, UnsetType) else connect_timeout244 )245 self.read_timeout = (246 timeout if isinstance(read_timeout, UnsetType) else read_timeout247 )248 self.write_timeout = (249 timeout if isinstance(write_timeout, UnsetType) else write_timeout250 )251 self.pool_timeout = (252 timeout if isinstance(pool_timeout, UnsetType) else pool_timeout253 )254255 def __eq__(self, other: typing.Any) -> bool:256 return (257 isinstance(other, self.__class__)258 and self.connect_timeout == other.connect_timeout259 and self.read_timeout == other.read_timeout260 and self.write_timeout == other.write_timeout261 and self.pool_timeout == other.pool_timeout262 )263264 def __repr__(self) -> str:265 class_name = self.__class__.__name__266 if (267 len(268 {269 self.connect_timeout,270 self.read_timeout,271 self.write_timeout,272 self.pool_timeout,273 }274 )275 == 1276 ):277 return f"{class_name}(timeout={self.connect_timeout})"278 return (279 f"{class_name}(connect_timeout={self.connect_timeout}, "280 f"read_timeout={self.read_timeout}, write_timeout={self.write_timeout}, "281 f"pool_timeout={self.pool_timeout})"282 )283284285class PoolLimits:286 """287 Limits on the number of connections in a connection pool.288289 **Parameters:**290291 * **soft_limit** - Allow the connection pool to maintain keep-alive connections292 below this point.293 * **hard_limit** - The maximum number of concurrenct connections that may be294 established.295 """296297 def __init__(298 self, *, soft_limit: int = None, hard_limit: int = None,299 ):300 self.soft_limit = soft_limit301 self.hard_limit = hard_limit302303 def __eq__(self, other: typing.Any) -> bool:304 return (305 isinstance(other, self.__class__)306 and self.soft_limit == other.soft_limit307 and self.hard_limit == other.hard_limit308 )309310 def __repr__(self) -> str:311 class_name = self.__class__.__name__312 return (313 f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"314 )315316317class Proxy:318 def __init__(319 self, url: URLTypes, *, headers: HeaderTypes = None, mode: str = "DEFAULT",320 ):321 url = URL(url)322 headers = Headers(headers)323324 if url.scheme not in ("http", "https"):325 raise ValueError(f"Unknown scheme for proxy URL {url!r}")326 if mode not in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY"):327 raise ValueError(f"Unknown proxy mode {mode!r}")328329 if url.username or url.password:330 headers.setdefault(331 "Proxy-Authorization",332 self.build_auth_header(url.username, url.password),333 )334 # Remove userinfo from the URL authority, e.g.:335 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'336 url = url.copy_with(username=None, password=None)337338 self.url = url339 self.headers = headers340 self.mode = mode341342 def build_auth_header(self, username: str, password: str) -> str:343 userpass = (username.encode("utf-8"), password.encode("utf-8"))344 token = b64encode(b":".join(userpass)).decode().strip()345 return f"Basic {token}"346347 def __repr__(self) -> str:348 return (349 f"Proxy(url={str(self.url)!r}, "350 f"headers={dict(self.headers)!r}, "351 f"mode={self.mode!r})"352 )353354355DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)356DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)357DEFAULT_MAX_REDIRECTS = 20
deleted:httpx/content_streams.py-346 removed
1import binascii2import mimetypes3import os4import typing5from io import BytesIO6from json import dumps as json_dumps7from pathlib import Path8from urllib.parse import urlencode910from .exceptions import StreamConsumed11from .utils import format_form_param1213RequestData = typing.Union[14 dict, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]15]1617RequestFiles = typing.Dict[18 str,19 typing.Union[20 # file (or str)21 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],22 # (filename, file (or str))23 typing.Tuple[24 typing.Optional[str], typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],25 ],26 # (filename, file (or str), content_type)27 typing.Tuple[28 typing.Optional[str],29 typing.Union[typing.IO[typing.AnyStr], typing.AnyStr],30 typing.Optional[str],31 ],32 ],33]343536class ContentStream:37 def get_headers(self) -> typing.Dict[str, str]:38 """39 Return a dictionary of headers that are implied by the encoding.40 """41 return {}4243 def can_replay(self) -> bool:44 """45 Return `True` if `__aiter__` can be called multiple times.4647 We need this in cases such determining if we can re-issue a request48 body when we receive a redirect response.49 """50 return True5152 def __iter__(self) -> typing.Iterator[bytes]:53 yield b""5455 def close(self) -> None:56 pass5758 async def __aiter__(self) -> typing.AsyncIterator[bytes]:59 yield b""6061 async def aclose(self) -> None:62 pass636465class ByteStream(ContentStream):66 """67 Request content encoded as plain bytes.68 """6970 def __init__(self, body: typing.Union[str, bytes]) -> None:71 self.body = body.encode("utf-8") if isinstance(body, str) else body7273 def get_headers(self) -> typing.Dict[str, str]:74 if not self.body:75 return {}76 content_length = str(len(self.body))77 return {"Content-Length": content_length}7879 def __iter__(self) -> typing.Iterator[bytes]:80 yield self.body8182 async def __aiter__(self) -> typing.AsyncIterator[bytes]:83 yield self.body848586class IteratorStream(ContentStream):87 """88 Request content encoded as plain bytes, using an byte iterator.89 """9091 def __init__(92 self, iterator: typing.Iterator[bytes], close_func: typing.Callable = None93 ) -> None:94 self.iterator = iterator95 self.close_func = close_func96 self.is_stream_consumed = False9798 def can_replay(self) -> bool:99 return False100101 def get_headers(self) -> typing.Dict[str, str]:102 return {"Transfer-Encoding": "chunked"}103104 def __iter__(self) -> typing.Iterator[bytes]:105 if self.is_stream_consumed:106 raise StreamConsumed()107 self.is_stream_consumed = True108 for part in self.iterator:109 yield part110111 def __aiter__(self) -> typing.AsyncIterator[bytes]:112 raise RuntimeError("Attempted to call a async iterator on an sync stream.")113114 def close(self) -> None:115 if self.close_func is not None:116 self.close_func()117118119class AsyncIteratorStream(ContentStream):120 """121 Request content encoded as plain bytes, using an async byte iterator.122 """123124 def __init__(125 self, aiterator: typing.AsyncIterator[bytes], close_func: typing.Callable = None126 ) -> None:127 self.aiterator = aiterator128 self.close_func = close_func129 self.is_stream_consumed = False130131 def can_replay(self) -> bool:132 return False133134 def get_headers(self) -> typing.Dict[str, str]:135 return {"Transfer-Encoding": "chunked"}136137 def __iter__(self) -> typing.Iterator[bytes]:138 raise RuntimeError("Attempted to call a sync iterator on an async stream.")139140 async def __aiter__(self) -> typing.AsyncIterator[bytes]:141 if self.is_stream_consumed:142 raise StreamConsumed()143 self.is_stream_consumed = True144 async for part in self.aiterator:145 yield part146147 async def aclose(self) -> None:148 if self.close_func is not None:149 await self.close_func()150151152class JSONStream(ContentStream):153 """154 Request content encoded as JSON.155 """156157 def __init__(self, json: typing.Any) -> None:158 self.body = json_dumps(json).encode("utf-8")159160 def get_headers(self) -> typing.Dict[str, str]:161 content_length = str(len(self.body))162 content_type = "application/json"163 return {"Content-Length": content_length, "Content-Type": content_type}164165 def __iter__(self) -> typing.Iterator[bytes]:166 yield self.body167168 async def __aiter__(self) -> typing.AsyncIterator[bytes]:169 yield self.body170171172class URLEncodedStream(ContentStream):173 """174 Request content as URL encoded form data.175 """176177 def __init__(self, data: dict) -> None:178 self.body = urlencode(data, doseq=True).encode("utf-8")179180 def get_headers(self) -> typing.Dict[str, str]:181 content_length = str(len(self.body))182 content_type = "application/x-www-form-urlencoded"183 return {"Content-Length": content_length, "Content-Type": content_type}184185 def __iter__(self) -> typing.Iterator[bytes]:186 yield self.body187188 async def __aiter__(self) -> typing.AsyncIterator[bytes]:189 yield self.body190191192class MultipartStream(ContentStream):193 """194 Request content as multipart encoded form data.195 """196197 class DataField:198 """199 A single form field item, within a multipart form field.200 """201202 def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:203 if not isinstance(name, str):204 raise TypeError("Invalid type for name. Expected str.")205 if not isinstance(value, (str, bytes)):206 raise TypeError("Invalid type for value. Expected str or bytes.")207 self.name = name208 self.value = value209210 def render_headers(self) -> bytes:211 name = format_form_param("name", self.name)212 return b"".join([b"Content-Disposition: form-data; ", name, b"\r\n\r\n"])213214 def render_data(self) -> bytes:215 return (216 self.value217 if isinstance(self.value, bytes)218 else self.value.encode("utf-8")219 )220221 class FileField:222 """223 A single file field item, within a multipart form field.224 """225226 def __init__(227 self, name: str, value: typing.Union[typing.IO[typing.AnyStr], tuple]228 ) -> None:229 self.name = name230 if not isinstance(value, tuple):231 self.filename = Path(str(getattr(value, "name", "upload"))).name232 self.file = (233 value234 ) # type: typing.Union[typing.IO[str], typing.IO[bytes]]235 self.content_type = self.guess_content_type()236 else:237 self.filename = value[0]238 self.file = value[1]239 self.content_type = (240 value[2] if len(value) > 2 else self.guess_content_type()241 )242243 def guess_content_type(self) -> typing.Optional[str]:244 if self.filename:245 return (246 mimetypes.guess_type(self.filename)[0] or "application/octet-stream"247 )248 else:249 return None250251 def render_headers(self) -> bytes:252 parts = [253 b"Content-Disposition: form-data; ",254 format_form_param("name", self.name),255 ]256 if self.filename:257 filename = format_form_param("filename", self.filename)258 parts.extend([b"; ", filename])259 if self.content_type is not None:260 content_type = self.content_type.encode()261 parts.extend([b"\r\nContent-Type: ", content_type])262 parts.append(b"\r\n\r\n")263 return b"".join(parts)264265 def render_data(self) -> bytes:266 if isinstance(self.file, str):267 content = self.file268 else:269 content = self.file.read()270 return content.encode("utf-8") if isinstance(content, str) else content271272 def __init__(self, data: dict, files: dict, boundary: bytes = None) -> None:273 body = BytesIO()274 if boundary is None:275 boundary = binascii.hexlify(os.urandom(16))276277 for field in self.iter_fields(data, files):278 body.write(b"--%s\r\n" % boundary)279 body.write(field.render_headers())280 body.write(field.render_data())281 body.write(b"\r\n")282283 body.write(b"--%s--\r\n" % boundary)284285 self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(286 "ascii"287 )288 self.body = body.getvalue()289290 def iter_fields(291 self, data: dict, files: dict292 ) -> typing.Iterator[typing.Union["FileField", "DataField"]]:293 for name, value in data.items():294 if isinstance(value, (list, dict)):295 for item in value:296 yield self.DataField(name=name, value=item)297 else:298 yield self.DataField(name=name, value=value)299300 for name, value in files.items():301 yield self.FileField(name=name, value=value)302303 def get_headers(self) -> typing.Dict[str, str]:304 content_length = str(len(self.body))305 content_type = self.content_type306 return {"Content-Length": content_length, "Content-Type": content_type}307308 def __iter__(self) -> typing.Iterator[bytes]:309 yield self.body310311 async def __aiter__(self) -> typing.AsyncIterator[bytes]:312 yield self.body313314315def encode(316 data: RequestData = None,317 files: RequestFiles = None,318 json: typing.Any = None,319 boundary: bytes = None,320) -> ContentStream:321 """322 Handles encoding the given `data`, `files`, and `json`, returning323 a `ContentStream` implementation.324 """325 if data is None:326 if json is not None:327 return JSONStream(json=json)328 elif files:329 return MultipartStream(data={}, files=files, boundary=boundary)330 else:331 return ByteStream(body=b"")332 elif isinstance(data, dict):333 if files is not None:334 return MultipartStream(data=data, files=files, boundary=boundary)335 else:336 return URLEncodedStream(data=data)337 elif isinstance(data, (str, bytes)):338 return ByteStream(body=data)339 elif hasattr(data, "__aiter__"):340 data = typing.cast(typing.AsyncIterator[bytes], data)341 return AsyncIteratorStream(aiterator=data)342 elif hasattr(data, "__iter__"):343 data = typing.cast(typing.Iterator[bytes], data)344 return IteratorStream(iterator=data)345346 raise TypeError(f"Unexpected type for 'data', {type(data)!r}")
deleted:httpx/decoders.py-290 removed
1"""2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import codecs7import typing8import zlib910import chardet1112from .exceptions import DecodingError1314try:15 import brotli16except ImportError: # pragma: nocover17 brotli = None181920class Decoder:21 def decode(self, data: bytes) -> bytes:22 raise NotImplementedError() # pragma: nocover2324 def flush(self) -> bytes:25 raise NotImplementedError() # pragma: nocover262728class IdentityDecoder(Decoder):29 """30 Handle unencoded data.31 """3233 def decode(self, data: bytes) -> bytes:34 return data3536 def flush(self) -> bytes:37 return b""383940class DeflateDecoder(Decoder):41 """42 Handle 'deflate' decoding.4344 See: https://stackoverflow.com/questions/183869945 """4647 def __init__(self) -> None:48 self.first_attempt = True49 self.decompressor = zlib.decompressobj()5051 def decode(self, data: bytes) -> bytes:52 was_first_attempt = self.first_attempt53 self.first_attempt = False54 try:55 return self.decompressor.decompress(data)56 except zlib.error as exc:57 if was_first_attempt:58 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)59 return self.decode(data)60 raise DecodingError from exc6162 def flush(self) -> bytes:63 try:64 return self.decompressor.flush()65 except zlib.error as exc: # pragma: nocover66 raise DecodingError from exc676869class GZipDecoder(Decoder):70 """71 Handle 'gzip' decoding.7273 See: https://stackoverflow.com/questions/183869974 """7576 def __init__(self) -> None:77 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)7879 def decode(self, data: bytes) -> bytes:80 try:81 return self.decompressor.decompress(data)82 except zlib.error as exc:83 raise DecodingError from exc8485 def flush(self) -> bytes:86 try:87 return self.decompressor.flush()88 except zlib.error as exc: # pragma: nocover89 raise DecodingError from exc909192class BrotliDecoder(Decoder):93 """94 Handle 'brotli' decoding.9596 Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/97 or `pip install brotli`. See https://github.com/google/brotli98 Supports both 'brotlipy' and 'Brotli' packages since they share an import99 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'100 """101102 def __init__(self) -> None:103 assert (104 brotli is not None105 ), "The 'brotlipy' or 'brotli' library must be installed to use 'BrotliDecoder'"106 self.decompressor = brotli.Decompressor()107 self.seen_data = False108109 def decode(self, data: bytes) -> bytes:110 if not data:111 return b""112 self.seen_data = True113 try:114 if hasattr(self.decompressor, "decompress"):115 return self.decompressor.decompress(data)116 return self.decompressor.process(data) # pragma: nocover117 except brotli.error as exc:118 raise DecodingError from exc119120 def flush(self) -> bytes:121 if not self.seen_data:122 return b""123 try:124 if hasattr(self.decompressor, "finish"):125 self.decompressor.finish()126 return b""127 except brotli.error as exc: # pragma: nocover128 raise DecodingError from exc129130131class MultiDecoder(Decoder):132 """133 Handle the case where multiple encodings have been applied.134 """135136 def __init__(self, children: typing.Sequence[Decoder]) -> None:137 """138 'children' should be a sequence of decoders in the order in which139 each was applied.140 """141 # Note that we reverse the order for decoding.142 self.children = list(reversed(children))143144 def decode(self, data: bytes) -> bytes:145 for child in self.children:146 data = child.decode(data)147 return data148149 def flush(self) -> bytes:150 data = b""151 for child in self.children:152 data = child.decode(data) + child.flush()153 return data154155156class TextDecoder:157 """158 Handles incrementally decoding bytes into text159 """160161 def __init__(self, encoding: typing.Optional[str] = None):162 self.decoder: typing.Optional[codecs.IncrementalDecoder] = (163 None if encoding is None else codecs.getincrementaldecoder(encoding)()164 )165 self.detector = chardet.universaldetector.UniversalDetector()166167 # This buffer is only needed if 'decoder' is 'None'168 # we want to trigger errors if data is getting added to169 # our internal buffer for some silly reason while170 # a decoder is discovered.171 self.buffer: typing.Optional[bytearray] = None if self.decoder else bytearray()172173 def decode(self, data: bytes) -> str:174 try:175 if self.decoder is not None:176 text = self.decoder.decode(data)177 else:178 assert self.buffer is not None179 text = ""180 self.detector.feed(data)181 self.buffer += data182183 # Should be more than enough data to process, we don't184 # want to buffer too long as chardet will wait until185 # detector.close() is used to give back common186 # encodings like 'utf-8'.187 if len(self.buffer) >= 4096:188 self.decoder = codecs.getincrementaldecoder(189 self._detector_result()190 )()191 text = self.decoder.decode(bytes(self.buffer), False)192 self.buffer = None193194 return text195 except UnicodeDecodeError: # pragma: nocover196 raise DecodingError() from None197198 def flush(self) -> str:199 try:200 if self.decoder is None:201 # Empty string case as chardet is guaranteed to not have a guess.202 assert self.buffer is not None203 if len(self.buffer) == 0:204 return ""205 return bytes(self.buffer).decode(self._detector_result())206207 return self.decoder.decode(b"", True)208 except UnicodeDecodeError: # pragma: nocover209 raise DecodingError() from None210211 def _detector_result(self) -> str:212 self.detector.close()213 result = self.detector.result["encoding"]214 if not result: # pragma: nocover215 raise DecodingError("Unable to determine encoding of content")216217 return result218219220class LineDecoder:221 """222 Handles incrementally reading lines from text.223224 Uses universal line decoding, supporting any of `\n`, `\r`, or `\r\n`225 as line endings, normalizing to `\n`.226 """227228 def __init__(self) -> None:229 self.buffer = ""230231 def decode(self, text: str) -> typing.List[str]:232 lines = []233234 if text.startswith("\n") and self.buffer and self.buffer[-1] == "\r":235 # Handle the case where we have an "\r\n" split across236 # our previous input, and our new chunk.237 lines.append(self.buffer[:-1] + "\n")238 self.buffer = ""239 text = text[1:]240241 while text:242 num_chars = len(text)243 for idx in range(num_chars):244 char = text[idx]245 next_char = None if idx + 1 == num_chars else text[idx + 1]246 if char == "\n":247 lines.append(self.buffer + text[: idx + 1])248 self.buffer = ""249 text = text[idx + 1 :]250 break251 elif char == "\r" and next_char == "\n":252 lines.append(self.buffer + text[:idx] + "\n")253 self.buffer = ""254 text = text[idx + 2 :]255 break256 elif char == "\r" and next_char is not None:257 lines.append(self.buffer + text[:idx] + "\n")258 self.buffer = ""259 text = text[idx + 1 :]260 break261 elif next_char is None:262 self.buffer = text263 text = ""264 break265266 return lines267268 def flush(self) -> typing.List[str]:269 if self.buffer.endswith("\r"):270 # Handle the case where we had a trailing '\r', which could have271 # been a '\r\n' pair.272 lines = [self.buffer[:-1] + "\n"]273 elif self.buffer:274 lines = [self.buffer]275 else:276 lines = []277 self.buffer = ""278 return lines279280281SUPPORTED_DECODERS = {282 "identity": IdentityDecoder,283 "gzip": GZipDecoder,284 "deflate": DeflateDecoder,285 "br": BrotliDecoder,286}287288289if brotli is None:290 SUPPORTED_DECODERS.pop("br") # pragma: nocover
deleted:httpx/exceptions.py-174 removed
1import typing23if typing.TYPE_CHECKING:4 from .models import Request, Response # pragma: nocover567class HTTPError(Exception):8 """9 Base class for all httpx exceptions.10 """1112 def __init__(13 self, *args: typing.Any, request: "Request" = None, response: "Response" = None14 ) -> None:15 self.response = response16 self.request = request or getattr(self.response, "request", None)17 super().__init__(*args)181920# Timeout exceptions...212223class TimeoutException(HTTPError):24 """25 A base class for all timeouts.26 """272829class ConnectTimeout(TimeoutException):30 """31 Timeout while establishing a connection.32 """333435class ReadTimeout(TimeoutException):36 """37 Timeout while reading response data.38 """394041class WriteTimeout(TimeoutException):42 """43 Timeout while writing request data.44 """454647class PoolTimeout(TimeoutException):48 """49 Timeout while waiting to acquire a connection from the pool.50 """515253class ProxyError(HTTPError):54 """55 Error from within a proxy56 """575859# HTTP exceptions...606162class ProtocolError(HTTPError):63 """64 Malformed HTTP.65 """666768class DecodingError(HTTPError):69 """70 Decoding of the response failed.71 """727374# Network exceptions...757677class NetworkError(HTTPError):78 """79 A failure occurred while trying to access the network.80 """818283class ConnectionClosed(NetworkError):84 """85 Expected more data from peer, but connection was closed.86 """878889# Redirect exceptions...909192class RedirectError(HTTPError):93 """94 Base class for HTTP redirect errors.95 """969798class TooManyRedirects(RedirectError):99 """100 Too many redirects.101 """102103104class RedirectLoop(RedirectError):105 """106 Infinite redirect loop.107 """108109110class NotRedirectResponse(RedirectError):111 """112 Response was not a redirect response.113 """114115116# Stream exceptions...117118119class StreamError(HTTPError):120 """121 The base class for stream exceptions.122123 The developer made an error in accessing the request stream in124 an invalid way.125 """126127128class RequestBodyUnavailable(StreamError):129 """130 Had to send the request again, but the request body was streaming, and is131 no longer available.132 """133134135class StreamConsumed(StreamError):136 """137 Attempted to read or stream response content, but the content has already138 been streamed.139 """140141142class ResponseNotRead(StreamError):143 """144 Attempted to access response content, without having called `read()`145 after a streaming response.146 """147148149class RequestNotRead(StreamError):150 """151 Attempted to access request content, without having called `read()`.152 """153154155class ResponseClosed(StreamError):156 """157 Attempted to read or stream response content, but the request has been158 closed.159 """160161162# Other cases...163164165class InvalidURL(HTTPError):166 """167 URL was missing a hostname, or was not one of HTTP/HTTPS.168 """169170171class CookieConflict(HTTPError):172 """173 Attempted to lookup a cookie by name, but multiple cookies existed.174 """
deleted:httpx/models.py-1207 removed
1import cgi2import datetime3import email.message4import json as jsonlib5import typing6import urllib.request7import warnings8from collections.abc import MutableMapping9from http.cookiejar import Cookie, CookieJar10from urllib.parse import parse_qsl, urlencode1112import chardet13import rfc39861415from .__version__ import __version__16from .content_streams import (17 ByteStream,18 ContentStream,19 RequestData,20 RequestFiles,21 encode,22)23from .decoders import (24 SUPPORTED_DECODERS,25 Decoder,26 IdentityDecoder,27 LineDecoder,28 MultiDecoder,29 TextDecoder,30)31from .exceptions import (32 CookieConflict,33 HTTPError,34 InvalidURL,35 NotRedirectResponse,36 RequestNotRead,37 ResponseClosed,38 ResponseNotRead,39 StreamConsumed,40)41from .status_codes import StatusCode42from .utils import (43 ElapsedTimer,44 flatten_queryparams,45 guess_json_utf,46 is_known_encoding,47 normalize_header_key,48 normalize_header_value,49 obfuscate_sensitive_headers,50 parse_header_links,51 str_query_param,52)5354if typing.TYPE_CHECKING: # pragma: no cover55 from .dispatch.base import AsyncDispatcher # noqa: F4015657PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]5859URLTypes = typing.Union["URL", str]6061QueryParamTypes = typing.Union[62 "QueryParams",63 typing.Mapping[str, typing.Union[PrimitiveData, typing.Sequence[PrimitiveData]]],64 typing.List[typing.Tuple[str, PrimitiveData]],65 str,66]6768HeaderTypes = typing.Union[69 "Headers",70 typing.Dict[typing.AnyStr, typing.AnyStr],71 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],72]7374CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]757677class URL:78 def __init__(79 self,80 url: URLTypes,81 allow_relative: bool = False,82 params: QueryParamTypes = None,83 ) -> None:84 if isinstance(url, str):85 self._uri_reference = rfc3986.api.iri_reference(url).encode()86 else:87 self._uri_reference = url._uri_reference8889 # Normalize scheme and domain name.90 if self.is_absolute_url:91 self._uri_reference = self._uri_reference.normalize()9293 # Add any query parameters, merging with any in the URL if needed.94 if params:95 if self._uri_reference.query:96 url_params = QueryParams(self._uri_reference.query)97 url_params.update(params)98 query_string = str(url_params)99 else:100 query_string = str(QueryParams(params))101 self._uri_reference = self._uri_reference.copy_with(query=query_string)102103 # Enforce absolute URLs by default.104 if not allow_relative:105 if not self.scheme:106 raise InvalidURL("No scheme included in URL.")107 if not self.host:108 raise InvalidURL("No host included in URL.")109110 # Allow setting full_path to custom attributes requests111 # like OPTIONS, CONNECT, and forwarding proxy requests.112 self._full_path: typing.Optional[str] = None113114 @property115 def scheme(self) -> str:116 return self._uri_reference.scheme or ""117118 @property119 def authority(self) -> str:120 port_str = self._uri_reference.port121 default_port_str = {"https": "443", "http": "80"}.get(self.scheme, "")122 if port_str is None or port_str == default_port_str:123 return self._uri_reference.host or ""124 return self._uri_reference.authority or ""125126 @property127 def userinfo(self) -> str:128 return self._uri_reference.userinfo or ""129130 @property131 def username(self) -> str:132 userinfo = self._uri_reference.userinfo or ""133 return userinfo.partition(":")[0]134135 @property136 def password(self) -> str:137 userinfo = self._uri_reference.userinfo or ""138 return userinfo.partition(":")[2]139140 @property141 def host(self) -> str:142 return self._uri_reference.host or ""143144 @property145 def port(self) -> int:146 port = self._uri_reference.port147 if port is None:148 return {"https": 443, "http": 80}[self.scheme]149 return int(port)150151 @property152 def path(self) -> str:153 return self._uri_reference.path or "/"154155 @property156 def query(self) -> str:157 return self._uri_reference.query or ""158159 @property160 def full_path(self) -> str:161 if self._full_path is not None:162 return self._full_path163 path = self.path164 if self.query:165 path += "?" + self.query166 return path167168 @full_path.setter169 def full_path(self, value: typing.Optional[str]) -> None:170 self._full_path = value171172 @property173 def fragment(self) -> str:174 return self._uri_reference.fragment or ""175176 @property177 def is_ssl(self) -> bool:178 return self.scheme == "https"179180 @property181 def is_absolute_url(self) -> bool:182 """183 Return `True` for absolute URLs such as 'http://example.com/path',184 and `False` for relative URLs such as '/path'.185 """186 # We don't use `.is_absolute` from `rfc3986` because it treats187 # URLs with a fragment portion as not absolute.188 # What we actually care about is if the URL provides189 # a scheme and hostname to which connections should be made.190 return bool(self.scheme and self.host)191192 @property193 def is_relative_url(self) -> bool:194 return not self.is_absolute_url195196 def copy_with(self, **kwargs: typing.Any) -> "URL":197 if (198 "username" in kwargs199 or "password" in kwargs200 or "host" in kwargs201 or "port" in kwargs202 ):203 host = kwargs.pop("host", self.host)204 port = kwargs.pop("port", None if self.is_relative_url else self.port)205 username = kwargs.pop("username", self.username)206 password = kwargs.pop("password", self.password)207208 authority = host209 if port is not None:210 authority += f":{port}"211 if username:212 userpass = username213 if password:214 userpass += f":{password}"215 authority = f"{userpass}@{authority}"216217 kwargs["authority"] = authority218219 return URL(220 self._uri_reference.copy_with(**kwargs).unsplit(),221 allow_relative=self.is_relative_url,222 )223224 def join(self, relative_url: URLTypes) -> "URL":225 """226 Return an absolute URL, using given this URL as the base.227 """228 if self.is_relative_url:229 return URL(relative_url)230231 # We drop any fragment portion, because RFC 3986 strictly232 # treats URLs with a fragment portion as not being absolute URLs.233 base_uri = self._uri_reference.copy_with(fragment=None)234 relative_url = URL(relative_url, allow_relative=True)235 return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())236237 def __hash__(self) -> int:238 return hash(str(self))239240 def __eq__(self, other: typing.Any) -> bool:241 return isinstance(other, (URL, str)) and str(self) == str(other)242243 def __str__(self) -> str:244 return self._uri_reference.unsplit()245246 def __repr__(self) -> str:247 class_name = self.__class__.__name__248 url_str = str(self)249 if self._uri_reference.userinfo:250 url_str = (251 rfc3986.urlparse(url_str)252 .copy_with(userinfo=f"{self.username}:[secure]")253 .unsplit()254 )255 return f"{class_name}({url_str!r})"256257258class Origin:259 """260 The URL scheme and authority information, as a comparable, hashable object.261 """262263 def __init__(self, url: URLTypes) -> None:264 if not isinstance(url, URL):265 url = URL(url)266 self.scheme = url.scheme267 self.is_ssl = url.is_ssl268 self.host = url.host269 self.port = url.port270271 def __eq__(self, other: typing.Any) -> bool:272 return (273 isinstance(other, self.__class__)274 and self.scheme == other.scheme275 and self.host == other.host276 and self.port == other.port277 )278279 def __hash__(self) -> int:280 return hash((self.scheme, self.host, self.port))281282 def __repr__(self) -> str:283 class_name = self.__class__.__name__284 return (285 f"{class_name}(scheme={self.scheme!r} host={self.host!r} port={self.port})"286 )287288289class QueryParams(typing.Mapping[str, str]):290 """291 URL query parameters, as a multi-dict.292 """293294 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:295 assert len(args) < 2, "Too many arguments."296 assert not (args and kwargs), "Cannot mix named and unnamed arguments."297298 value = args[0] if args else kwargs299300 items: typing.Sequence[typing.Tuple[str, PrimitiveData]]301 if isinstance(value, str):302 items = parse_qsl(value)303 elif isinstance(value, QueryParams):304 items = value.multi_items()305 elif isinstance(value, list):306 items = value307 else:308 items = flatten_queryparams(value)309310 self._list = [(str(k), str_query_param(v)) for k, v in items]311 self._dict = {str(k): str_query_param(v) for k, v in items}312313 def getlist(self, key: typing.Any) -> typing.List[str]:314 return [item_value for item_key, item_value in self._list if item_key == key]315316 def keys(self) -> typing.KeysView:317 return self._dict.keys()318319 def values(self) -> typing.ValuesView:320 return self._dict.values()321322 def items(self) -> typing.ItemsView:323 return self._dict.items()324325 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:326 return list(self._list)327328 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:329 if key in self._dict:330 return self._dict[key]331 return default332333 def update(self, params: QueryParamTypes = None) -> None: # type: ignore334 if not params:335 return336337 params = QueryParams(params)338 for param in params:339 item, *extras = params.getlist(param)340 self[param] = item341 if extras:342 self._list.extend((param, e) for e in extras)343 # ensure getter matches merged QueryParams getter344 self._dict[param] = params[param]345346 def __getitem__(self, key: typing.Any) -> str:347 return self._dict[key]348349 def __setitem__(self, key: str, value: str) -> None:350 self._dict[key] = value351352 found_indexes = []353 for idx, (item_key, _) in enumerate(self._list):354 if item_key == key:355 found_indexes.append(idx)356357 for idx in reversed(found_indexes[1:]):358 del self._list[idx]359360 if found_indexes:361 idx = found_indexes[0]362 self._list[idx] = (key, value)363 else:364 self._list.append((key, value))365366 def __contains__(self, key: typing.Any) -> bool:367 return key in self._dict368369 def __iter__(self) -> typing.Iterator[typing.Any]:370 return iter(self.keys())371372 def __len__(self) -> int:373 return len(self._dict)374375 def __eq__(self, other: typing.Any) -> bool:376 if not isinstance(other, self.__class__):377 return False378 return sorted(self._list) == sorted(other._list)379380 def __str__(self) -> str:381 return urlencode(self._list)382383 def __repr__(self) -> str:384 class_name = self.__class__.__name__385 query_string = str(self)386 return f"{class_name}({query_string!r})"387388389class Headers(typing.MutableMapping[str, str]):390 """391 HTTP headers, as a case-insensitive multi-dict.392 """393394 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:395 if headers is None:396 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]397 elif isinstance(headers, Headers):398 self._list = list(headers.raw)399 elif isinstance(headers, dict):400 self._list = [401 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))402 for k, v in headers.items()403 ]404 else:405 self._list = [406 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))407 for k, v in headers408 ]409 self._encoding = encoding410411 @property412 def encoding(self) -> str:413 """414 Header encoding is mandated as ascii, but we allow fallbacks to utf-8415 or iso-8859-1.416 """417 if self._encoding is None:418 for encoding in ["ascii", "utf-8"]:419 for key, value in self.raw:420 try:421 key.decode(encoding)422 value.decode(encoding)423 except UnicodeDecodeError:424 break425 else:426 # The else block runs if 'break' did not occur, meaning427 # all values fitted the encoding.428 self._encoding = encoding429 break430 else:431 # The ISO-8859-1 encoding covers all 256 code points in a byte,432 # so will never raise decode errors.433 self._encoding = "iso-8859-1"434 return self._encoding435436 @encoding.setter437 def encoding(self, value: str) -> None:438 self._encoding = value439440 @property441 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:442 """443 Returns a list of the raw header items, as byte pairs.444 May be mutated in-place.445 """446 return self._list447448 def keys(self) -> typing.List[str]: # type: ignore449 return [key.decode(self.encoding) for key, value in self._list]450451 def values(self) -> typing.List[str]: # type: ignore452 return [value.decode(self.encoding) for key, value in self._list]453454 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore455 return [456 (key.decode(self.encoding), value.decode(self.encoding))457 for key, value in self._list458 ]459460 def get(self, key: str, default: typing.Any = None) -> typing.Any:461 try:462 return self[key]463 except KeyError:464 return default465466 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:467 """468 Return multiple header values.469 """470 get_header_key = key.lower().encode(self.encoding)471472 values = [473 item_value.decode(self.encoding)474 for item_key, item_value in self._list475 if item_key == get_header_key476 ]477478 if not split_commas:479 return values480481 split_values = []482 for value in values:483 split_values.extend([item.strip() for item in value.split(",")])484 return split_values485486 def update(self, headers: HeaderTypes = None) -> None: # type: ignore487 headers = Headers(headers)488 for header in headers:489 self[header] = headers[header]490491 def copy(self) -> "Headers":492 return Headers(self.items(), encoding=self.encoding)493494 def __getitem__(self, key: str) -> str:495 """496 Return a single header value.497498 If there are multiple headers with the same key, then we concatenate499 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2500 """501 normalized_key = key.lower().encode(self.encoding)502503 items = []504 for header_key, header_value in self._list:505 if header_key == normalized_key:506 items.append(header_value.decode(self.encoding))507508 if items:509 return ", ".join(items)510511 raise KeyError(key)512513 def __setitem__(self, key: str, value: str) -> None:514 """515 Set the header `key` to `value`, removing any duplicate entries.516 Retains insertion order.517 """518 set_key = key.lower().encode(self.encoding)519 set_value = value.encode(self.encoding)520521 found_indexes = []522 for idx, (item_key, _) in enumerate(self._list):523 if item_key == set_key:524 found_indexes.append(idx)525526 for idx in reversed(found_indexes[1:]):527 del self._list[idx]528529 if found_indexes:530 idx = found_indexes[0]531 self._list[idx] = (set_key, set_value)532 else:533 self._list.append((set_key, set_value))534535 def __delitem__(self, key: str) -> None:536 """537 Remove the header `key`.538 """539 del_key = key.lower().encode(self.encoding)540541 pop_indexes = []542 for idx, (item_key, _) in enumerate(self._list):543 if item_key == del_key:544 pop_indexes.append(idx)545 if not pop_indexes:546 raise KeyError(key)547548 for idx in reversed(pop_indexes):549 del self._list[idx]550551 def __contains__(self, key: typing.Any) -> bool:552 get_header_key = key.lower().encode(self.encoding)553 for header_key, _ in self._list:554 if header_key == get_header_key:555 return True556 return False557558 def __iter__(self) -> typing.Iterator[typing.Any]:559 return iter(self.keys())560561 def __len__(self) -> int:562 return len(self._list)563564 def __eq__(self, other: typing.Any) -> bool:565 if not isinstance(other, Headers):566 return False567 return sorted(self._list) == sorted(other._list)568569 def __repr__(self) -> str:570 class_name = self.__class__.__name__571572 encoding_str = ""573 if self.encoding != "ascii":574 encoding_str = f", encoding={self.encoding!r}"575576 as_list = list(obfuscate_sensitive_headers(self.items()))577 as_dict = dict(as_list)578579 no_duplicate_keys = len(as_dict) == len(as_list)580 if no_duplicate_keys:581 return f"{class_name}({as_dict!r}{encoding_str})"582 return f"{class_name}({as_list!r}{encoding_str})"583584585USER_AGENT = f"python-httpx/{__version__}"586ACCEPT_ENCODING = ", ".join(587 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]588)589590591class Request:592 def __init__(593 self,594 method: str,595 url: typing.Union[str, URL],596 *,597 params: QueryParamTypes = None,598 headers: HeaderTypes = None,599 cookies: CookieTypes = None,600 data: RequestData = None,601 files: RequestFiles = None,602 json: typing.Any = None,603 stream: ContentStream = None,604 ):605 self.method = method.upper()606 self.url = URL(url, params=params)607 self.headers = Headers(headers)608 if cookies:609 Cookies(cookies).set_cookie_header(self)610611 if stream is not None:612 self.stream = stream613 else:614 self.stream = encode(data, files, json)615616 self.timer = ElapsedTimer()617 self.prepare()618619 def prepare(self) -> None:620 for key, value in self.stream.get_headers().items():621 self.headers.setdefault(key, value)622623 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []624625 has_host = "host" in self.headers626 has_user_agent = "user-agent" in self.headers627 has_accept = "accept" in self.headers628 has_accept_encoding = "accept-encoding" in self.headers629 has_connection = "connection" in self.headers630631 if not has_host:632 url = self.url633 if url.userinfo:634 url = url.copy_with(username=None, password=None)635 auto_headers.append((b"host", url.authority.encode("ascii")))636 if not has_user_agent:637 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))638 if not has_accept:639 auto_headers.append((b"accept", b"*/*"))640 if not has_accept_encoding:641 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))642 if not has_connection:643 auto_headers.append((b"connection", b"keep-alive"))644645 for item in reversed(auto_headers):646 self.headers.raw.insert(0, item)647648 @property649 def content(self) -> bytes:650 if not hasattr(self, "_content"):651 raise RequestNotRead()652 return self._content653654 def read(self) -> bytes:655 """656 Read and return the request content.657 """658 if not hasattr(self, "_content"):659 self._content = b"".join([part for part in self.stream])660 # If a streaming request has been read entirely into memory, then661 # we can replace the stream with a raw bytes implementation,662 # to ensure that any non-replayable streams can still be used.663 self.stream = ByteStream(self._content)664 return self._content665666 async def aread(self) -> bytes:667 """668 Read and return the request content.669 """670 if not hasattr(self, "_content"):671 self._content = b"".join([part async for part in self.stream])672 # If a streaming request has been read entirely into memory, then673 # we can replace the stream with a raw bytes implementation,674 # to ensure that any non-replayable streams can still be used.675 self.stream = ByteStream(self._content)676 return self._content677678 def __repr__(self) -> str:679 class_name = self.__class__.__name__680 url = str(self.url)681 return f"<{class_name}({self.method!r}, {url!r})>"682683684class Response:685 def __init__(686 self,687 status_code: int,688 *,689 request: Request,690 http_version: str = None,691 headers: HeaderTypes = None,692 stream: ContentStream = None,693 content: bytes = None,694 history: typing.List["Response"] = None,695 ):696 self.status_code = status_code697 self.http_version = http_version698 self.headers = Headers(headers)699700 self.request = request701 self.call_next: typing.Optional[typing.Callable] = None702703 self.history = [] if history is None else list(history)704705 self.is_closed = False706 self.is_stream_consumed = False707 if stream is not None:708 self._raw_stream = stream709 else:710 self._raw_stream = ByteStream(body=content or b"")711 self.read()712713 @property714 def elapsed(self) -> datetime.timedelta:715 """716 Returns the time taken for the complete request/response717 cycle to complete.718 """719 if not hasattr(self, "_elapsed"):720 raise RuntimeError(721 "'.elapsed' may only be accessed after the response "722 "has been read or closed."723 )724 return self._elapsed725726 @property727 def reason_phrase(self) -> str:728 return StatusCode.get_reason_phrase(self.status_code)729730 @property731 def url(self) -> typing.Optional[URL]:732 """733 Returns the URL for which the request was made.734 """735 return self.request.url736737 @property738 def content(self) -> bytes:739 if not hasattr(self, "_content"):740 raise ResponseNotRead()741 return self._content742743 @property744 def text(self) -> str:745 if not hasattr(self, "_text"):746 content = self.content747 if not content:748 self._text = ""749 else:750 encoding = self.encoding751 self._text = content.decode(encoding, errors="replace")752 return self._text753754 @property755 def encoding(self) -> str:756 if not hasattr(self, "_encoding"):757 encoding = self.charset_encoding758 if encoding is None or not is_known_encoding(encoding):759 encoding = self.apparent_encoding760 if encoding is None or not is_known_encoding(encoding):761 encoding = "utf-8"762 self._encoding = encoding763 return self._encoding764765 @encoding.setter766 def encoding(self, value: str) -> None:767 self._encoding = value768769 @property770 def charset_encoding(self) -> typing.Optional[str]:771 """772 Return the encoding, as specified by the Content-Type header.773 """774 content_type = self.headers.get("Content-Type")775 if content_type is None:776 return None777778 parsed = cgi.parse_header(content_type)779 media_type, params = parsed[0], parsed[-1]780 if "charset" in params:781 return params["charset"].strip("'\"")782783 # RFC 2616 specifies that 'iso-8859-1' should be used as the default784 # for 'text/*' media types, if no charset is provided.785 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1786 if media_type.startswith("text/"):787 return "iso-8859-1"788789 return None790791 @property792 def apparent_encoding(self) -> typing.Optional[str]:793 """794 Return the encoding, as it appears to autodetection.795 """796 return chardet.detect(self.content)["encoding"]797798 @property799 def decoder(self) -> Decoder:800 """801 Returns a decoder instance which can be used to decode the raw byte802 content, depending on the Content-Encoding used in the response.803 """804 if not hasattr(self, "_decoder"):805 decoders: typing.List[Decoder] = []806 values = self.headers.getlist("content-encoding", split_commas=True)807 for value in values:808 value = value.strip().lower()809 try:810 decoder_cls = SUPPORTED_DECODERS[value]811 decoders.append(decoder_cls())812 except KeyError:813 continue814815 if len(decoders) == 1:816 self._decoder = decoders[0]817 elif len(decoders) > 1:818 self._decoder = MultiDecoder(decoders)819 else:820 self._decoder = IdentityDecoder()821822 return self._decoder823824 @property825 def is_error(self) -> bool:826 return StatusCode.is_error(self.status_code)827828 @property829 def is_redirect(self) -> bool:830 return StatusCode.is_redirect(self.status_code) and "location" in self.headers831832 def raise_for_status(self) -> None:833 """834 Raise the `HttpError` if one occurred.835 """836 message = (837 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"838 "For more information check: https://httpstatuses.com/{0.status_code}"839 )840841 if StatusCode.is_client_error(self.status_code):842 message = message.format(self, error_type="Client Error")843 raise HTTPError(message, response=self)844 elif StatusCode.is_server_error(self.status_code):845 message = message.format(self, error_type="Server Error")846 raise HTTPError(message, response=self)847848 def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:849 if self.charset_encoding is None and self.content and len(self.content) > 3:850 encoding = guess_json_utf(self.content)851 if encoding is not None:852 try:853 return jsonlib.loads(self.content.decode(encoding), **kwargs)854 except UnicodeDecodeError:855 pass856 return jsonlib.loads(self.text, **kwargs)857858 @property859 def cookies(self) -> "Cookies":860 if not hasattr(self, "_cookies"):861 self._cookies = Cookies()862 self._cookies.extract_cookies(self)863 return self._cookies864865 @property866 def links(self) -> typing.Dict[typing.Optional[str], typing.Dict[str, str]]:867 """868 Returns the parsed header links of the response, if any869 """870 header = self.headers.get("link")871 ldict = {}872 if header:873 links = parse_header_links(header)874 for link in links:875 key = link.get("rel") or link.get("url")876 ldict[key] = link877 return ldict878879 def __repr__(self) -> str:880 return f"<Response [{self.status_code} {self.reason_phrase}]>"881882 @property883 def stream(self): # type: ignore884 warnings.warn( # pragma: nocover885 "Response.stream() is due to be deprecated. "886 "Use Response.aiter_bytes() instead."887 )888 return self.aiter_bytes # pragma: nocover889890 @property891 def raw(self): # type: ignore892 warnings.warn( # pragma: nocover893 "Response.raw() is due to be deprecated. "894 "Use Response.aiter_raw() instead."895 )896 return self.aiter_raw # pragma: nocover897898 def read(self) -> bytes:899 """900 Read and return the response content.901 """902 if not hasattr(self, "_content"):903 self._content = b"".join([part for part in self.iter_bytes()])904 return self._content905906 def iter_bytes(self) -> typing.Iterator[bytes]:907 """908 A byte-iterator over the decoded response content.909 This allows us to handle gzip, deflate, and brotli encoded responses.910 """911 if hasattr(self, "_content"):912 yield self._content913 else:914 for chunk in self.iter_raw():915 yield self.decoder.decode(chunk)916 yield self.decoder.flush()917918 def iter_text(self) -> typing.Iterator[str]:919 """920 A str-iterator over the decoded response content921 that handles both gzip, deflate, etc but also detects the content's922 string encoding.923 """924 decoder = TextDecoder(encoding=self.charset_encoding)925 for chunk in self.iter_bytes():926 yield decoder.decode(chunk)927 yield decoder.flush()928929 def iter_lines(self) -> typing.Iterator[str]:930 decoder = LineDecoder()931 for text in self.iter_text():932 for line in decoder.decode(text):933 yield line934 for line in decoder.flush():935 yield line936937 def iter_raw(self) -> typing.Iterator[bytes]:938 """939 A byte-iterator over the raw response content.940 """941 if self.is_stream_consumed:942 raise StreamConsumed()943 if self.is_closed:944 raise ResponseClosed()945946 self.is_stream_consumed = True947 for part in self._raw_stream:948 yield part949 self.close()950951 def close(self) -> None:952 """953 Close the response and release the connection.954 Automatically called if the response body is read to completion.955 """956 if not self.is_closed:957 self.is_closed = True958 self._elapsed = self.request.timer.elapsed959 if hasattr(self, "_raw_stream"):960 self._raw_stream.close()961962 async def aread(self) -> bytes:963 """964 Read and return the response content.965 """966 if not hasattr(self, "_content"):967 self._content = b"".join([part async for part in self.aiter_bytes()])968 return self._content969970 async def aiter_bytes(self) -> typing.AsyncIterator[bytes]:971 """972 A byte-iterator over the decoded response content.973 This allows us to handle gzip, deflate, and brotli encoded responses.974 """975 if hasattr(self, "_content"):976 yield self._content977 else:978 async for chunk in self.aiter_raw():979 yield self.decoder.decode(chunk)980 yield self.decoder.flush()981982 async def aiter_text(self) -> typing.AsyncIterator[str]:983 """984 A str-iterator over the decoded response content985 that handles both gzip, deflate, etc but also detects the content's986 string encoding.987 """988 decoder = TextDecoder(encoding=self.charset_encoding)989 async for chunk in self.aiter_bytes():990 yield decoder.decode(chunk)991 yield decoder.flush()992993 async def aiter_lines(self) -> typing.AsyncIterator[str]:994 decoder = LineDecoder()995 async for text in self.aiter_text():996 for line in decoder.decode(text):997 yield line998 for line in decoder.flush():999 yield line10001001 async def aiter_raw(self) -> typing.AsyncIterator[bytes]:1002 """1003 A byte-iterator over the raw response content.1004 """1005 if self.is_stream_consumed:1006 raise StreamConsumed()1007 if self.is_closed:1008 raise ResponseClosed()10091010 self.is_stream_consumed = True1011 async for part in self._raw_stream:1012 yield part1013 await self.aclose()10141015 async def anext(self) -> "Response":1016 """1017 Get the next response from a redirect response.1018 """1019 if not self.is_redirect:1020 raise NotRedirectResponse()1021 assert self.call_next is not None1022 return await self.call_next()10231024 async def aclose(self) -> None:1025 """1026 Close the response and release the connection.1027 Automatically called if the response body is read to completion.1028 """1029 if not self.is_closed:1030 self.is_closed = True1031 self._elapsed = self.request.timer.elapsed1032 if hasattr(self, "_raw_stream"):1033 await self._raw_stream.aclose()103410351036class Cookies(MutableMapping):1037 """1038 HTTP Cookies, as a mutable mapping.1039 """10401041 def __init__(self, cookies: CookieTypes = None) -> None:1042 if cookies is None or isinstance(cookies, dict):1043 self.jar = CookieJar()1044 if isinstance(cookies, dict):1045 for key, value in cookies.items():1046 self.set(key, value)1047 elif isinstance(cookies, Cookies):1048 self.jar = CookieJar()1049 for cookie in cookies.jar:1050 self.jar.set_cookie(cookie)1051 else:1052 self.jar = cookies10531054 def extract_cookies(self, response: Response) -> None:1055 """1056 Loads any cookies based on the response `Set-Cookie` headers.1057 """1058 urlib_response = self._CookieCompatResponse(response)1059 urllib_request = self._CookieCompatRequest(response.request)10601061 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore10621063 def set_cookie_header(self, request: Request) -> None:1064 """1065 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1066 """1067 urllib_request = self._CookieCompatRequest(request)1068 self.jar.add_cookie_header(urllib_request)10691070 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1071 """1072 Set a cookie value by name. May optionally include domain and path.1073 """1074 kwargs = {1075 "version": 0,1076 "name": name,1077 "value": value,1078 "port": None,1079 "port_specified": False,1080 "domain": domain,1081 "domain_specified": bool(domain),1082 "domain_initial_dot": domain.startswith("."),1083 "path": path,1084 "path_specified": bool(path),1085 "secure": False,1086 "expires": None,1087 "discard": True,1088 "comment": None,1089 "comment_url": None,1090 "rest": {"HttpOnly": None},1091 "rfc2109": False,1092 }1093 cookie = Cookie(**kwargs) # type: ignore1094 self.jar.set_cookie(cookie)10951096 def get( # type: ignore1097 self, name: str, default: str = None, domain: str = None, path: str = None1098 ) -> typing.Optional[str]:1099 """1100 Get a cookie by name. May optionally include domain and path1101 in order to specify exactly which cookie to retrieve.1102 """1103 value = None1104 for cookie in self.jar:1105 if cookie.name == name:1106 if domain is None or cookie.domain == domain: # type: ignore1107 if path is None or cookie.path == path:1108 if value is not None:1109 message = f"Multiple cookies exist with name={name}"1110 raise CookieConflict(message)1111 value = cookie.value11121113 if value is None:1114 return default1115 return value11161117 def delete(self, name: str, domain: str = None, path: str = None) -> None:1118 """1119 Delete a cookie by name. May optionally include domain and path1120 in order to specify exactly which cookie to delete.1121 """1122 if domain is not None and path is not None:1123 return self.jar.clear(domain, path, name)11241125 remove = []1126 for cookie in self.jar:1127 if cookie.name == name:1128 if domain is None or cookie.domain == domain: # type: ignore1129 if path is None or cookie.path == path:1130 remove.append(cookie)11311132 for cookie in remove:1133 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore11341135 def clear(self, domain: str = None, path: str = None) -> None:1136 """1137 Delete all cookies. Optionally include a domain and path in1138 order to only delete a subset of all the cookies.1139 """1140 args = []1141 if domain is not None:1142 args.append(domain)1143 if path is not None:1144 assert domain is not None1145 args.append(path)1146 self.jar.clear(*args)11471148 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1149 cookies = Cookies(cookies)1150 for cookie in cookies.jar:1151 self.jar.set_cookie(cookie)11521153 def __setitem__(self, name: str, value: str) -> None:1154 return self.set(name, value)11551156 def __getitem__(self, name: str) -> str:1157 value = self.get(name)1158 if value is None:1159 raise KeyError(name)1160 return value11611162 def __delitem__(self, name: str) -> None:1163 return self.delete(name)11641165 def __len__(self) -> int:1166 return len(self.jar)11671168 def __iter__(self) -> typing.Iterator[str]:1169 return (cookie.name for cookie in self.jar)11701171 def __bool__(self) -> bool:1172 for _ in self.jar:1173 return True1174 return False11751176 class _CookieCompatRequest(urllib.request.Request):1177 """1178 Wraps a `Request` instance up in a compatibility interface suitable1179 for use with `CookieJar` operations.1180 """11811182 def __init__(self, request: Request) -> None:1183 super().__init__(1184 url=str(request.url),1185 headers=dict(request.headers),1186 method=request.method,1187 )1188 self.request = request11891190 def add_unredirected_header(self, key: str, value: str) -> None:1191 super().add_unredirected_header(key, value)1192 self.request.headers[key] = value11931194 class _CookieCompatResponse:1195 """1196 Wraps a `Request` instance up in a compatibility interface suitable1197 for use with `CookieJar` operations.1198 """11991200 def __init__(self, response: Response):1201 self.response = response12021203 def info(self) -> email.message.Message:1204 info = email.message.Message()1205 for key, value in self.response.headers.items():1206 info[key] = value1207 return info
deleted:httpx/status_codes.py-139 removed
1from enum import IntEnum234class StatusCode(IntEnum):5 """HTTP status codes and reason phrases6 Status codes from the following RFCs are all observed:7 * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 26168 * RFC 6585: Additional HTTP Status Codes9 * RFC 3229: Delta encoding in HTTP10 * RFC 4918: HTTP Extensions for WebDAV, obsoletes 251811 * RFC 5842: Binding Extensions to WebDAV12 * RFC 7238: Permanent Redirect13 * RFC 2295: Transparent Content Negotiation in HTTP14 * RFC 2774: An HTTP Extension Framework15 * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)16 * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)17 * RFC 7725: An HTTP Status Code to Report Legal Obstacles18 """1920 def __new__(cls, value: int, phrase: str = "") -> "StatusCode":21 obj = int.__new__(cls, value) # type: ignore22 obj._value_ = value2324 obj.phrase = phrase25 return obj2627 def __str__(self) -> str:28 return str(self.value)2930 @classmethod31 def get_reason_phrase(cls, value: int) -> str:32 try:33 return StatusCode(value).phrase # type: ignore34 except ValueError:35 return ""3637 @classmethod38 def is_redirect(cls, value: int) -> bool:39 return value in (40 # 301 (Cacheable redirect. Method may change to GET.)41 StatusCode.MOVED_PERMANENTLY,42 # 302 (Uncacheable redirect. Method may change to GET.)43 StatusCode.FOUND,44 # 303 (Client should make a GET or HEAD request.)45 StatusCode.SEE_OTHER,46 # 307 (Equiv. 302, but retain method)47 StatusCode.TEMPORARY_REDIRECT,48 # 308 (Equiv. 301, but retain method)49 StatusCode.PERMANENT_REDIRECT,50 )5152 @classmethod53 def is_error(cls, value: int) -> bool:54 return 400 <= value <= 5995556 @classmethod57 def is_client_error(cls, value: int) -> bool:58 return 400 <= value <= 4995960 @classmethod61 def is_server_error(cls, value: int) -> bool:62 return 500 <= value <= 5996364 # informational65 CONTINUE = 100, "Continue"66 SWITCHING_PROTOCOLS = 101, "Switching Protocols"67 PROCESSING = 102, "Processing"6869 # success70 OK = 200, "OK"71 CREATED = 201, "Created"72 ACCEPTED = 202, "Accepted"73 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"74 NO_CONTENT = 204, "No Content"75 RESET_CONTENT = 205, "Reset Content"76 PARTIAL_CONTENT = 206, "Partial Content"77 MULTI_STATUS = 207, "Multi-Status"78 ALREADY_REPORTED = 208, "Already Reported"79 IM_USED = 226, "IM Used"8081 # redirection82 MULTIPLE_CHOICES = 300, "Multiple Choices"83 MOVED_PERMANENTLY = 301, "Moved Permanently"84 FOUND = 302, "Found"85 SEE_OTHER = 303, "See Other"86 NOT_MODIFIED = 304, "Not Modified"87 USE_PROXY = 305, "Use Proxy"88 TEMPORARY_REDIRECT = 307, "Temporary Redirect"89 PERMANENT_REDIRECT = 308, "Permanent Redirect"9091 # client error92 BAD_REQUEST = 400, "Bad Request"93 UNAUTHORIZED = 401, "Unauthorized"94 PAYMENT_REQUIRED = 402, "Payment Required"95 FORBIDDEN = 403, "Forbidden"96 NOT_FOUND = 404, "Not Found"97 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"98 NOT_ACCEPTABLE = 406, "Not Acceptable"99 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"100 REQUEST_TIMEOUT = 408, "Request Timeout"101 CONFLICT = 409, "Conflict"102 GONE = 410, "Gone"103 LENGTH_REQUIRED = 411, "Length Required"104 PRECONDITION_FAILED = 412, "Precondition Failed"105 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"106 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"107 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"108 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"109 EXPECTATION_FAILED = 417, "Expectation Failed"110 IM_A_TEAPOT = 418, "I'm a teapot"111 MISDIRECTED_REQUEST = 421, "Misdirected Request"112 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"113 LOCKED = 423, "Locked"114 FAILED_DEPENDENCY = 424, "Failed Dependency"115 UPGRADE_REQUIRED = 426, "Upgrade Required"116 PRECONDITION_REQUIRED = 428, "Precondition Required"117 TOO_MANY_REQUESTS = 429, "Too Many Requests"118 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"119 UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons"120121 # server errors122 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"123 NOT_IMPLEMENTED = 501, "Not Implemented"124 BAD_GATEWAY = 502, "Bad Gateway"125 SERVICE_UNAVAILABLE = 503, "Service Unavailable"126 GATEWAY_TIMEOUT = 504, "Gateway Timeout"127 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"128 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"129 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"130 LOOP_DETECTED = 508, "Loop Detected"131 NOT_EXTENDED = 510, "Not Extended"132 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"133134135codes = StatusCode136137#  Include lower-case styles for `requests` compatibility.138for code in codes:139 setattr(codes, code._name_.lower(), int(code))
deleted:httpx/utils.py-369 removed
1import codecs2import collections3import contextlib4import logging5import netrc6import os7import re8import sys9import typing10from datetime import timedelta11from pathlib import Path12from time import perf_counter13from types import TracebackType14from urllib.request import getproxies1516from .exceptions import NetworkError1718if typing.TYPE_CHECKING: # pragma: no cover19 from .models import PrimitiveData20 from .models import URL212223_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}24_HTML5_FORM_ENCODING_REPLACEMENTS.update(25 {chr(c): "%{:02X}".format(c) for c in range(0x00, 0x1F + 1) if c != 0x1B}26)27_HTML5_FORM_ENCODING_RE = re.compile(28 r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])29)303132def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:33 """34 Coerce str/bytes into a strictly byte-wise HTTP header key.35 """36 if isinstance(value, bytes):37 return value.lower()38 return value.encode(encoding or "ascii").lower()394041def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:42 """43 Coerce str/bytes into a strictly byte-wise HTTP header value.44 """45 if isinstance(value, bytes):46 return value47 return value.encode(encoding or "ascii")484950def str_query_param(value: "PrimitiveData") -> str:51 """52 Coerce a primitive data type into a string value for query params.5354 Note that we prefer JSON-style 'true'/'false' for boolean values here.55 """56 if value is True:57 return "true"58 elif value is False:59 return "false"60 elif value is None:61 return ""62 return str(value)636465def is_known_encoding(encoding: str) -> bool:66 """67 Return `True` if `encoding` is a known codec.68 """69 try:70 codecs.lookup(encoding)71 except LookupError:72 return False73 return True747576def format_form_param(name: str, value: typing.Union[str, bytes]) -> bytes:77 """78 Encode a name/value pair within a multipart form.79 """80 if isinstance(value, bytes):81 value = value.decode()8283 def replacer(match: typing.Match[str]) -> str:84 return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]8586 value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)87 return f'{name}="{value}"'.encode()888990# Null bytes; no need to recreate these on each call to guess_json_utf91_null = "\x00".encode("ascii") # encoding to ASCII for Python 392_null2 = _null * 293_null3 = _null * 3949596def guess_json_utf(data: bytes) -> typing.Optional[str]:97 # JSON always starts with two ASCII characters, so detection is as98 # easy as counting the nulls and from their location and count99 # determine the encoding. Also detect a BOM, if present.100 sample = data[:4]101 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):102 return "utf-32" # BOM included103 if sample[:3] == codecs.BOM_UTF8:104 return "utf-8-sig" # BOM included, MS style (discouraged)105 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):106 return "utf-16" # BOM included107 nullcount = sample.count(_null)108 if nullcount == 0:109 return "utf-8"110 if nullcount == 2:111 if sample[::2] == _null2: # 1st and 3rd are null112 return "utf-16-be"113 if sample[1::2] == _null2: # 2nd and 4th are null114 return "utf-16-le"115 # Did not detect 2 valid UTF-16 ascii-range characters116 if nullcount == 3:117 if sample[:3] == _null3:118 return "utf-32-be"119 if sample[1:] == _null3:120 return "utf-32-le"121 # Did not detect a valid UTF-32 ascii-range character122 return None123124125class NetRCInfo:126 def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:127 if files is None:128 files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]129 self.netrc_files = files130131 @property132 def netrc_info(self) -> typing.Optional[netrc.netrc]:133 if not hasattr(self, "_netrc_info"):134 self._netrc_info = None135 for file_path in self.netrc_files:136 expanded_path = Path(file_path).expanduser()137 if expanded_path.is_file():138 self._netrc_info = netrc.netrc(str(expanded_path))139 break140 return self._netrc_info141142 def get_credentials(143 self, authority: str144 ) -> typing.Optional[typing.Tuple[str, str]]:145 if self.netrc_info is None:146 return None147148 auth_info = self.netrc_info.authenticators(authority)149 if auth_info is None or auth_info[2] is None:150 return None151 return (auth_info[0], auth_info[2])152153154def get_ca_bundle_from_env() -> typing.Optional[str]:155 if "SSL_CERT_FILE" in os.environ:156 ssl_file = Path(os.environ["SSL_CERT_FILE"])157 if ssl_file.is_file():158 return str(ssl_file)159 if "SSL_CERT_DIR" in os.environ:160 ssl_path = Path(os.environ["SSL_CERT_DIR"])161 if ssl_path.is_dir():162 return str(ssl_path)163 return None164165166def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:167 """168 Returns a list of parsed link headers, for more info see:169 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link170 The generic syntax of those is:171 Link: < uri-reference >; param1=value1; param2="value2"172 So for instance:173 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'174 would return175 [176 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},177 {"url": "http://.../back.jpeg"},178 ]179 :param value: HTTP Link entity-header field180 :return: list of parsed link headers181 """182 links: typing.List[typing.Dict[str, str]] = []183 replace_chars = " '\""184 value = value.strip(replace_chars)185 if not value:186 return links187 for val in re.split(", *<", value):188 try:189 url, params = val.split(";", 1)190 except ValueError:191 url, params = val, ""192 link = {"url": url.strip("<> '\"")}193 for param in params.split(";"):194 try:195 key, value = param.split("=")196 except ValueError:197 break198 link[key.strip(replace_chars)] = value.strip(replace_chars)199 links.append(link)200 return links201202203SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}204205206def obfuscate_sensitive_headers(207 items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]208) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:209 for k, v in items:210 if to_str(k.lower()) in SENSITIVE_HEADERS:211 v = to_bytes_or_str("[secure]", match_type_of=v)212 yield k, v213214215_LOGGER_INITIALIZED = False216TRACE_LOG_LEVEL = 5217218219class Logger(logging.Logger):220 # Stub for type checkers.221 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:222 ... # pragma: nocover223224225def get_logger(name: str) -> Logger:226 """227 Get a `logging.Logger` instance, and optionally228 set up debug logging based on the HTTPX_LOG_LEVEL environment variable.229 """230 global _LOGGER_INITIALIZED231232 if not _LOGGER_INITIALIZED:233 _LOGGER_INITIALIZED = True234 logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")235236 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()237 if log_level in ("DEBUG", "TRACE"):238 logger = logging.getLogger("httpx")239 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)240 handler = logging.StreamHandler(sys.stderr)241 handler.setFormatter(242 logging.Formatter(243 fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",244 datefmt="%Y-%m-%d %H:%M:%S",245 )246 )247 logger.addHandler(handler)248249 logger = logging.getLogger(name)250251 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:252 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)253254 logger.trace = trace # type: ignore255256 return typing.cast(Logger, logger)257258259def should_not_be_proxied(url: "URL") -> bool:260 """ Return True if url should not be proxied,261 return False otherwise.262 """263 no_proxy = getproxies().get("no")264 if not no_proxy:265 return False266 no_proxy_list = [host.strip() for host in no_proxy.split(",")]267 for name in no_proxy_list:268 if name == "*":269 return True270 if name:271 name = name.lstrip(".") # ignore leading dots272 name = re.escape(name)273 pattern = r"(.+\.)?%s$" % name274 if re.match(pattern, url.host, re.I) or re.match(275 pattern, url.authority, re.I276 ):277 return True278 return False279280281def get_environment_proxies() -> typing.Dict[str, str]:282 """Gets proxy information from the environment"""283284 # urllib.request.getproxies() falls back on System285 # Registry and Config for proxies on Windows and macOS.286 # We don't want to propagate non-HTTP proxies into287 # our configuration such as 'TRAVIS_APT_PROXY'.288 supported_proxy_schemes = ("http", "https", "all")289 return {290 key: val291 for key, val in getproxies().items()292 if ("://" in key or key in supported_proxy_schemes)293 }294295296def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:297 return value.encode(encoding) if isinstance(value, str) else value298299300def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:301 return value if isinstance(value, str) else value.decode(encoding)302303304def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:305 return value if isinstance(match_type_of, str) else value.encode()306307308def unquote(value: str) -> str:309 return value[1:-1] if value[0] == value[-1] == '"' else value310311312def flatten_queryparams(313 queryparams: typing.Mapping[314 str, typing.Union["PrimitiveData", typing.Sequence["PrimitiveData"]]315 ]316) -> typing.List[typing.Tuple[str, "PrimitiveData"]]:317 """318 Convert a mapping of query params into a flat list of two-tuples319 representing each item.320321 Example:322 >>> flatten_queryparams_values({"q": "httpx", "tag": ["python", "dev"]})323 [("q", "httpx), ("tag", "python"), ("tag", "dev")]324 """325 items = []326327 for k, v in queryparams.items():328 if isinstance(v, collections.abc.Sequence) and not isinstance(v, (str, bytes)):329 for u in v:330 items.append((k, u))331 else:332 items.append((k, typing.cast("PrimitiveData", v)))333334 return items335336337class ElapsedTimer:338 def __init__(self) -> None:339 self.start: float = perf_counter()340 self.end: typing.Optional[float] = None341342 def __enter__(self) -> "ElapsedTimer":343 self.start = perf_counter()344 return self345346 def __exit__(347 self,348 exc_type: typing.Type[BaseException] = None,349 exc_value: BaseException = None,350 traceback: TracebackType = None,351 ) -> None:352 self.end = perf_counter()353354 @property355 def elapsed(self) -> timedelta:356 if self.end is None:357 return timedelta(seconds=perf_counter() - self.start)358 return timedelta(seconds=self.end - self.start)359360361@contextlib.contextmanager362def as_network_error(*exception_classes: type) -> typing.Iterator[None]:363 try:364 yield365 except BaseException as exc:366 for cls in exception_classes:367 if isinstance(exc, cls):368 raise NetworkError(exc) from exc369 raise
modified:tests/client/test_auth.py+2 added-2 removed
13 unmodified lines
14 Request,15 RequestBodyUnavailable,16 Response,17)18from httpx.config import CertTypes, TimeoutTypes, VerifyTypes19from httpx.dispatch.base import AsyncDispatcher18from httpx._config import CertTypes, TimeoutTypes, VerifyTypes19from httpx._dispatch.base import AsyncDispatcher202122class MockDispatch(AsyncDispatcher):23 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:
446 unmodified lines
modified:tests/client/test_cookies.py+2 added-2 removed
2 unmodified lines
34import pytest56from httpx import AsyncClient, Cookies, Request, Response7from httpx.config import CertTypes, TimeoutTypes, VerifyTypes8from httpx.dispatch.base import AsyncDispatcher7from httpx._config import CertTypes, TimeoutTypes, VerifyTypes8from httpx._dispatch.base import AsyncDispatcher91011class MockDispatch(AsyncDispatcher):12 async def send(
152 unmodified lines
modified:tests/client/test_headers.py+2 added-2 removed
3 unmodified lines
45import pytest67from httpx import AsyncClient, Headers, Request, Response, __version__8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import AsyncDispatcher8from httpx._config import CertTypes, TimeoutTypes, VerifyTypes9from httpx._dispatch.base import AsyncDispatcher101112class MockDispatch(AsyncDispatcher):13 async def send(
165 unmodified lines
modified:tests/client/test_queryparams.py+2 added-2 removed
1 unmodified line
23import pytest45from httpx import URL, AsyncClient, QueryParams, Request, Response6from httpx.config import CertTypes, TimeoutTypes, VerifyTypes7from httpx.dispatch.base import AsyncDispatcher6from httpx._config import CertTypes, TimeoutTypes, VerifyTypes7from httpx._dispatch.base import AsyncDispatcher8910class MockDispatch(AsyncDispatcher):11 async def send(
40 unmodified lines
modified:tests/client/test_redirects.py+3 added-3 removed
12 unmodified lines
13 Response,14 TooManyRedirects,15 codes,16)17from httpx.config import CertTypes, TimeoutTypes, VerifyTypes18from httpx.content_streams import AsyncIteratorStream19from httpx.dispatch.base import AsyncDispatcher17from httpx._config import CertTypes, TimeoutTypes, VerifyTypes18from httpx._content_streams import AsyncIteratorStream19from httpx._dispatch.base import AsyncDispatcher202122class MockDispatch(AsyncDispatcher):23 async def send(
383 unmodified lines
modified:tests/dispatch/test_connection_pools.py+1 added-1 removed
1import pytest23import httpx4from httpx.dispatch.connection_pool import ConnectionPool4from httpx._dispatch.connection_pool import ConnectionPool567@pytest.mark.usefixtures("async_environment")8async def test_keepalive_connections(server):
238 unmodified lines
modified:tests/dispatch/test_connections.py+2 added-2 removed
1import pytest23import httpx4from httpx.config import SSLConfig5from httpx.dispatch.connection import HTTPConnection4from httpx._config import SSLConfig5from httpx._dispatch.connection import HTTPConnection678@pytest.mark.usefixtures("async_environment")9async def test_get(server):
35 unmodified lines
modified:tests/dispatch/test_proxy_http.py+1 added-1 removed
1import pytest23import httpx4from httpx.dispatch.proxy_http import HTTPProxy4from httpx._dispatch.proxy_http import HTTPProxy56from .utils import MockRawSocketBackend78
199 unmodified lines
modified:tests/dispatch/utils.py+1 added-1 removed
4 unmodified lines
5import h2.connection6import h2.events78from httpx import Request, Timeout9from httpx.backends.base import BaseSocketStream, lookup_backend9from httpx._backends.base import BaseSocketStream, lookup_backend101112class MockHTTP2Backend:13 def __init__(self, app, backend="auto"):
191 unmodified lines
modified:tests/models/test_responses.py+2 added-2 removed
3 unmodified lines
45import pytest67import httpx8from httpx.content_streams import AsyncIteratorStream, IteratorStream8from httpx._content_streams import AsyncIteratorStream, IteratorStream910REQUEST = httpx.Request("GET", "https://example.org")1112
355 unmodified lines
368 data = {"greeting": "hello", "recipient": "world"}369 content = json.dumps(data).encode("utf-32-be")370 headers = {"Content-Type": "application/json"}371 # force incorrect guess from `guess_json_utf` to trigger error372 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):372 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):373 response = httpx.Response(374 200, content=content, headers=headers, request=REQUEST375 )376 with pytest.raises(json.JSONDecodeError):
22 unmodified lines
modified:tests/models/test_url.py+1 added-1 removed
1import pytest23from httpx import URL, InvalidURL4from httpx.models import Origin4from httpx._models import Origin567@pytest.mark.parametrize(8 "given,idna,host,scheme,port",
198 unmodified lines
modified:tests/test_concurrency.py+4 added-4 removed
2 unmodified lines
3import pytest4import trio56from httpx import Timeout7from httpx.backends.asyncio import AsyncioBackend8from httpx.backends.base import lookup_backend9from httpx.backends.trio import TrioBackend10from httpx.config import SSLConfig7from httpx._backends.asyncio import AsyncioBackend8from httpx._backends.base import lookup_backend9from httpx._backends.trio import TrioBackend10from httpx._config import SSLConfig11from tests.concurrency import get_cipher, run_concurrently121314async def read_response(stream, timeout: Timeout, should_contain: bytes) -> bytes:
108 unmodified lines
modified:tests/test_config.py+1 added-1 removed
6 unmodified lines
7import certifi8import pytest910import httpx11from httpx.config import SSLConfig11from httpx._config import SSLConfig121314def test_load_ssl_config():15 ssl_config = SSLConfig()
226 unmodified lines
modified:tests/test_content_streams.py+2 added-2 removed
1import io23import pytest45from httpx.content_streams import ContentStream, encode6from httpx.exceptions import StreamConsumed5from httpx import StreamConsumed6from httpx._content_streams import ContentStream, encode789@pytest.mark.asyncio10async def test_base_content():
184 unmodified lines
modified:tests/test_decoders.py+2 added-2 removed
2 unmodified lines
3import brotli4import pytest56import httpx7from httpx.content_streams import AsyncIteratorStream8from httpx.decoders import (7from httpx._content_streams import AsyncIteratorStream8from httpx._decoders import (9 BrotliDecoder,10 DeflateDecoder,11 GZipDecoder,12 IdentityDecoder,
252 unmodified lines
modified:tests/test_multipart.py+4 added-4 removed
5 unmodified lines
67import pytest89import httpx10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.content_streams import encode12from httpx.dispatch.base import AsyncDispatcher13from httpx.utils import format_form_param10from httpx._config import CertTypes, TimeoutTypes, VerifyTypes11from httpx._content_streams import encode12from httpx._dispatch.base import AsyncDispatcher13from httpx._utils import format_form_param141516class MockDispatch(AsyncDispatcher):17 async def send(
184 unmodified lines
modified:tests/test_utils.py+4 added-4 removed
2 unmodified lines
34import pytest56import httpx7from httpx.utils import (7from httpx._utils import (8 ElapsedTimer,9 NetRCInfo,10 get_ca_bundle_from_env,11 get_environment_proxies,
85 unmodified lines
97 response = await client.get(server.url)98 assert response.status_code == 20099 stderr = capsys.readouterr().err100 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr101 assert "httpx.dispatch.connection_pool" not in stderr101 assert "httpx._dispatch.connection_pool" not in stderr102103104@pytest.mark.asyncio105async def test_logs_trace(server, capsys):
2 unmodified lines
108 response = await client.get(server.url)109 assert response.status_code == 200110 stderr = capsys.readouterr().err111 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr112 assert "httpx.dispatch.connection_pool" in stderr112 assert "httpx._dispatch.connection_pool" in stderr113114115@pytest.mark.asyncio116async def test_logs_redirect_chain(server, capsys):
165 unmodified lines
282 ],283)284def test_should_not_be_proxied(url, no_proxy, expected):285 os.environ.update(no_proxy)286 parsed_url = httpx.models.URL(url)286 parsed_url = httpx.URL(url)287 assert should_not_be_proxied(parsed_url) == expected
modified:tests/utils.py+3 added-3 removed
1import contextlib2import logging3import os45from httpx import utils5from httpx import _utils678@contextlib.contextmanager9def override_log_level(log_level: str):10 os.environ["HTTPX_LOG_LEVEL"] = log_level1112 # Force a reload on the logging handlers13 utils._LOGGER_INITIALIZED = False14 utils.get_logger("httpx")13 _utils._LOGGER_INITIALIZED = False14 _utils.get_logger("httpx")1516 try:17 yield18 finally:
2 unmodified lines