Skip to content
Myr

http3 (#86)

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

* Start fleshing out documentation * Docs work * http3 * Update docs * Include lowercase status codes, for requests compat * Updating docs * Docs tweaks

authored by Tom Christie · committed by GitHub · parent 77c3725 · Browse files · 69 files+4835 added−4173 removed
This commit

State

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

Diff stats

69 files+4835 added−4173 removed

  • tests:+161 added−161 removed
  • other:+4674 added−4012 removed

69 files+4835 added−4173 removed

added:docs/api.md+146 added
1# Developer Interface23## Main Interface45* `get(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`6* `options(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`7* `head(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`8* `post(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`9* `put(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`10* `patch(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`11* `delete(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`12* `request(method, url, [data], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`1314## `Client`1516*An HTTP client, with connection pooling, redirects, cookie persistence, etc.*1718```python19>>> client = http3.Client()20>>> response = client.get('https://example.org')21```2223* `def __init__([auth], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [dispatch])`24* `def .get(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`25* `def .options(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`26* `def .head(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`27* `def .post(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`28* `def .put(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`29* `def .patch(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`30* `def .delete(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`31* `def .request(method, url, [data], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`32* `def .send(request, [stream], [allow_redirects], [verify], [cert], [timeout])`33* `def .close()`3435## `Response`3637*An HTTP response.*3839* `def __init__(...)`40* `.status_code` - **int** *(Typically a `StatusCode` IntEnum.)*41* `.reason_phrase` - **str**42* `.protocol` - `"HTTP/2"` or `"HTTP/1.1"`43* `.url` - **URL**44* `.headers` - **Headers**45* `.content` - **bytes**46* `.text` - **str**47* `.encoding` - **str**48* `.is_redirect` - **bool**49* `.request` - **Request**50* `.cookies` - **Cookies**51* `.history` - **List[Response]**52* `def .raise_for_status()` - **None**53* `def .json()` - **Any**54* `def .read()` - **bytes**55* `def .stream()` - **bytes iterator**56* `def .raw()` - **bytes iterator**57* `def .close()` - **None**58* `def .next()` - **Response**5960## `Request`6162*An HTTP request. Can be constructed explicitly for more control over exactly63what gets sent over the wire.*6465```python66>>> request = http3.Request("GET", "https://example.org", headers={'host': 'example.org'})67>>> response = client.send(request)68```6970* `def __init__(method, url, [params], [data], [json], [headers], [cookies])`71* `.method` - **str**72* `.url` - **URL**73* `.content` - **byte** or **byte async iterator**74* `.headers` - **Headers**75* `.cookies` - **Cookies**7677## `URL`7879*A normalized, IDNA supporting URL.*8081```python82>>> url = URL("https://example.org/")83>>> url.host84'example.org'85```8687* `def __init__(url, allow_relative=False, params=None)`88* `.scheme` - **str**89* `.authority` - **str**90* `.host` - **str**91* `.port` - **int**92* `.path` - **str**93* `.query` - **str**94* `.full_path` - **str**95* `.fragment` - **str**96* `.is_ssl` - **bool**97* `.origin` - **Origin**98* `.is_absolute_url` - **bool**99* `.is_relative_url` - **bool**100* `def .copy_with([scheme], [authority], [path], [query], [fragment])` - **URL**101* `def .resolve_with(url)` - **URL**102103## `Origin`104105*A normalized, IDNA supporting set of scheme/host/port info.*106107```python108>>> Origin('https://example.org') == Origin('HTTPS://EXAMPLE.ORG:443')109True110```111112* `def __init__(url)`113* `.is_ssl` - **bool**114* `.host` - **str**115* `.port` - **int**116117## `Headers`118119*A case-insensitive multi-dict.*120121```python122>>> headers = Headers({'Content-Type': 'application/json'})123>>> headers['content-type']124'application/json'125```126127* `def __init__(self, headers)`128129## `Cookies`130131*A dict-like cookie store.*132133```python134>>> cookies = Cookies()135>>> cookies.set("name", "value", domain="example.org")136```137138* `def __init__(cookies: [dict, Cookies, CookieJar])`139* `.jar` - **CookieJar**140* `def extract_cookies(response)`141* `def set_cookie_header(request)`142* `def set(name, value, [domain], [path])`143* `def get(name, [domain], [path])`144* `def delete(name, [domain], [path])`145* `def clear([domain], [path])`146* *Standard mutable mapping interface*
added:docs/async.md+60 added
added:docs/compatibility.md+7 added
added:docs/index.md+88 added
1# HTTP323<a href="https://travis-ci.org/encode/http3">4 <img src="https://travis-ci.org/encode/http3.svg?branch=master" alt="Build Status">5</a>6<a href="https://codecov.io/gh/encode/http3">7 <img src="https://codecov.io/gh/encode/http3/branch/master/graph/badge.svg" alt="Coverage">8</a>9<a href="https://pypi.org/project/http3/">10 <img src="https://badge.fury.io/py/http3.svg" alt="Package version">11</a>1213HTTP3 is a next-generation HTTP client for Python.1415!!! warning16 This project should be considered as an "alpha" release. It is substantially17 API complete, but there are still some areas that need more work.1819---2021Let's get started...2223```python24>>> import http325>>> r = http3.get('https://www.example.org/')26>>> r.status_code27<StatusCode.OK: 200>28>>> r.protocol29'HTTP/2'30>>> r.headers['content-type']31'text/html; charset=UTF-8'32>>> r.text33'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'34```3536## Features3738HTTP3 builds on the well-established usability of `requests`, and gives you:3940* A requests-compatible API.41* HTTP/2 and HTTP/1.1 support.42* Support for issuing HTTP requests in parallel.43* Standard synchronous interface, but with `async`/`await` support if you need it.44* Strict timeouts everywhere.45* Fully type annotated.46* 100% test coverage.4748Plus all the standard features of `requests`...4950* International Domains and URLs51* Keep-Alive & Connection Pooling52* Sessions with Cookie Persistence53* Browser-style SSL Verification54* Basic/Digest Authentication *Digest is still TODO*55* Elegant Key/Value Cookies56* Automatic Decompression57* Automatic Content Decoding58* Unicode Response Bodies59* Multipart File Uploads *TODO*60* HTTP(S) Proxy Support *TODO*61* Connection Timeouts62* Streaming Downloads63* .netrc Support *TODO*64* Chunked Requests6566## Documentation6768For a run-through of all the basics, head over to the [QuickStart](quickstart.md).6970For more advanced topics, see the [Parallel Requests](parallel.md) or [Async Client](async.md) documentation.7172The [Developer Interface](api.md) provides a comprehensive API reference.7374## Dependencies7576The HTTP3 project relies on these excellent libraries:7778* `h2` - HTTP/2 support.79* `h11` - HTTP/1.1 support.80* `certifi` - SSL certificates.81* `chardet` - Fallback auto-detection for response encoding.82* `idna` - Internationalized domain name support.83* `rfc3986` - URL parsing & normalization.84* `brotlipy` - Decoding for "brotli" compressed responses. *(Optional)*8586A huge amount of credit is due to `requests` for the API layout that87much of this work follows, as well as to `urllib3` for plenty of design88inspiration around the lower level networking details.
added:docs/parallel.md+66 added
added:docs/quickstart.md+270 added
1# QuickStart23!!! note4 This page closely follows the layout of the `requests` QuickStart documentation.5 The `http3` library is designed to be API compatible with `requests` wherever6 possible.78First start by importing HTTP3:910```11>>> import http312```1314Now, let’s try to get a webpage. For this example, let’s get GitHub’s public timeline:1516```python17>>> r = http3.get('https://api.github.com/events')18```1920Similarly, to make an HTTP POST request:2122```python23>>> r = http3.post('https://httpbin.org/post', data={'key': 'value'})24```2526The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2728```python29>>> r = http3.put('https://httpbin.org/put', data={'key': 'value'})30>>> r = http3.delete('https://httpbin.org/delete')31>>> r = http3.head('https://httpbin.org/get')32>>> r = http3.options('https://httpbin.org/get')33```3435## Passing Parameters in URLs3637To include URL query parameters in the request, use the `params` keyword:3839```python40>>> params = {'key1': 'value1', 'key2': 'value2'}41>>> r = http3.get('https://httpbin.org/get', params=params)42```4344To see how the values get encoding into the URL string, we can inspect the45resulting URL that was used to make the request:4647```python48>>> r.url49URL('https://httpbin.org/get?key2=value2&key1=value1')50```5152You can also pass a list of items as a value:5354```python55>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}56>>> r = http3.get('https://httpbin.org/get', params=params)57>>> r.url58URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')59```6061## Response Content6263HTTP3 will automatically handle decoding the response content into unicode text.6465```python66>>> r = http3.get('https://www.example.org/')67>>> r.text68'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'69```7071You can inspect what encoding has been used to decode the response.7273```python74>>> r.encoding75'UTF-8'76```7778If you need to override the standard behavior and explicitly set the encoding to79use, then you can do that too.8081```python82>>> r.encoding = 'ISO-8859-1'83```8485## Binary Response Content8687The response content can also be accessed as bytes, for non-text responses:8889```python90>>> r.content91b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'92```9394Any `gzip` and `deflate` HTTP response encodings will automatically95be decoded for you. If `brotlipy` is installed, then the `brotli` response96encoding will also be supported.9798For example, to create an image from binary data returned by a request, you can use the following code:99100```python101>>> from PIL import Image102>>> from io import BytesIO103>>> i = Image.open(BytesIO(r.content))104```105106## JSON Response Content107108Often Web API responses will be encoded as JSON.109110```python111>>> r = http3.get('https://api.github.com/events')112>>> r.json()113[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]114```115116## Custom Headers117118To include additional headers in the outgoing request, use the `headers` keyword argument:119120```python121>>> url = 'http://httpbin.org/headers'122>>> headers = {'user-agent': 'my-app/0.0.1'}123>>> r = http3.get(url, headers=headers)124```125126## Sending Form Encoded Data127128Some types of HTTP requests, such as `POST` and `PUT` requests, can include data129in the request body. One common way of including that is as form encoded data,130which is used for HTML forms.131132```python133>>> data = {'key1': 'value1', 'key2': 'value2'}134>>> r = http3.post("https://httpbin.org/post", data=data)135>>> print(r.text)136{137 ...138 "form": {139 "key2": "value2",140 "key1": "value1"141 },142 ...143}144```145146Form encoded data can also include multiple values form a given key.147148```python149>>> data = {'key1': ['value1', 'value2']}150>>> r = http3.post("https://httpbin.org/post", data=data)151>>> print(r.text)152{153 ...154 "form": {155 "key1": [156 "value1",157 "value2"158 ]159 },160 ...161}162```163164## Sending JSON Encoded Data165166Form encoded data is okay if all you need is simple key-value data structure.167For more complicated data structures you'll often want to use JSON encoding instead.168169```python170>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}171>>> r = http3.post("https://httpbin.org/post", json=data)172>>> print(r.text)173{174 ...175 "json": {176 "boolean": true,177 "integer": 123,178 "list": [179 "a",180 "b",181 "c"182 ]183 },184 ...185}186```187188## Sending Binary Request Data189190For other encodings you should use either a `bytes` type, or a generator191that yields `bytes`.192193You'll probably also want to set a custom `Content-Type` header when uploading194binary data.195196## Response Status Codes197198We can inspect the HTTP status code of the response:199200```python201>>> r = http3.get('https://httpbin.org/get')202>>> r.status_code203<StatusCode.OK: 200>204```205206The status code is an integer enum, meaning that the Python representation gives207use some descriptive information, but the value itself can be used as a regular integer.208209```python210>>> r.status_code == 200211True212```213214HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.215216```python217>>> r.status_code == requests.codes.OK218True219```220221We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):222223```python224>>> not_found = http3.get('https://httpbin.org/status/404')225>>> not_found.status_code226<StatusCode.NOT_FOUND: 404>227>>> not_found.raise_for_status()228Traceback (most recent call last):229 File "/Users/tomchristie/GitHub/encode/httpcore/http3/models.py", line 776, in raise_for_status230 raise HttpError(message)231http3.exceptions.HttpError: 404 Not Found232```233234Any successful response codes will simply return `None` rather than raising an exception.235236``` python237>>> r.raise_for_status()238```239240## Response Headers241242The response headers are available as a dictionary-like interface.243244```python245>>> r.headers246Headers({247 'content-encoding': 'gzip',248 'transfer-encoding': 'chunked',249 'connection': 'close',250 'server': 'nginx/1.0.4',251 'x-runtime': '148ms',252 'etag': '"e1ca502697e5c9317743dc078f67693f"',253 'content-type': 'application/json'254})255```256257The `Headers` data type is case-insensitive, so you can use any capitalization.258259```python260>>> r.headers['Content-Type']261'application/json'262263>>> r.headers.get('content-type')264'application/json'265```266267Multiple values for a single response header are represented as a single comma separated268value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):269270> A recipient MAY combine multiple header fields with the same field name into one “field-name: field-value” pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.
added:http3/dispatch/__init__.py+4 added
1"""2Dispatch classes handle the raw network connections and the implementation3details of making the HTTP request and receiving the response.4"""
added:http3/dispatch/connection_pool.py+164 added
1import typing23from ..concurrency import AsyncioBackend4from ..config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_TIMEOUT_CONFIG,8 CertTypes,9 PoolLimits,10 TimeoutTypes,11 VerifyTypes,12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout15from ..interfaces import AsyncDispatcher, ConcurrencyBackend16from ..models import AsyncRequest, AsyncResponse, Origin17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]202122class ConnectionStore:23 """24 We need to maintain collections of connections in a way that allows us to:2526 * Lookup connections by origin.27 * Iterate over connections by insertion time.28 * Return the total number of connections.29 """3031 def __init__(self) -> None:32 self.all = {} # type: typing.Dict[HTTPConnection, float]33 self.by_origin = (34 {}35 ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3637 def pop_by_origin(38 self, origin: Origin, http2_only: bool = False39 ) -> typing.Optional[HTTPConnection]:40 try:41 connections = self.by_origin[origin]42 except KeyError:43 return None4445 connection = next(reversed(list(connections.keys())))46 if http2_only and not connection.is_http2:47 return None4849 del connections[connection]50 if not connections:51 del self.by_origin[origin]52 del self.all[connection]5354 return connection5556 def add(self, connection: HTTPConnection) -> None:57 self.all[connection] = 0.058 try:59 self.by_origin[connection.origin][connection] = 0.060 except KeyError:61 self.by_origin[connection.origin] = {connection: 0.0}6263 def remove(self, connection: HTTPConnection) -> None:64 del self.all[connection]65 del self.by_origin[connection.origin][connection]66 if not self.by_origin[connection.origin]:67 del self.by_origin[connection.origin]6869 def clear(self) -> None:70 self.all.clear()71 self.by_origin.clear()7273 def __iter__(self) -> typing.Iterator[HTTPConnection]:74 return iter(self.all.keys())7576 def __len__(self) -> int:77 return len(self.all)787980class ConnectionPool(AsyncDispatcher):81 def __init__(82 self,83 *,84 verify: VerifyTypes = True,85 cert: CertTypes = None,86 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,87 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,88 backend: ConcurrencyBackend = None,89 ):90 self.verify = verify91 self.cert = cert92 self.timeout = timeout93 self.pool_limits = pool_limits94 self.is_closed = False9596 self.keepalive_connections = ConnectionStore()97 self.active_connections = ConnectionStore()9899 self.backend = AsyncioBackend() if backend is None else backend100 self.max_connections = self.backend.get_semaphore(pool_limits)101102 @property103 def num_connections(self) -> int:104 return len(self.keepalive_connections) + len(self.active_connections)105106 async def send(107 self,108 request: AsyncRequest,109 verify: VerifyTypes = None,110 cert: CertTypes = None,111 timeout: TimeoutTypes = None,112 ) -> AsyncResponse:113 connection = await self.acquire_connection(request.url.origin)114 try:115 response = await connection.send(116 request, verify=verify, cert=cert, timeout=timeout117 )118 except BaseException as exc:119 self.active_connections.remove(connection)120 self.max_connections.release()121 raise exc122 return response123124 async def acquire_connection(self, origin: Origin) -> HTTPConnection:125 connection = self.active_connections.pop_by_origin(origin, http2_only=True)126 if connection is None:127 connection = self.keepalive_connections.pop_by_origin(origin)128129 if connection is None:130 await self.max_connections.acquire()131 connection = HTTPConnection(132 origin,133 verify=self.verify,134 cert=self.cert,135 timeout=self.timeout,136 backend=self.backend,137 release_func=self.release_connection,138 )139140 self.active_connections.add(connection)141142 return connection143144 async def release_connection(self, connection: HTTPConnection) -> None:145 if connection.is_closed:146 self.active_connections.remove(connection)147 self.max_connections.release()148 elif (149 self.pool_limits.soft_limit is not None150 and self.num_connections > self.pool_limits.soft_limit151 ):152 self.active_connections.remove(connection)153 self.max_connections.release()154 await connection.close()155 else:156 self.active_connections.remove(connection)157 self.keepalive_connections.add(connection)158159 async def close(self) -> None:160 self.is_closed = True161 connections = list(self.keepalive_connections)162 self.keepalive_connections.clear()163 for connection in connections:164 await connection.close()
added:http3/dispatch/connection.py+107 added
1import functools2import typing34import h2.connection5import h1167from ..concurrency import AsyncioBackend8from ..config import (9 DEFAULT_SSL_CONFIG,10 DEFAULT_TIMEOUT_CONFIG,11 CertTypes,12 SSLConfig,13 TimeoutConfig,14 TimeoutTypes,15 VerifyTypes,16)17from ..exceptions import ConnectTimeout18from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol19from ..models import AsyncRequest, AsyncResponse, Origin20from .http2 import HTTP2Connection21from .http11 import HTTP11Connection2223# Callback signature: async def callback(conn: HTTPConnection) -> None24ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]252627class HTTPConnection(AsyncDispatcher):28 def __init__(29 self,30 origin: typing.Union[str, Origin],31 verify: VerifyTypes = True,32 cert: CertTypes = None,33 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,34 backend: ConcurrencyBackend = None,35 release_func: typing.Optional[ReleaseCallback] = None,36 ):37 self.origin = Origin(origin) if isinstance(origin, str) else origin38 self.ssl = SSLConfig(cert=cert, verify=verify)39 self.timeout = TimeoutConfig(timeout)40 self.backend = AsyncioBackend() if backend is None else backend41 self.release_func = release_func42 self.h11_connection = None # type: typing.Optional[HTTP11Connection]43 self.h2_connection = None # type: typing.Optional[HTTP2Connection]4445 async def send(46 self,47 request: AsyncRequest,48 verify: VerifyTypes = None,49 cert: CertTypes = None,50 timeout: TimeoutTypes = None,51 ) -> AsyncResponse:52 if self.h11_connection is None and self.h2_connection is None:53 await self.connect(verify=verify, cert=cert, timeout=timeout)5455 if self.h2_connection is not None:56 response = await self.h2_connection.send(request, timeout=timeout)57 else:58 assert self.h11_connection is not None59 response = await self.h11_connection.send(request, timeout=timeout)6061 return response6263 async def connect(64 self,65 verify: VerifyTypes = None,66 cert: CertTypes = None,67 timeout: TimeoutTypes = None,68 ) -> None:69 ssl = self.ssl.with_overrides(verify=verify, cert=cert)70 timeout = self.timeout if timeout is None else TimeoutConfig(timeout)7172 host = self.origin.host73 port = self.origin.port74 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None7576 if self.release_func is None:77 on_release = None78 else:79 on_release = functools.partial(self.release_func, self)8081 reader, writer, protocol = await self.backend.connect(82 host, port, ssl_context, timeout83 )84 if protocol == Protocol.HTTP_2:85 self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)86 else:87 self.h11_connection = HTTP11Connection(88 reader, writer, on_release=on_release89 )9091 async def close(self) -> None:92 if self.h2_connection is not None:93 await self.h2_connection.close()94 elif self.h11_connection is not None:95 await self.h11_connection.close()9697 @property98 def is_http2(self) -> bool:99 return self.h2_connection is not None100101 @property102 def is_closed(self) -> bool:103 if self.h2_connection is not None:104 return self.h2_connection.is_closed105 else:106 assert self.h11_connection is not None107 return self.h11_connection.is_closed
added:http3/dispatch/http11.py+127 added
1import typing23import h1145from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes6from ..exceptions import ConnectTimeout, ReadTimeout7from ..interfaces import BaseReader, BaseWriter8from ..models import AsyncRequest, AsyncResponse910H11Event = typing.Union[11 h11.Request,12 h11.Response,13 h11.InformationalResponse,14 h11.Data,15 h11.EndOfMessage,16 h11.ConnectionClosed,17]181920# Callback signature: async def callback() -> None21# In practice the callback will be a functools partial, which binds22# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.23OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]242526class HTTP11Connection:27 READ_NUM_BYTES = 40962829 def __init__(30 self,31 reader: BaseReader,32 writer: BaseWriter,33 on_release: typing.Optional[OnReleaseCallback] = None,34 ):35 self.reader = reader36 self.writer = writer37 self.on_release = on_release38 self.h11_state = h11.Connection(our_role=h11.CLIENT)3940 async def send(41 self, request: AsyncRequest, timeout: TimeoutTypes = None42 ) -> AsyncResponse:43 timeout = None if timeout is None else TimeoutConfig(timeout)4445 #  Start sending the request.46 method = request.method.encode("ascii")47 target = request.url.full_path.encode("ascii")48 headers = request.headers.raw49 if "Host" not in request.headers:50 host = request.url.authority.encode("ascii")51 headers = [(b"host", host)] + headers52 event = h11.Request(method=method, target=target, headers=headers)53 await self._send_event(event, timeout)5455 # Send the request body.56 async for data in request.stream():57 event = h11.Data(data=data)58 await self._send_event(event, timeout)5960 # Finalize sending the request.61 event = h11.EndOfMessage()62 await self._send_event(event, timeout)6364 # Start getting the response.65 event = await self._receive_event(timeout)66 if isinstance(event, h11.InformationalResponse):67 event = await self._receive_event(timeout)6869 assert isinstance(event, h11.Response)70 reason_phrase = event.reason.decode("ascii", errors="ignore")71 status_code = event.status_code72 headers = event.headers73 content = self._body_iter(timeout)7475 return AsyncResponse(76 status_code=status_code,77 reason_phrase=reason_phrase,78 protocol="HTTP/1.1",79 headers=headers,80 content=content,81 on_close=self.response_closed,82 request=request,83 )8485 async def close(self) -> None:86 event = h11.ConnectionClosed()87 self.h11_state.send(event)88 await self.writer.close()8990 async def _body_iter(91 self, timeout: TimeoutConfig = None92 ) -> typing.AsyncIterator[bytes]:93 event = await self._receive_event(timeout)94 while isinstance(event, h11.Data):95 yield event.data96 event = await self._receive_event(timeout)97 assert isinstance(event, h11.EndOfMessage)9899 async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:100 data = self.h11_state.send(event)101 await self.writer.write(data, timeout)102103 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:104 event = self.h11_state.next_event()105106 while event is h11.NEED_DATA:107 data = await self.reader.read(self.READ_NUM_BYTES, timeout)108 self.h11_state.receive_data(data)109 event = self.h11_state.next_event()110111 return event112113 async def response_closed(self) -> None:114 if (115 self.h11_state.our_state is h11.DONE116 and self.h11_state.their_state is h11.DONE117 ):118 self.h11_state.start_next_cycle()119 else:120 await self.close()121122 if self.on_release is not None:123 await self.on_release()124125 @property126 def is_closed(self) -> bool:127 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)
added:http3/dispatch/http2.py+141 added
1import functools2import typing34import h2.connection5import h2.events67from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes8from ..exceptions import ConnectTimeout, ReadTimeout9from ..interfaces import BaseReader, BaseWriter10from ..models import AsyncRequest, AsyncResponse111213class HTTP2Connection:14 READ_NUM_BYTES = 40961516 def __init__(17 self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None18 ):19 self.reader = reader20 self.writer = writer21 self.on_release = on_release22 self.h2_state = h2.connection.H2Connection()23 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]24 self.initialized = False2526 async def send(27 self, request: AsyncRequest, timeout: TimeoutTypes = None28 ) -> AsyncResponse:29 timeout = None if timeout is None else TimeoutConfig(timeout)3031 #  Start sending the request.32 if not self.initialized:33 self.initiate_connection()3435 stream_id = await self.send_headers(request, timeout)36 self.events[stream_id] = []3738 # Send the request body.39 async for data in request.stream():40 await self.send_data(stream_id, data, timeout)4142 # Finalize sending the request.43 await self.end_stream(stream_id, timeout)4445 # Start getting the response.46 while True:47 event = await self.receive_event(stream_id, timeout)48 if isinstance(event, h2.events.ResponseReceived):49 break5051 status_code = 20052 headers = []53 for k, v in event.headers:54 if k == b":status":55 status_code = int(v.decode("ascii", errors="ignore"))56 elif not k.startswith(b":"):57 headers.append((k, v))5859 content = self.body_iter(stream_id, timeout)60 on_close = functools.partial(self.response_closed, stream_id=stream_id)6162 return AsyncResponse(63 status_code=status_code,64 protocol="HTTP/2",65 headers=headers,66 content=content,67 on_close=on_close,68 request=request,69 )7071 async def close(self) -> None:72 await self.writer.close()7374 def initiate_connection(self) -> None:75 self.h2_state.initiate_connection()76 data_to_send = self.h2_state.data_to_send()77 self.writer.write_no_block(data_to_send)78 self.initialized = True7980 async def send_headers(81 self, request: AsyncRequest, timeout: TimeoutConfig = None82 ) -> int:83 stream_id = self.h2_state.get_next_available_stream_id()84 headers = [85 (b":method", request.method.encode("ascii")),86 (b":authority", request.url.authority.encode("ascii")),87 (b":scheme", request.url.scheme.encode("ascii")),88 (b":path", request.url.full_path.encode("ascii")),89 ] + request.headers.raw90 self.h2_state.send_headers(stream_id, headers)91 data_to_send = self.h2_state.data_to_send()92 await self.writer.write(data_to_send, timeout)93 return stream_id9495 async def send_data(96 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None97 ) -> None:98 self.h2_state.send_data(stream_id, data)99 data_to_send = self.h2_state.data_to_send()100 await self.writer.write(data_to_send, timeout)101102 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:103 self.h2_state.end_stream(stream_id)104 data_to_send = self.h2_state.data_to_send()105 await self.writer.write(data_to_send, timeout)106107 async def body_iter(108 self, stream_id: int, timeout: TimeoutConfig = None109 ) -> typing.AsyncIterator[bytes]:110 while True:111 event = await self.receive_event(stream_id, timeout)112 if isinstance(event, h2.events.DataReceived):113 self.h2_state.acknowledge_received_data(len(event.data), stream_id)114 yield event.data115 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):116 break117118 async def receive_event(119 self, stream_id: int, timeout: TimeoutConfig = None120 ) -> h2.events.Event:121 while not self.events[stream_id]:122 data = await self.reader.read(self.READ_NUM_BYTES, timeout)123 events = self.h2_state.receive_data(data)124 for event in events:125 if getattr(event, "stream_id", 0):126 self.events[event.stream_id].append(event)127128 data_to_send = self.h2_state.data_to_send()129 await self.writer.write(data_to_send, timeout)130131 return self.events[stream_id].pop(0)132133 async def response_closed(self, stream_id: int) -> None:134 del self.events[stream_id]135136 if not self.events and self.on_release is not None:137 await self.on_release()138139 @property140 def is_closed(self) -> bool:141 return False
added:http3/dispatch/threaded.py+97 added
1from ..config import CertTypes, TimeoutTypes, VerifyTypes2from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3from ..models import (4 AsyncRequest,5 AsyncRequestData,6 AsyncResponse,7 AsyncResponseContent,8 Request,9 RequestData,10 Response,11 ResponseContent,12)131415class ThreadedDispatcher(AsyncDispatcher):16 """17 The ThreadedDispatcher class is used to mediate between the Client18 (which always uses async under the hood), and a synchronous `Dispatch`19 class.20 """2122 def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23 self.sync_dispatcher = dispatch24 self.backend = backend2526 async def send(27 self,28 request: AsyncRequest,29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,32 ) -> AsyncResponse:33 concurrency_backend = self.backend3435 data = getattr(request, "content", getattr(request, "content_aiter", None))36 sync_data = self._sync_request_data(data)3738 sync_request = Request(39 method=request.method,40 url=request.url,41 headers=request.headers,42 data=sync_data,43 )4445 func = self.sync_dispatcher.send46 kwargs = {47 "request": sync_request,48 "verify": verify,49 "cert": cert,50 "timeout": timeout,51 }52 sync_response = await self.backend.run_in_threadpool(func, **kwargs)53 assert isinstance(sync_response, Response)5455 content = getattr(56 sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57 )5859 async_content = self._async_response_content(content)6061 async def async_on_close() -> None:62 nonlocal concurrency_backend, sync_response63 await concurrency_backend.run_in_threadpool(sync_response.close)6465 return AsyncResponse(66 status_code=sync_response.status_code,67 reason_phrase=sync_response.reason_phrase,68 protocol=sync_response.protocol,69 headers=sync_response.headers,70 content=async_content,71 on_close=async_on_close,72 request=request,73 history=sync_response.history,74 )7576 async def close(self) -> None:77 """78 The `.close()` method runs the `Dispatcher.close()` within a threadpool,79 so as not to block the async event loop.80 """81 func = self.sync_dispatcher.close82 await self.backend.run_in_threadpool(func)8384 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85 if isinstance(content, bytes):86 return content8788 # Coerce an async iterator into an iterator, with each item in the89 # iteration run within the event loop.90 assert hasattr(content, "__iter__")91 return self.backend.iterate_in_threadpool(content)9293 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94 if isinstance(data, bytes):95 return data9697 return self.backend.iterate(data)
added:http3/__init__.py+52 added
1from .api import delete, get, head, options, patch, post, put, request2from .client import AsyncClient, Client3from .concurrency import AsyncioBackend4from .config import (5 CertTypes,6 PoolLimits,7 SSLConfig,8 TimeoutConfig,9 TimeoutTypes,10 VerifyTypes,11)12from .dispatch.connection import HTTPConnection13from .dispatch.connection_pool import ConnectionPool14from .exceptions import (15 ConnectTimeout,16 CookieConflict,17 DecodingError,18 InvalidURL,19 PoolTimeout,20 ProtocolError,21 ReadTimeout,22 RedirectBodyUnavailable,23 RedirectLoop,24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27 Timeout,28 TooManyRedirects,29 WriteTimeout,30)31from .interfaces import (32 AsyncDispatcher,33 BaseReader,34 BaseWriter,35 ConcurrencyBackend,36 Dispatcher,37 Protocol,38)39from .models import (40 URL,41 AsyncRequest,42 AsyncResponse,43 Cookies,44 Headers,45 Origin,46 QueryParams,47 Request,48 Response,49)50from .status_codes import StatusCode, codes5152__version__ = "0.0.1"
added:http3/api.py+261 added
1import typing23from .client import Client4from .config import CertTypes, TimeoutTypes, VerifyTypes5from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 RequestData,11 Response,12 URLTypes,13)141516def request(17 method: str,18 url: URLTypes,19 *,20 params: QueryParamTypes = None,21 data: RequestData = b"",22 json: typing.Any = None,23 headers: HeaderTypes = None,24 cookies: CookieTypes = None,25 # files26 auth: AuthTypes = None,27 timeout: TimeoutTypes = None,28 allow_redirects: bool = True,29 # proxies30 cert: CertTypes = None,31 verify: VerifyTypes = True,32 stream: bool = False,33) -> Response:34 with Client() as client:35 return client.request(36 method=method,37 url=url,38 data=data,39 json=json,40 params=params,41 headers=headers,42 cookies=cookies,43 stream=stream,44 auth=auth,45 allow_redirects=allow_redirects,46 cert=cert,47 verify=verify,48 timeout=timeout,49 )505152def get(53 url: URLTypes,54 *,55 params: QueryParamTypes = None,56 headers: HeaderTypes = None,57 cookies: CookieTypes = None,58 stream: bool = False,59 auth: AuthTypes = None,60 allow_redirects: bool = True,61 cert: CertTypes = None,62 verify: VerifyTypes = True,63 timeout: TimeoutTypes = None,64) -> Response:65 return request(66 "GET",67 url,68 params=params,69 headers=headers,70 cookies=cookies,71 stream=stream,72 auth=auth,73 allow_redirects=allow_redirects,74 cert=cert,75 verify=verify,76 timeout=timeout,77 )787980def options(81 url: URLTypes,82 *,83 params: QueryParamTypes = None,84 headers: HeaderTypes = None,85 cookies: CookieTypes = None,86 stream: bool = False,87 auth: AuthTypes = None,88 allow_redirects: bool = True,89 cert: CertTypes = None,90 verify: VerifyTypes = True,91 timeout: TimeoutTypes = None,92) -> Response:93 return request(94 "OPTIONS",95 url,96 params=params,97 headers=headers,98 cookies=cookies,99 stream=stream,100 auth=auth,101 allow_redirects=allow_redirects,102 cert=cert,103 verify=verify,104 timeout=timeout,105 )106107108def head(109 url: URLTypes,110 *,111 params: QueryParamTypes = None,112 headers: HeaderTypes = None,113 cookies: CookieTypes = None,114 stream: bool = False,115 auth: AuthTypes = None,116 allow_redirects: bool = False, #  Note: Differs to usual default.117 cert: CertTypes = None,118 verify: VerifyTypes = True,119 timeout: TimeoutTypes = None,120) -> Response:121 return request(122 "HEAD",123 url,124 params=params,125 headers=headers,126 cookies=cookies,127 stream=stream,128 auth=auth,129 allow_redirects=allow_redirects,130 cert=cert,131 verify=verify,132 timeout=timeout,133 )134135136def post(137 url: URLTypes,138 *,139 data: RequestData = b"",140 json: typing.Any = None,141 params: QueryParamTypes = None,142 headers: HeaderTypes = None,143 cookies: CookieTypes = None,144 stream: bool = False,145 auth: AuthTypes = None,146 allow_redirects: bool = True,147 cert: CertTypes = None,148 verify: VerifyTypes = True,149 timeout: TimeoutTypes = None,150) -> Response:151 return request(152 "POST",153 url,154 data=data,155 json=json,156 params=params,157 headers=headers,158 cookies=cookies,159 stream=stream,160 auth=auth,161 allow_redirects=allow_redirects,162 cert=cert,163 verify=verify,164 timeout=timeout,165 )166167168def put(169 url: URLTypes,170 *,171 data: RequestData = b"",172 json: typing.Any = None,173 params: QueryParamTypes = None,174 headers: HeaderTypes = None,175 cookies: CookieTypes = None,176 stream: bool = False,177 auth: AuthTypes = None,178 allow_redirects: bool = True,179 cert: CertTypes = None,180 verify: VerifyTypes = True,181 timeout: TimeoutTypes = None,182) -> Response:183 return request(184 "PUT",185 url,186 data=data,187 json=json,188 params=params,189 headers=headers,190 cookies=cookies,191 stream=stream,192 auth=auth,193 allow_redirects=allow_redirects,194 cert=cert,195 verify=verify,196 timeout=timeout,197 )198199200def patch(201 url: URLTypes,202 *,203 data: RequestData = b"",204 json: typing.Any = None,205 params: QueryParamTypes = None,206 headers: HeaderTypes = None,207 cookies: CookieTypes = None,208 stream: bool = False,209 auth: AuthTypes = None,210 allow_redirects: bool = True,211 cert: CertTypes = None,212 verify: VerifyTypes = True,213 timeout: TimeoutTypes = None,214) -> Response:215 return request(216 "PATCH",217 url,218 data=data,219 json=json,220 params=params,221 headers=headers,222 cookies=cookies,223 stream=stream,224 auth=auth,225 allow_redirects=allow_redirects,226 cert=cert,227 verify=verify,228 timeout=timeout,229 )230231232def delete(233 url: URLTypes,234 *,235 data: RequestData = b"",236 json: typing.Any = None,237 params: QueryParamTypes = None,238 headers: HeaderTypes = None,239 cookies: CookieTypes = None,240 stream: bool = False,241 auth: AuthTypes = None,242 allow_redirects: bool = True,243 cert: CertTypes = None,244 verify: VerifyTypes = True,245 timeout: TimeoutTypes = None,246) -> Response:247 return request(248 "DELETE",249 url,250 data=data,251 json=json,252 params=params,253 headers=headers,254 cookies=cookies,255 stream=stream,256 auth=auth,257 allow_redirects=allow_redirects,258 cert=cert,259 verify=verify,260 timeout=timeout,261 )
added:http3/auth.py+38 added
1import typing2from base64 import b64encode34from .models import AsyncRequest567class AuthBase:8 """9 Base class that all auth implementations derive from.10 """1112 def __call__(self, request: AsyncRequest) -> AsyncRequest:13 raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover141516class HTTPBasicAuth(AuthBase):17 def __init__(18 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]19 ) -> None:20 self.username = username21 self.password = password2223 def __call__(self, request: AsyncRequest) -> AsyncRequest:24 request.headers["Authorization"] = self.build_auth_header()25 return request2627 def build_auth_header(self) -> str:28 username, password = self.username, self.password2930 if isinstance(username, str):31 username = username.encode("latin1")3233 if isinstance(password, str):34 password = password.encode("latin1")3536 userpass = b":".join((username, password))37 token = b64encode(userpass).decode().strip()38 return f"Basic {token}"
added:http3/client.py+831 added
1import typing2from types import TracebackType34from .auth import HTTPBasicAuth5from .concurrency import AsyncioBackend6from .config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_TIMEOUT_CONFIG,10 CertTypes,11 PoolLimits,12 TimeoutTypes,13 VerifyTypes,14)15from .dispatch.connection_pool import ConnectionPool16from .dispatch.threaded import ThreadedDispatcher17from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects18from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher19from .models import (20 URL,21 AsyncRequest,22 AsyncRequestData,23 AsyncResponse,24 AsyncResponseContent,25 AuthTypes,26 Cookies,27 CookieTypes,28 Headers,29 HeaderTypes,30 QueryParamTypes,31 Request,32 RequestData,33 Response,34 ResponseContent,35 URLTypes,36)37from .status_codes import codes383940class BaseClient:41 def __init__(42 self,43 auth: AuthTypes = None,44 cookies: CookieTypes = None,45 verify: VerifyTypes = True,46 cert: CertTypes = None,47 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,48 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,49 max_redirects: int = DEFAULT_MAX_REDIRECTS,50 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,51 backend: ConcurrencyBackend = None,52 ):53 if backend is None:54 backend = AsyncioBackend()5556 if dispatch is None:57 async_dispatch = ConnectionPool(58 verify=verify,59 cert=cert,60 timeout=timeout,61 pool_limits=pool_limits,62 backend=backend,63 ) # type: AsyncDispatcher64 elif isinstance(dispatch, Dispatcher):65 async_dispatch = ThreadedDispatcher(dispatch, backend)66 else:67 async_dispatch = dispatch6869 self.auth = auth70 self.cookies = Cookies(cookies)71 self.max_redirects = max_redirects72 self.dispatch = async_dispatch73 self.concurrency_backend = backend7475 def merge_cookies(76 self, cookies: CookieTypes = None77 ) -> typing.Optional[CookieTypes]:78 if cookies or self.cookies:79 merged_cookies = Cookies(self.cookies)80 merged_cookies.update(cookies)81 return merged_cookies82 return cookies8384 async def send(85 self,86 request: AsyncRequest,87 *,88 stream: bool = False,89 auth: AuthTypes = None,90 allow_redirects: bool = True,91 verify: VerifyTypes = None,92 cert: CertTypes = None,93 timeout: TimeoutTypes = None,94 ) -> AsyncResponse:95 if auth is None:96 auth = self.auth9798 url = request.url99 if auth is None and (url.username or url.password):100 auth = HTTPBasicAuth(username=url.username, password=url.password)101102 if auth is not None:103 if isinstance(auth, tuple):104 auth = HTTPBasicAuth(username=auth[0], password=auth[1])105 request = auth(request)106107 response = await self.send_handling_redirects(108 request,109 verify=verify,110 cert=cert,111 timeout=timeout,112 allow_redirects=allow_redirects,113 )114115 if not stream:116 try:117 await response.read()118 finally:119 await response.close()120121 return response122123 async def send_handling_redirects(124 self,125 request: AsyncRequest,126 *,127 cert: CertTypes = None,128 verify: VerifyTypes = None,129 timeout: TimeoutTypes = None,130 allow_redirects: bool = True,131 history: typing.List[AsyncResponse] = None,132 ) -> AsyncResponse:133 if history is None:134 history = []135136 while True:137 # We perform these checks here, so that calls to `response.next()`138 # will raise redirect errors if appropriate.139 if len(history) > self.max_redirects:140 raise TooManyRedirects()141 if request.url in [response.url for response in history]:142 raise RedirectLoop()143144 response = await self.dispatch.send(145 request, verify=verify, cert=cert, timeout=timeout146 )147 assert isinstance(response, AsyncResponse)148 response.history = list(history)149 self.cookies.extract_cookies(response)150 history = [response] + history151 if not response.is_redirect:152 break153154 if allow_redirects:155 request = self.build_redirect_request(request, response)156 else:157158 async def send_next() -> AsyncResponse:159 nonlocal request, response, verify, cert, allow_redirects, timeout, history160 request = self.build_redirect_request(request, response)161 response = await self.send_handling_redirects(162 request,163 allow_redirects=allow_redirects,164 verify=verify,165 cert=cert,166 timeout=timeout,167 history=history,168 )169 return response170171 response.next = send_next # type: ignore172 break173174 return response175176 def build_redirect_request(177 self, request: AsyncRequest, response: AsyncResponse178 ) -> AsyncRequest:179 method = self.redirect_method(request, response)180 url = self.redirect_url(request, response)181 headers = self.redirect_headers(request, url)182 content = self.redirect_content(request, method)183 cookies = self.merge_cookies(request.cookies)184 return AsyncRequest(185 method=method, url=url, headers=headers, data=content, cookies=cookies186 )187188 def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:189 """190 When being redirected we may want to change the method of the request191 based on certain specs or browser behavior.192 """193 method = request.method194195 # https://tools.ietf.org/html/rfc7231#section-6.4.4196 if response.status_code == codes.SEE_OTHER and method != "HEAD":197 method = "GET"198199 # Do what the browsers do, despite standards...200 # Turn 302s into GETs.201 if response.status_code == codes.FOUND and method != "HEAD":202 method = "GET"203204 # If a POST is responded to with a 301, turn it into a GET.205 # This bizarre behaviour is explained in 'requests' issue 1704.206 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":207 method = "GET"208209 return method210211 def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:212 """213 Return the URL for the redirect to follow.214 """215 location = response.headers["Location"]216217 url = URL(location, allow_relative=True)218219 # Facilitate relative 'Location' headers, as allowed by RFC 7231.220 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')221 if url.is_relative_url:222 url = url.resolve_with(request.url)223224 # Attach previous fragment if needed (RFC 7231 7.1.2)225 if request.url.fragment and not url.fragment:226 url = url.copy_with(fragment=request.url.fragment)227228 return url229230 def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:231 """232 Strip Authorization headers when responses are redirected away from233 the origin.234 """235 headers = Headers(request.headers)236 if url.origin != request.url.origin:237 del headers["Authorization"]238 return headers239240 def redirect_content(self, request: AsyncRequest, method: str) -> bytes:241 """242 Return the body that should be used for the redirect request.243 """244 if method != request.method and method == "GET":245 return b""246 if request.is_streaming:247 raise RedirectBodyUnavailable()248 return request.content249250251class AsyncClient(BaseClient):252 async def get(253 self,254 url: URLTypes,255 *,256 params: QueryParamTypes = None,257 headers: HeaderTypes = None,258 cookies: CookieTypes = None,259 stream: bool = False,260 auth: AuthTypes = None,261 allow_redirects: bool = True,262 cert: CertTypes = None,263 verify: VerifyTypes = None,264 timeout: TimeoutTypes = None,265 ) -> AsyncResponse:266 return await self.request(267 "GET",268 url,269 params=params,270 headers=headers,271 cookies=cookies,272 stream=stream,273 auth=auth,274 allow_redirects=allow_redirects,275 verify=verify,276 cert=cert,277 timeout=timeout,278 )279280 async def options(281 self,282 url: URLTypes,283 *,284 params: QueryParamTypes = None,285 headers: HeaderTypes = None,286 cookies: CookieTypes = None,287 stream: bool = False,288 auth: AuthTypes = None,289 allow_redirects: bool = True,290 cert: CertTypes = None,291 verify: VerifyTypes = None,292 timeout: TimeoutTypes = None,293 ) -> AsyncResponse:294 return await self.request(295 "OPTIONS",296 url,297 params=params,298 headers=headers,299 cookies=cookies,300 stream=stream,301 auth=auth,302 allow_redirects=allow_redirects,303 verify=verify,304 cert=cert,305 timeout=timeout,306 )307308 async def head(309 self,310 url: URLTypes,311 *,312 params: QueryParamTypes = None,313 headers: HeaderTypes = None,314 cookies: CookieTypes = None,315 stream: bool = False,316 auth: AuthTypes = None,317 allow_redirects: bool = False, #  Note: Differs to usual default.318 cert: CertTypes = None,319 verify: VerifyTypes = None,320 timeout: TimeoutTypes = None,321 ) -> AsyncResponse:322 return await self.request(323 "HEAD",324 url,325 params=params,326 headers=headers,327 cookies=cookies,328 stream=stream,329 auth=auth,330 allow_redirects=allow_redirects,331 verify=verify,332 cert=cert,333 timeout=timeout,334 )335336 async def post(337 self,338 url: URLTypes,339 *,340 data: AsyncRequestData = b"",341 json: typing.Any = None,342 params: QueryParamTypes = None,343 headers: HeaderTypes = None,344 cookies: CookieTypes = None,345 stream: bool = False,346 auth: AuthTypes = None,347 allow_redirects: bool = True,348 cert: CertTypes = None,349 verify: VerifyTypes = None,350 timeout: TimeoutTypes = None,351 ) -> AsyncResponse:352 return await self.request(353 "POST",354 url,355 data=data,356 json=json,357 params=params,358 headers=headers,359 cookies=cookies,360 stream=stream,361 auth=auth,362 allow_redirects=allow_redirects,363 verify=verify,364 cert=cert,365 timeout=timeout,366 )367368 async def put(369 self,370 url: URLTypes,371 *,372 data: AsyncRequestData = b"",373 json: typing.Any = None,374 params: QueryParamTypes = None,375 headers: HeaderTypes = None,376 cookies: CookieTypes = None,377 stream: bool = False,378 auth: AuthTypes = None,379 allow_redirects: bool = True,380 cert: CertTypes = None,381 verify: VerifyTypes = None,382 timeout: TimeoutTypes = None,383 ) -> AsyncResponse:384 return await self.request(385 "PUT",386 url,387 data=data,388 json=json,389 params=params,390 headers=headers,391 cookies=cookies,392 stream=stream,393 auth=auth,394 allow_redirects=allow_redirects,395 verify=verify,396 cert=cert,397 timeout=timeout,398 )399400 async def patch(401 self,402 url: URLTypes,403 *,404 data: AsyncRequestData = b"",405 json: typing.Any = None,406 params: QueryParamTypes = None,407 headers: HeaderTypes = None,408 cookies: CookieTypes = None,409 stream: bool = False,410 auth: AuthTypes = None,411 allow_redirects: bool = True,412 cert: CertTypes = None,413 verify: VerifyTypes = None,414 timeout: TimeoutTypes = None,415 ) -> AsyncResponse:416 return await self.request(417 "PATCH",418 url,419 data=data,420 json=json,421 params=params,422 headers=headers,423 cookies=cookies,424 stream=stream,425 auth=auth,426 allow_redirects=allow_redirects,427 verify=verify,428 cert=cert,429 timeout=timeout,430 )431432 async def delete(433 self,434 url: URLTypes,435 *,436 data: AsyncRequestData = b"",437 json: typing.Any = None,438 params: QueryParamTypes = None,439 headers: HeaderTypes = None,440 cookies: CookieTypes = None,441 stream: bool = False,442 auth: AuthTypes = None,443 allow_redirects: bool = True,444 cert: CertTypes = None,445 verify: VerifyTypes = None,446 timeout: TimeoutTypes = None,447 ) -> AsyncResponse:448 return await self.request(449 "DELETE",450 url,451 data=data,452 json=json,453 params=params,454 headers=headers,455 cookies=cookies,456 stream=stream,457 auth=auth,458 allow_redirects=allow_redirects,459 verify=verify,460 cert=cert,461 timeout=timeout,462 )463464 async def request(465 self,466 method: str,467 url: URLTypes,468 *,469 data: AsyncRequestData = b"",470 json: typing.Any = None,471 params: QueryParamTypes = None,472 headers: HeaderTypes = None,473 cookies: CookieTypes = None,474 stream: bool = False,475 auth: AuthTypes = None,476 allow_redirects: bool = True,477 cert: CertTypes = None,478 verify: VerifyTypes = None,479 timeout: TimeoutTypes = None,480 ) -> AsyncResponse:481 request = AsyncRequest(482 method,483 url,484 data=data,485 json=json,486 params=params,487 headers=headers,488 cookies=self.merge_cookies(cookies),489 )490 response = await self.send(491 request,492 stream=stream,493 auth=auth,494 allow_redirects=allow_redirects,495 verify=verify,496 cert=cert,497 timeout=timeout,498 )499 return response500501 async def close(self) -> None:502 await self.dispatch.close()503504 async def __aenter__(self) -> "AsyncClient":505 return self506507 async def __aexit__(508 self,509 exc_type: typing.Type[BaseException] = None,510 exc_value: BaseException = None,511 traceback: TracebackType = None,512 ) -> None:513 await self.close()514515516class Client(BaseClient):517 def _async_request_data(self, data: RequestData) -> AsyncRequestData:518 """519 If the request data is an bytes iterator then return an async bytes520 iterator onto the request data.521 """522 if isinstance(data, (bytes, dict)):523 return data524525 # Coerce an iterator into an async iterator, with each item in the526 # iteration running as a thread-pooled operation.527 assert hasattr(data, "__iter__")528 return self.concurrency_backend.iterate_in_threadpool(data)529530 def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:531 if isinstance(data, bytes):532 return data533534 # Coerce an async iterator into an iterator, with each item in the535 # iteration run within the event loop.536 assert hasattr(data, "__aiter__")537 return self.concurrency_backend.iterate(data)538539 def request(540 self,541 method: str,542 url: URLTypes,543 *,544 data: RequestData = b"",545 json: typing.Any = None,546 params: QueryParamTypes = None,547 headers: HeaderTypes = None,548 cookies: CookieTypes = None,549 stream: bool = False,550 auth: AuthTypes = None,551 allow_redirects: bool = True,552 cert: CertTypes = None,553 verify: VerifyTypes = None,554 timeout: TimeoutTypes = None,555 ) -> Response:556 request = AsyncRequest(557 method,558 url,559 data=self._async_request_data(data),560 json=json,561 params=params,562 headers=headers,563 cookies=self.merge_cookies(cookies),564 )565 concurrency_backend = self.concurrency_backend566567 coroutine = self.send568 args = [request]569 kwargs = dict(570 stream=True,571 auth=auth,572 allow_redirects=allow_redirects,573 verify=verify,574 cert=cert,575 timeout=timeout,576 )577 async_response = concurrency_backend.run(coroutine, *args, **kwargs)578579 content = getattr(580 async_response, "_raw_content", getattr(async_response, "_raw_stream", None)581 )582583 sync_content = self._sync_data(content)584585 def sync_on_close() -> None:586 nonlocal concurrency_backend, async_response587 concurrency_backend.run(async_response.on_close)588589 response = Response(590 status_code=async_response.status_code,591 reason_phrase=async_response.reason_phrase,592 protocol=async_response.protocol,593 headers=async_response.headers,594 content=sync_content,595 on_close=sync_on_close,596 request=async_response.request,597 history=async_response.history,598 )599 if not stream:600 try:601 response.read()602 finally:603 response.close()604 return response605606 def get(607 self,608 url: URLTypes,609 *,610 params: QueryParamTypes = None,611 headers: HeaderTypes = None,612 cookies: CookieTypes = None,613 stream: bool = False,614 auth: AuthTypes = None,615 allow_redirects: bool = True,616 cert: CertTypes = None,617 verify: VerifyTypes = None,618 timeout: TimeoutTypes = None,619 ) -> Response:620 return self.request(621 "GET",622 url,623 params=params,624 headers=headers,625 cookies=cookies,626 stream=stream,627 auth=auth,628 allow_redirects=allow_redirects,629 verify=verify,630 cert=cert,631 timeout=timeout,632 )633634 def options(635 self,636 url: URLTypes,637 *,638 params: QueryParamTypes = None,639 headers: HeaderTypes = None,640 cookies: CookieTypes = None,641 stream: bool = False,642 auth: AuthTypes = None,643 allow_redirects: bool = True,644 cert: CertTypes = None,645 verify: VerifyTypes = None,646 timeout: TimeoutTypes = None,647 ) -> Response:648 return self.request(649 "OPTIONS",650 url,651 params=params,652 headers=headers,653 cookies=cookies,654 stream=stream,655 auth=auth,656 allow_redirects=allow_redirects,657 verify=verify,658 cert=cert,659 timeout=timeout,660 )661662 def head(663 self,664 url: URLTypes,665 *,666 params: QueryParamTypes = None,667 headers: HeaderTypes = None,668 cookies: CookieTypes = None,669 stream: bool = False,670 auth: AuthTypes = None,671 allow_redirects: bool = False, #  Note: Differs to usual default.672 cert: CertTypes = None,673 verify: VerifyTypes = None,674 timeout: TimeoutTypes = None,675 ) -> Response:676 return self.request(677 "HEAD",678 url,679 params=params,680 headers=headers,681 cookies=cookies,682 stream=stream,683 auth=auth,684 allow_redirects=allow_redirects,685 verify=verify,686 cert=cert,687 timeout=timeout,688 )689690 def post(691 self,692 url: URLTypes,693 *,694 data: RequestData = b"",695 json: typing.Any = None,696 params: QueryParamTypes = None,697 headers: HeaderTypes = None,698 cookies: CookieTypes = None,699 stream: bool = False,700 auth: AuthTypes = None,701 allow_redirects: bool = True,702 cert: CertTypes = None,703 verify: VerifyTypes = None,704 timeout: TimeoutTypes = None,705 ) -> Response:706 return self.request(707 "POST",708 url,709 data=data,710 json=json,711 params=params,712 headers=headers,713 cookies=cookies,714 stream=stream,715 auth=auth,716 allow_redirects=allow_redirects,717 verify=verify,718 cert=cert,719 timeout=timeout,720 )721722 def put(723 self,724 url: URLTypes,725 *,726 data: RequestData = b"",727 json: typing.Any = None,728 params: QueryParamTypes = None,729 headers: HeaderTypes = None,730 cookies: CookieTypes = None,731 stream: bool = False,732 auth: AuthTypes = None,733 allow_redirects: bool = True,734 cert: CertTypes = None,735 verify: VerifyTypes = None,736 timeout: TimeoutTypes = None,737 ) -> Response:738 return self.request(739 "PUT",740 url,741 data=data,742 json=json,743 params=params,744 headers=headers,745 cookies=cookies,746 stream=stream,747 auth=auth,748 allow_redirects=allow_redirects,749 verify=verify,750 cert=cert,751 timeout=timeout,752 )753754 def patch(755 self,756 url: URLTypes,757 *,758 data: RequestData = b"",759 json: typing.Any = None,760 params: QueryParamTypes = None,761 headers: HeaderTypes = None,762 cookies: CookieTypes = None,763 stream: bool = False,764 auth: AuthTypes = None,765 allow_redirects: bool = True,766 cert: CertTypes = None,767 verify: VerifyTypes = None,768 timeout: TimeoutTypes = None,769 ) -> Response:770 return self.request(771 "PATCH",772 url,773 data=data,774 json=json,775 params=params,776 headers=headers,777 cookies=cookies,778 stream=stream,779 auth=auth,780 allow_redirects=allow_redirects,781 verify=verify,782 cert=cert,783 timeout=timeout,784 )785786 def delete(787 self,788 url: URLTypes,789 *,790 data: RequestData = b"",791 json: typing.Any = None,792 params: QueryParamTypes = None,793 headers: HeaderTypes = None,794 cookies: CookieTypes = None,795 stream: bool = False,796 auth: AuthTypes = None,797 allow_redirects: bool = True,798 cert: CertTypes = None,799 verify: VerifyTypes = None,800 timeout: TimeoutTypes = None,801 ) -> Response:802 return self.request(803 "DELETE",804 url,805 data=data,806 json=json,807 params=params,808 headers=headers,809 cookies=cookies,810 stream=stream,811 auth=auth,812 allow_redirects=allow_redirects,813 verify=verify,814 cert=cert,815 timeout=timeout,816 )817818 def close(self) -> None:819 coroutine = self.dispatch.close820 self.concurrency_backend.run(coroutine)821822 def __enter__(self) -> "Client":823 return self824825 def __exit__(826 self,827 exc_type: typing.Type[BaseException] = None,828 exc_value: BaseException = None,829 traceback: TracebackType = None,830 ) -> None:831 self.close()
added:http3/concurrency.py+195 added
1"""2The `Reader` and `Writer` classes here provide a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.67These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import functools13import ssl14import typing1516from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18from .interfaces import (19 BasePoolSemaphore,20 BaseReader,21 BaseWriter,22 ConcurrencyBackend,23 Protocol,24)2526SSL_MONKEY_PATCH_APPLIED = False272829def ssl_monkey_patch() -> None:30 """31 Monky-patch for https://bugs.python.org/issue367093233 This prevents console errors when outstanding HTTPS connections34 still exist at the point of exiting.3536 Clients which have been opened using a `with` block, or which have37 had `close()` closed, will not exhibit this issue in the first place.38 """39 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore4041 _write = MonkeyPatch.write4243 def _fixed_write(self, data: bytes) -> None: # type: ignore44 if not self._loop.is_closed():45 _write(self, data)4647 MonkeyPatch.write = _fixed_write484950class Reader(BaseReader):51 def __init__(52 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig53 ) -> None:54 self.stream_reader = stream_reader55 self.timeout = timeout5657 async def read(self, n: int, timeout: TimeoutConfig = None) -> bytes:58 if timeout is None:59 timeout = self.timeout6061 try:62 data = await asyncio.wait_for(63 self.stream_reader.read(n), timeout.read_timeout64 )65 except asyncio.TimeoutError:66 raise ReadTimeout()6768 return data697071class Writer(BaseWriter):72 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):73 self.stream_writer = stream_writer74 self.timeout = timeout7576 def write_no_block(self, data: bytes) -> None:77 self.stream_writer.write(data) # pragma: nocover7879 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:80 if not data:81 return8283 if timeout is None:84 timeout = self.timeout8586 self.stream_writer.write(data)87 try:88 await asyncio.wait_for( # type: ignore89 self.stream_writer.drain(), timeout.write_timeout90 )91 except asyncio.TimeoutError:92 raise WriteTimeout()9394 async def close(self) -> None:95 self.stream_writer.close()969798class PoolSemaphore(BasePoolSemaphore):99 def __init__(self, pool_limits: PoolLimits):100 self.pool_limits = pool_limits101102 @property103 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:104 if not hasattr(self, "_semaphore"):105 max_connections = self.pool_limits.hard_limit106 if max_connections is None:107 self._semaphore = None108 else:109 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)110 return self._semaphore111112 async def acquire(self) -> None:113 if self.semaphore is None:114 return115116 timeout = self.pool_limits.pool_timeout117 try:118 await asyncio.wait_for(self.semaphore.acquire(), timeout)119 except asyncio.TimeoutError:120 raise PoolTimeout()121122 def release(self) -> None:123 if self.semaphore is None:124 return125126 self.semaphore.release()127128129class AsyncioBackend(ConcurrencyBackend):130 def __init__(self) -> None:131 global SSL_MONKEY_PATCH_APPLIED132133 if not SSL_MONKEY_PATCH_APPLIED:134 ssl_monkey_patch()135 SSL_MONKEY_PATCH_APPLIED = True136137 @property138 def loop(self) -> asyncio.AbstractEventLoop:139 if not hasattr(self, "_loop"):140 try:141 self._loop = asyncio.get_event_loop()142 except RuntimeError:143 self._loop = asyncio.new_event_loop()144 return self._loop145146 async def connect(147 self,148 hostname: str,149 port: int,150 ssl_context: typing.Optional[ssl.SSLContext],151 timeout: TimeoutConfig,152 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:153 try:154 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore155 asyncio.open_connection(hostname, port, ssl=ssl_context),156 timeout.connect_timeout,157 )158 except asyncio.TimeoutError:159 raise ConnectTimeout()160161 ssl_object = stream_writer.get_extra_info("ssl_object")162 if ssl_object is None:163 ident = "http/1.1"164 else:165 ident = ssl_object.selected_alpn_protocol()166 if ident is None:167 ident = ssl_object.selected_npn_protocol()168169 reader = Reader(stream_reader=stream_reader, timeout=timeout)170 writer = Writer(stream_writer=stream_writer, timeout=timeout)171 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11172173 return (reader, writer, protocol)174175 async def run_in_threadpool(176 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any177 ) -> typing.Any:178 if kwargs:179 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here180 func = functools.partial(func, **kwargs)181 return await self.loop.run_in_executor(None, func, *args)182183 def run(184 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any185 ) -> typing.Any:186 loop = self.loop187 if loop.is_running():188 self._loop = asyncio.new_event_loop()189 try:190 return self.loop.run_until_complete(coroutine(*args, **kwargs))191 finally:192 self._loop = loop193194 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:195 return PoolSemaphore(limits)
added:http3/config.py+196 added
1import asyncio2import os3import ssl4import typing56import certifi78CertTypes = typing.Union[str, typing.Tuple[str, str]]9VerifyTypes = typing.Union[str, bool]10TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]111213class SSLConfig:14 """15 SSL Configuration.16 """1718 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):19 self.cert = cert20 self.verify = verify2122 def __eq__(self, other: typing.Any) -> bool:23 return (24 isinstance(other, self.__class__)25 and self.cert == other.cert26 and self.verify == other.verify27 )2829 def __repr__(self) -> str:30 class_name = self.__class__.__name__31 return f"{class_name}(cert={self.cert}, verify={self.verify})"3233 def with_overrides(34 self, cert: CertTypes = None, verify: VerifyTypes = None35 ) -> "SSLConfig":36 cert = self.cert if cert is None else cert37 verify = self.verify if verify is None else verify38 if (cert == self.cert) and (verify == self.verify):39 return self40 return SSLConfig(cert=cert, verify=verify)4142 async def load_ssl_context(self) -> ssl.SSLContext:43 if not hasattr(self, "ssl_context"):44 if not self.verify:45 self.ssl_context = self.load_ssl_context_no_verify()46 else:47 # Run the SSL loading in a threadpool, since it makes disk accesses.48 loop = asyncio.get_event_loop()49 self.ssl_context = await loop.run_in_executor(50 None, self.load_ssl_context_verify51 )5253 return self.ssl_context5455 def load_ssl_context_no_verify(self) -> ssl.SSLContext:56 """57 Return an SSL context for unverified connections.58 """59 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)60 context.options |= ssl.OP_NO_SSLv261 context.options |= ssl.OP_NO_SSLv362 context.options |= ssl.OP_NO_COMPRESSION63 context.set_default_verify_paths()64 return context6566 def load_ssl_context_verify(self) -> ssl.SSLContext:67 """68 Return an SSL context for verified connections.69 """70 if isinstance(self.verify, bool):71 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH72 elif os.path.exists(self.verify):73 ca_bundle_path = self.verify74 else:75 raise IOError(76 "Could not find a suitable TLS CA certificate bundle, "77 "invalid path: {}".format(self.verify)78 )7980 context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)8182 context.verify_mode = ssl.CERT_REQUIRED8384 context.options |= ssl.OP_NO_SSLv285 context.options |= ssl.OP_NO_SSLv386 context.options |= ssl.OP_NO_COMPRESSION8788 # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST89 # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the90 # blacklist defined in this section allows only the AES GCM and ChaCha2091 # cipher suites with ephemeral key negotiation.92 context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")9394 if ssl.HAS_ALPN:95 context.set_alpn_protocols(["h2", "http/1.1"])96 if ssl.HAS_NPN:97 context.set_npn_protocols(["h2", "http/1.1"])9899 if os.path.isfile(ca_bundle_path):100 context.load_verify_locations(cafile=ca_bundle_path)101 elif os.path.isdir(ca_bundle_path):102 context.load_verify_locations(capath=ca_bundle_path)103104 if self.cert is not None:105 if isinstance(self.cert, str):106 context.load_cert_chain(certfile=self.cert)107 else:108 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])109110 return context111112113class TimeoutConfig:114 """115 Timeout values.116 """117118 def __init__(119 self,120 timeout: TimeoutTypes = None,121 *,122 connect_timeout: float = None,123 read_timeout: float = None,124 write_timeout: float = None,125 ):126 if timeout is None:127 self.connect_timeout = connect_timeout128 self.read_timeout = read_timeout129 self.write_timeout = write_timeout130 else:131 # Specified as a single timeout value132 assert connect_timeout is None133 assert read_timeout is None134 assert write_timeout is None135 if isinstance(timeout, TimeoutConfig):136 self.connect_timeout = timeout.connect_timeout137 self.read_timeout = timeout.read_timeout138 self.write_timeout = timeout.write_timeout139 elif isinstance(timeout, tuple):140 self.connect_timeout = timeout[0]141 self.read_timeout = timeout[1]142 self.write_timeout = timeout[2]143 else:144 self.connect_timeout = timeout145 self.read_timeout = timeout146 self.write_timeout = timeout147148 def __eq__(self, other: typing.Any) -> bool:149 return (150 isinstance(other, self.__class__)151 and self.connect_timeout == other.connect_timeout152 and self.read_timeout == other.read_timeout153 and self.write_timeout == other.write_timeout154 )155156 def __repr__(self) -> str:157 class_name = self.__class__.__name__158 if len(set([self.connect_timeout, self.read_timeout, self.write_timeout])) == 1:159 return f"{class_name}(timeout={self.connect_timeout})"160 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"161162163class PoolLimits:164 """165 Limits on the number of connections in a connection pool.166 """167168 def __init__(169 self,170 *,171 soft_limit: int = None,172 hard_limit: int = None,173 pool_timeout: float = None,174 ):175 self.soft_limit = soft_limit176 self.hard_limit = hard_limit177 self.pool_timeout = pool_timeout178179 def __eq__(self, other: typing.Any) -> bool:180 return (181 isinstance(other, self.__class__)182 and self.soft_limit == other.soft_limit183 and self.hard_limit == other.hard_limit184 and self.pool_timeout == other.pool_timeout185 )186187 def __repr__(self) -> str:188 class_name = self.__class__.__name__189 return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"190191192DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)193DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)194DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)195DEFAULT_CA_BUNDLE_PATH = certifi.where()196DEFAULT_MAX_REDIRECTS = 20
added:http3/decoders.py+149 added
1"""2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import typing7import zlib89from .exceptions import DecodingError1011try:12 import brotli13except ImportError: # pragma: nocover14 brotli = None151617class Decoder:18 def decode(self, data: bytes) -> bytes:19 raise NotImplementedError() # pragma: nocover2021 def flush(self) -> bytes:22 raise NotImplementedError() # pragma: nocover232425class IdentityDecoder(Decoder):26 """27 Handle unencoded data.28 """2930 def decode(self, data: bytes) -> bytes:31 return data3233 def flush(self) -> bytes:34 return b""353637class DeflateDecoder(Decoder):38 """39 Handle 'deflate' decoding.4041 See: https://stackoverflow.com/questions/183869942 """4344 def __init__(self) -> None:45 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)4647 def decode(self, data: bytes) -> bytes:48 try:49 return self.decompressor.decompress(data)50 except zlib.error as exc:51 raise DecodingError from exc5253 def flush(self) -> bytes:54 try:55 return self.decompressor.flush()56 except zlib.error as exc: # pragma: nocover57 raise DecodingError from exc585960class GZipDecoder(Decoder):61 """62 Handle 'gzip' decoding.6364 See: https://stackoverflow.com/questions/183869965 """6667 def __init__(self) -> None:68 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)6970 def decode(self, data: bytes) -> bytes:71 try:72 return self.decompressor.decompress(data)73 except zlib.error as exc:74 raise DecodingError from exc7576 def flush(self) -> bytes:77 try:78 return self.decompressor.flush()79 except zlib.error as exc: # pragma: nocover80 raise DecodingError from exc818283class BrotliDecoder(Decoder):84 """85 Handle 'brotli' decoding.8687 Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/88 """8990 def __init__(self) -> None:91 assert (92 brotli is not None93 ), "The 'brotlipy' library must be installed to use 'BrotliDecoder'"94 self.decompressor = brotli.Decompressor()9596 def decode(self, data: bytes) -> bytes:97 try:98 return self.decompressor.decompress(data)99 except brotli.Error as exc:100 raise DecodingError from exc101102 def flush(self) -> bytes:103 try:104 self.decompressor.finish()105 return b""106 except brotli.Error as exc: # pragma: nocover107 raise DecodingError from exc108109110class MultiDecoder(Decoder):111 """112 Handle the case where multiple encodings have been applied.113 """114115 def __init__(self, children: typing.Sequence[Decoder]) -> None:116 """117 'children' should be a sequence of decoders in the order in which118 each was applied.119 """120 # Note that we reverse the order for decoding.121 self.children = list(reversed(children))122123 def decode(self, data: bytes) -> bytes:124 for child in self.children:125 data = child.decode(data)126 return data127128 def flush(self) -> bytes:129 data = b""130 for child in self.children:131 data = child.decode(data) + child.flush()132 return data133134135SUPPORTED_DECODERS = {136 "identity": IdentityDecoder,137 "deflate": DeflateDecoder,138 "gzip": GZipDecoder,139 "br": BrotliDecoder,140}141142143if brotli is None:144 SUPPORTED_DECODERS.pop("br") # pragma: nocover145146147ACCEPT_ENCODING = ", ".join(148 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]149)
added:http3/exceptions.py+128 added
1# Timeout exceptions...234class Timeout(Exception):5 """6 A base class for all timeouts.7 """8910class ConnectTimeout(Timeout):11 """12 Timeout while establishing a connection.13 """141516class ReadTimeout(Timeout):17 """18 Timeout while reading response data.19 """202122class WriteTimeout(Timeout):23 """24 Timeout while writing request data.25 """262728class PoolTimeout(Timeout):29 """30 Timeout while waiting to acquire a connection from the pool.31 """323334# HTTP exceptions...353637class HttpError(Exception):38 """39 An Http error occurred.40 """414243class ProtocolError(Exception):44 """45 Malformed HTTP.46 """474849class DecodingError(Exception):50 """51 Decoding of the response failed.52 """535455# Redirect exceptions...565758class RedirectError(Exception):59 """60 Base class for HTTP redirect errors.61 """626364class TooManyRedirects(RedirectError):65 """66 Too many redirects.67 """686970class RedirectBodyUnavailable(RedirectError):71 """72 Got a redirect response, but the request body was streaming, and is73 no longer available.74 """757677class RedirectLoop(RedirectError):78 """79 Infinite redirect loop.80 """818283# Stream exceptions...848586class StreamException(Exception):87 """88 The base class for stream exceptions.8990 The developer made an error in accessing the request stream in91 an invalid way.92 """939495class StreamConsumed(StreamException):96 """97 Attempted to read or stream response content, but the content has already98 been streamed.99 """100101102class ResponseNotRead(StreamException):103 """104 Attempted to access response content, without having called `read()`105 after a streaming response.106 """107108109class ResponseClosed(StreamException):110 """111 Attempted to read or stream response content, but the request has been112 closed.113 """114115116# Other cases...117118119class InvalidURL(Exception):120 """121 URL was missing a hostname, or was not one of HTTP/HTTPS.122 """123124125class CookieConflict(Exception):126 """127 Attempted to lookup a cookie by name, but multiple cookies existed.128 """
added:http3/interfaces.py+209 added
1import enum2import ssl3import typing4from types import TracebackType56from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7from .models import (8 URL,9 AsyncRequest,10 AsyncRequestData,11 AsyncResponse,12 Headers,13 HeaderTypes,14 QueryParamTypes,15 Request,16 RequestData,17 Response,18 URLTypes,19)202122class Protocol(str, enum.Enum):23 HTTP_11 = "HTTP/1.1"24 HTTP_2 = "HTTP/2"252627class AsyncDispatcher:28 """29 Base class for async dispatcher classes, that handle sending the request.3031 Stubs out the interface, as well as providing a `.request()` convienence32 implementation, to make it easy to use or test stand-alone dispatchers,33 without requiring a complete `Client` instance.34 """3536 async def request(37 self,38 method: str,39 url: URLTypes,40 *,41 data: AsyncRequestData = b"",42 params: QueryParamTypes = None,43 headers: HeaderTypes = None,44 verify: VerifyTypes = None,45 cert: CertTypes = None,46 timeout: TimeoutTypes = None47 ) -> AsyncResponse:48 request = AsyncRequest(method, url, data=data, params=params, headers=headers)49 return await self.send(request, verify=verify, cert=cert, timeout=timeout)5051 async def send(52 self,53 request: AsyncRequest,54 verify: VerifyTypes = None,55 cert: CertTypes = None,56 timeout: TimeoutTypes = None,57 ) -> AsyncResponse:58 raise NotImplementedError() # pragma: nocover5960 async def close(self) -> None:61 pass # pragma: nocover6263 async def __aenter__(self) -> "AsyncDispatcher":64 return self6566 async def __aexit__(67 self,68 exc_type: typing.Type[BaseException] = None,69 exc_value: BaseException = None,70 traceback: TracebackType = None,71 ) -> None:72 await self.close()737475class Dispatcher:76 """77 Base class for syncronous dispatcher classes, that handle sending the request.7879 Stubs out the interface, as well as providing a `.request()` convienence80 implementation, to make it easy to use or test stand-alone dispatchers,81 without requiring a complete `Client` instance.82 """8384 def request(85 self,86 method: str,87 url: URLTypes,88 *,89 data: RequestData = b"",90 params: QueryParamTypes = None,91 headers: HeaderTypes = None,92 verify: VerifyTypes = None,93 cert: CertTypes = None,94 timeout: TimeoutTypes = None95 ) -> Response:96 request = Request(method, url, data=data, params=params, headers=headers)97 return self.send(request, verify=verify, cert=cert, timeout=timeout)9899 def send(100 self,101 request: Request,102 verify: VerifyTypes = None,103 cert: CertTypes = None,104 timeout: TimeoutTypes = None,105 ) -> Response:106 raise NotImplementedError() # pragma: nocover107108 def close(self) -> None:109 pass # pragma: nocover110111 def __enter__(self) -> "Dispatcher":112 return self113114 def __exit__(115 self,116 exc_type: typing.Type[BaseException] = None,117 exc_value: BaseException = None,118 traceback: TracebackType = None,119 ) -> None:120 self.close()121122123class BaseReader:124 """125 A stream reader. Abstracts away any asyncio-specfic interfaces126 into a more generic base class, that we can use with alternate127 backend, or for stand-alone test cases.128 """129130 async def read(self, n: int, timeout: TimeoutConfig = None) -> bytes:131 raise NotImplementedError() # pragma: no cover132133134class BaseWriter:135 """136 A stream writer. Abstracts away any asyncio-specfic interfaces137 into a more generic base class, that we can use with alternate138 backend, or for stand-alone test cases.139 """140141 def write_no_block(self, data: bytes) -> None:142 raise NotImplementedError() # pragma: no cover143144 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:145 raise NotImplementedError() # pragma: no cover146147 async def close(self) -> None:148 raise NotImplementedError() # pragma: no cover149150151class BasePoolSemaphore:152 """153 A semaphore for use with connection pooling.154155 Abstracts away any asyncio-specfic interfaces.156 """157158 async def acquire(self) -> None:159 raise NotImplementedError() # pragma: no cover160161 def release(self) -> None:162 raise NotImplementedError() # pragma: no cover163164165class ConcurrencyBackend:166 async def connect(167 self,168 hostname: str,169 port: int,170 ssl_context: typing.Optional[ssl.SSLContext],171 timeout: TimeoutConfig,172 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:173 raise NotImplementedError() # pragma: no cover174175 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:176 raise NotImplementedError() # pragma: no cover177178 async def run_in_threadpool(179 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any180 ) -> typing.Any:181 raise NotImplementedError() # pragma: no cover182183 async def iterate_in_threadpool(self, iterator): # type: ignore184 class IterationComplete(Exception):185 pass186187 def next_wrapper(iterator): # type: ignore188 try:189 return next(iterator)190 except StopIteration:191 raise IterationComplete()192193 while True:194 try:195 yield await self.run_in_threadpool(next_wrapper, iterator)196 except IterationComplete:197 break198199 def run(200 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any201 ) -> typing.Any:202 raise NotImplementedError() # pragma: no cover203204 def iterate(self, async_iterator): # type: ignore205 while True:206 try:207 yield self.run(async_iterator.__anext__)208 except StopAsyncIteration:209 break
added:http3/models.py+1127 added
1import cgi2import email.message3import json as jsonlib4import typing5import urllib.request6from collections.abc import MutableMapping7from http.cookiejar import Cookie, CookieJar8from urllib.parse import parse_qsl, urlencode910import chardet11import rfc39861213from .decoders import (14 ACCEPT_ENCODING,15 SUPPORTED_DECODERS,16 Decoder,17 IdentityDecoder,18 MultiDecoder,19)20from .exceptions import (21 CookieConflict,22 HttpError,23 InvalidURL,24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27)28from .status_codes import StatusCode29from .utils import is_known_encoding, normalize_header_key, normalize_header_value3031URLTypes = typing.Union["URL", str]3233QueryParamTypes = typing.Union[34 "QueryParams",35 typing.Mapping[str, str],36 typing.List[typing.Tuple[typing.Any, typing.Any]],37 str,38]3940HeaderTypes = typing.Union[41 "Headers",42 typing.Dict[typing.AnyStr, typing.AnyStr],43 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44]4546CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]4748AuthTypes = typing.Union[49 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],50 typing.Callable[["AsyncRequest"], "AsyncRequest"],51]5253AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5455RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]5657AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]5859ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]606162class URL:63 def __init__(64 self,65 url: URLTypes,66 allow_relative: bool = False,67 params: QueryParamTypes = None,68 ) -> None:69 if isinstance(url, rfc3986.uri.URIReference):70 self.components = url71 elif isinstance(url, str):72 self.components = rfc3986.api.uri_reference(url)73 else:74 self.components = url.components7576 # Handle IDNA domain names.77 if self.components.authority:78 idna_authority = self.components.authority.encode("idna").decode("ascii")79 if idna_authority != self.components.authority:80 self.components = self.components.copy_with(authority=idna_authority)8182 # Normalize scheme and domain name.83 self.components = self.components.normalize()8485 # Add any query parameters.86 if params:87 query_string = str(QueryParams(params))88 self.components = self.components.copy_with(query=query_string)8990 # Enforce absolute URLs by default.91 if not allow_relative:92 if not self.scheme:93 raise InvalidURL("No scheme included in URL.")94 if self.scheme not in ("http", "https"):95 raise InvalidURL('URL scheme must be "http" or "https".')96 if not self.host:97 raise InvalidURL("No host included in URL.")9899 @property100 def scheme(self) -> str:101 return self.components.scheme or ""102103 @property104 def authority(self) -> str:105 return self.components.authority or ""106107 @property108 def username(self) -> str:109 userinfo = self.components.userinfo or ""110 return userinfo.partition(":")[0]111112 @property113 def password(self) -> str:114 userinfo = self.components.userinfo or ""115 return userinfo.partition(":")[2]116117 @property118 def host(self) -> str:119 return self.components.host or ""120121 @property122 def port(self) -> int:123 port = self.components.port124 if port is None:125 return {"https": 443, "http": 80}[self.scheme]126 return int(port)127128 @property129 def path(self) -> str:130 return self.components.path or "/"131132 @property133 def query(self) -> str:134 return self.components.query or ""135136 @property137 def full_path(self) -> str:138 path = self.path139 if self.query:140 path += "?" + self.query141 return path142143 @property144 def fragment(self) -> str:145 return self.components.fragment or ""146147 @property148 def is_ssl(self) -> bool:149 return self.components.scheme == "https"150151 @property152 def is_absolute_url(self) -> bool:153 """154 Return `True` for absolute URLs such as 'http://example.com/path',155 and `False` for relative URLs such as '/path'.156 """157 # We don't use rfc3986's `is_absolute` because it treats158 # URLs with a fragment portion as not absolute.159 # What we actually care about is if the URL provides160 # a scheme and hostname to which connections should be made.161 return self.components.scheme and self.components.host162163 @property164 def is_relative_url(self) -> bool:165 return not self.is_absolute_url166167 @property168 def origin(self) -> "Origin":169 return Origin(self)170171 def copy_with(self, **kwargs: typing.Any) -> "URL":172 return URL(self.components.copy_with(**kwargs))173174 def resolve_with(self, base_url: URLTypes) -> "URL":175 """176 Return an absolute URL, using base_url as the base.177 """178 # We drop any fragment portion, because RFC 3986 strictly179 # treats URLs with a fragment portion as not being absolute URLs.180 base_url = URL(base_url).copy_with(fragment=None)181 return URL(self.components.resolve_with(base_url.components))182183 def __hash__(self) -> int:184 return hash(str(self))185186 def __eq__(self, other: typing.Any) -> bool:187 return isinstance(other, URL) and str(self) == str(other)188189 def __str__(self) -> str:190 return self.components.unsplit()191192 def __repr__(self) -> str:193 class_name = self.__class__.__name__194 url_str = str(self)195 return f"{class_name}({url_str!r})"196197198class Origin:199 """200 The URL scheme and authority information, as a comparable, hashable object.201 """202203 def __init__(self, url: URLTypes) -> None:204 if not isinstance(url, URL):205 url = URL(url)206 self.is_ssl = url.is_ssl207 self.host = url.host208 self.port = url.port209210 def __eq__(self, other: typing.Any) -> bool:211 return (212 isinstance(other, self.__class__)213 and self.is_ssl == other.is_ssl214 and self.host == other.host215 and self.port == other.port216 )217218 def __hash__(self) -> int:219 return hash((self.is_ssl, self.host, self.port))220221222class QueryParams(typing.Mapping[str, str]):223 """224 URL query parameters, as a multi-dict.225 """226227 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:228 assert len(args) < 2, "Too many arguments."229 assert not (args and kwargs), "Cannot mix named and unnamed arguments."230231 value = args[0] if args else kwargs232233 if isinstance(value, str):234 items = parse_qsl(value)235 elif isinstance(value, QueryParams):236 items = value.multi_items()237 elif isinstance(value, list):238 items = value239 else:240 items = value.items() # type: ignore241242 self._list = [(str(k), str(v)) for k, v in items]243 self._dict = {str(k): str(v) for k, v in items}244245 def getlist(self, key: typing.Any) -> typing.List[str]:246 return [item_value for item_key, item_value in self._list if item_key == key]247248 def keys(self) -> typing.KeysView:249 return self._dict.keys()250251 def values(self) -> typing.ValuesView:252 return self._dict.values()253254 def items(self) -> typing.ItemsView:255 return self._dict.items()256257 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:258 return list(self._list)259260 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:261 if key in self._dict:262 return self._dict[key]263 return default264265 def __getitem__(self, key: typing.Any) -> str:266 return self._dict[key]267268 def __contains__(self, key: typing.Any) -> bool:269 return key in self._dict270271 def __iter__(self) -> typing.Iterator[typing.Any]:272 return iter(self.keys())273274 def __len__(self) -> int:275 return len(self._dict)276277 def __eq__(self, other: typing.Any) -> bool:278 if not isinstance(other, self.__class__):279 return False280 return sorted(self._list) == sorted(other._list)281282 def __str__(self) -> str:283 return urlencode(self._list)284285 def __repr__(self) -> str:286 class_name = self.__class__.__name__287 query_string = str(self)288 return f"{class_name}({query_string!r})"289290291class Headers(typing.MutableMapping[str, str]):292 """293 HTTP headers, as a case-insensitive multi-dict.294 """295296 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:297 if headers is None:298 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]299 elif isinstance(headers, Headers):300 self._list = list(headers.raw)301 elif isinstance(headers, dict):302 self._list = [303 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))304 for k, v in headers.items()305 ]306 else:307 self._list = [308 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))309 for k, v in headers310 ]311 self._encoding = encoding312313 @property314 def encoding(self) -> str:315 """316 Header encoding is mandated as ascii, but we allow fallbacks to utf-8317 or iso-8859-1.318 """319 if self._encoding is None:320 for encoding in ["ascii", "utf-8"]:321 for key, value in self.raw:322 try:323 key.decode(encoding)324 value.decode(encoding)325 except UnicodeDecodeError:326 break327 else:328 # The else block runs if 'break' did not occur, meaning329 # all values fitted the encoding.330 self._encoding = encoding331 break332 else:333 # The ISO-8859-1 encoding covers all 256 code points in a byte,334 # so will never raise decode errors.335 self._encoding = "iso-8859-1"336 return self._encoding337338 @encoding.setter339 def encoding(self, value: str) -> None:340 self._encoding = value341342 @property343 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:344 """345 Returns a list of the raw header items, as byte pairs.346 May be mutated in-place.347 """348 return self._list349350 def keys(self) -> typing.List[str]: # type: ignore351 return [key.decode(self.encoding) for key, value in self._list]352353 def values(self) -> typing.List[str]: # type: ignore354 return [value.decode(self.encoding) for key, value in self._list]355356 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore357 return [358 (key.decode(self.encoding), value.decode(self.encoding))359 for key, value in self._list360 ]361362 def get(self, key: str, default: typing.Any = None) -> typing.Any:363 try:364 return self[key]365 except KeyError:366 return default367368 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:369 """370 Return multiple header values.371 """372 get_header_key = key.lower().encode(self.encoding)373374 values = [375 item_value.decode(self.encoding)376 for item_key, item_value in self._list377 if item_key == get_header_key378 ]379380 if not split_commas:381 return values382383 split_values = []384 for value in values:385 split_values.extend([item.strip() for item in value.split(",")])386 return split_values387388 def __getitem__(self, key: str) -> str:389 """390 Return a single header value.391392 If there are multiple headers with the same key, then we concatenate393 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2394 """395 normalized_key = key.lower().encode(self.encoding)396397 items = []398 for header_key, header_value in self._list:399 if header_key == normalized_key:400 items.append(header_value.decode(self.encoding))401402 if items:403 return ", ".join(items)404405 raise KeyError(key)406407 def __setitem__(self, key: str, value: str) -> None:408 """409 Set the header `key` to `value`, removing any duplicate entries.410 Retains insertion order.411 """412 set_key = key.lower().encode(self.encoding)413 set_value = value.encode(self.encoding)414415 found_indexes = []416 for idx, (item_key, item_value) in enumerate(self._list):417 if item_key == set_key:418 found_indexes.append(idx)419420 for idx in reversed(found_indexes[1:]):421 del self._list[idx]422423 if found_indexes:424 idx = found_indexes[0]425 self._list[idx] = (set_key, set_value)426 else:427 self._list.append((set_key, set_value))428429 def __delitem__(self, key: str) -> None:430 """431 Remove the header `key`.432 """433 del_key = key.lower().encode(self.encoding)434435 pop_indexes = []436 for idx, (item_key, item_value) in enumerate(self._list):437 if item_key == del_key:438 pop_indexes.append(idx)439440 for idx in reversed(pop_indexes):441 del self._list[idx]442443 def __contains__(self, key: typing.Any) -> bool:444 get_header_key = key.lower().encode(self.encoding)445 for header_key, header_value in self._list:446 if header_key == get_header_key:447 return True448 return False449450 def __iter__(self) -> typing.Iterator[typing.Any]:451 return iter(self.keys())452453 def __len__(self) -> int:454 return len(self._list)455456 def __eq__(self, other: typing.Any) -> bool:457 if not isinstance(other, Headers):458 return False459 return sorted(self._list) == sorted(other._list)460461 def __repr__(self) -> str:462 class_name = self.__class__.__name__463464 encoding_str = ""465 if self.encoding != "ascii":466 encoding_str = f", encoding={self.encoding!r}"467468 as_dict = dict(self.items())469 if len(as_dict) == len(self):470 return f"{class_name}({as_dict!r}{encoding_str})"471 as_list = self.items()472 return f"{class_name}({as_list!r}{encoding_str})"473474475class BaseRequest:476 def __init__(477 self,478 method: str,479 url: typing.Union[str, URL],480 *,481 params: QueryParamTypes = None,482 headers: HeaderTypes = None,483 cookies: CookieTypes = None,484 ):485 self.method = method.upper()486 self.url = URL(url, params=params)487 self.headers = Headers(headers)488 if cookies:489 self._cookies = Cookies(cookies)490 self._cookies.set_cookie_header(self)491492 def encode_json(self, json: typing.Any) -> bytes:493 return jsonlib.dumps(json).encode("utf-8")494495 def urlencode_data(self, data: dict) -> bytes:496 return urlencode(data, doseq=True).encode("utf-8")497498 def prepare(self) -> None:499 content = getattr(self, "content", None) # type: bytes500 is_streaming = getattr(self, "is_streaming", False)501502 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]503504 has_user_agent = "user-agent" in self.headers505 has_accept = "accept" in self.headers506 has_content_length = (507 "content-length" in self.headers or "transfer-encoding" in self.headers508 )509 has_accept_encoding = "accept-encoding" in self.headers510511 if not has_user_agent:512 auto_headers.append((b"user-agent", b"http3"))513 if not has_accept:514 auto_headers.append((b"accept", b"*/*"))515 if not has_content_length:516 if is_streaming:517 auto_headers.append((b"transfer-encoding", b"chunked"))518 elif content:519 content_length = str(len(content)).encode()520 auto_headers.append((b"content-length", content_length))521 if not has_accept_encoding:522 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))523524 for item in reversed(auto_headers):525 self.headers.raw.insert(0, item)526527 @property528 def cookies(self) -> "Cookies":529 if not hasattr(self, "_cookies"):530 self._cookies = Cookies()531 return self._cookies532533 def __repr__(self) -> str:534 class_name = self.__class__.__name__535 url = str(self.url)536 return f"<{class_name}({self.method!r}, {url!r})>"537538539class AsyncRequest(BaseRequest):540 def __init__(541 self,542 method: str,543 url: typing.Union[str, URL],544 *,545 params: QueryParamTypes = None,546 headers: HeaderTypes = None,547 cookies: CookieTypes = None,548 data: AsyncRequestData = b"",549 json: typing.Any = None,550 ):551 super().__init__(552 method=method, url=url, params=params, headers=headers, cookies=cookies553 )554555 if json is not None:556 self.is_streaming = False557 self.content = self.encode_json(json)558 self.headers["Content-Type"] = "application/json"559 elif isinstance(data, bytes):560 self.is_streaming = False561 self.content = data562 elif isinstance(data, dict):563 self.is_streaming = False564 self.content = self.urlencode_data(data)565 self.headers["Content-Type"] = "application/x-www-form-urlencoded"566 else:567 assert hasattr(data, "__aiter__")568 self.is_streaming = True569 self.content_aiter = data570571 self.prepare()572573 async def read(self) -> bytes:574 """575 Read and return the response content.576 """577 if not hasattr(self, "content"):578 self.content = b"".join([part async for part in self.stream()])579 return self.content580581 async def stream(self) -> typing.AsyncIterator[bytes]:582 if self.is_streaming:583 async for part in self.content_aiter:584 yield part585 elif self.content:586 yield self.content587588589class Request(BaseRequest):590 def __init__(591 self,592 method: str,593 url: typing.Union[str, URL],594 *,595 params: QueryParamTypes = None,596 headers: HeaderTypes = None,597 cookies: CookieTypes = None,598 data: RequestData = b"",599 json: typing.Any = None,600 ):601 super().__init__(602 method=method, url=url, params=params, headers=headers, cookies=cookies603 )604605 if json is not None:606 self.is_streaming = False607 self.content = self.encode_json(json)608 self.headers["Content-Type"] = "application/json"609 elif isinstance(data, bytes):610 self.is_streaming = False611 self.content = data612 elif isinstance(data, dict):613 self.is_streaming = False614 self.content = self.urlencode_data(data)615 self.headers["Content-Type"] = "application/x-www-form-urlencoded"616 else:617 assert hasattr(data, "__iter__")618 self.is_streaming = True619 self.content_iter = data620621 self.prepare()622623 def read(self) -> bytes:624 if not hasattr(self, "content"):625 self.content = b"".join([part for part in self.stream()])626 return self.content627628 def stream(self) -> typing.Iterator[bytes]:629 if self.is_streaming:630 for part in self.content_iter:631 yield part632 elif self.content:633 yield self.content634635636class BaseResponse:637 def __init__(638 self,639 status_code: int,640 *,641 reason_phrase: str = None,642 protocol: str = None,643 headers: HeaderTypes = None,644 request: BaseRequest = None,645 on_close: typing.Callable = None,646 ):647 self.status_code = StatusCode.enum_or_int(status_code)648 self.reason_phrase = StatusCode.get_reason_phrase(status_code)649 self.protocol = protocol650 self.headers = Headers(headers)651652 self.request = request653 self.on_close = on_close654 self.next = None # typing.Optional[typing.Callable]655656 @property657 def url(self) -> typing.Optional[URL]:658 """659 Returns the URL for which the request was made.660661 Requires that `request` was provided when instantiating the response.662 """663 return None if self.request is None else self.request.url664665 @property666 def content(self) -> bytes:667 if not hasattr(self, "_content"):668 if hasattr(self, "_raw_content"):669 raw_content = getattr(self, "_raw_content") # type: bytes670 content = self.decoder.decode(raw_content)671 content += self.decoder.flush()672 self._content = content673 else:674 raise ResponseNotRead()675 return self._content676677 @property678 def text(self) -> str:679 if not hasattr(self, "_text"):680 content = self.content681 if not content:682 self._text = ""683 else:684 encoding = self.encoding685 self._text = content.decode(encoding, errors="replace")686 return self._text687688 @property689 def encoding(self) -> str:690 if not hasattr(self, "_encoding"):691 encoding = self.charset_encoding692 if encoding is None or not is_known_encoding(encoding):693 encoding = self.apparent_encoding694 if encoding is None or not is_known_encoding(encoding):695 encoding = "utf-8"696 self._encoding = encoding697 return self._encoding698699 @encoding.setter700 def encoding(self, value: str) -> None:701 self._encoding = value702703 @property704 def charset_encoding(self) -> typing.Optional[str]:705 """706 Return the encoding, as specified by the Content-Type header.707 """708 content_type = self.headers.get("Content-Type")709 if content_type is None:710 return None711712 parsed = cgi.parse_header(content_type)713 media_type, params = parsed[0], parsed[-1]714 if "charset" in params:715 return params["charset"].strip("'\"")716717 # RFC 2616 specifies that 'iso-8859-1' should be used as the default718 # for 'text/*' media types, if no charset is provided.719 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1720 if media_type.startswith("text/"):721 return "iso-8859-1"722723 return None724725 @property726 def apparent_encoding(self) -> typing.Optional[str]:727 """728 Return the encoding, as it appears to autodetection.729 """730 return chardet.detect(self.content)["encoding"]731732 @property733 def decoder(self) -> Decoder:734 """735 Returns a decoder instance which can be used to decode the raw byte736 content, depending on the Content-Encoding used in the response.737 """738 if not hasattr(self, "_decoder"):739 decoders = [] # type: typing.List[Decoder]740 values = self.headers.getlist("content-encoding", split_commas=True)741 for value in values:742 value = value.strip().lower()743 decoder_cls = SUPPORTED_DECODERS[value]744 decoders.append(decoder_cls())745746 if len(decoders) == 1:747 self._decoder = decoders[0]748 elif len(decoders) > 1:749 self._decoder = MultiDecoder(decoders)750 else:751 self._decoder = IdentityDecoder()752753 return self._decoder754755 @property756 def is_redirect(self) -> bool:757 return StatusCode.is_redirect(self.status_code) and "location" in self.headers758759 def raise_for_status(self) -> None:760 """761 Raise the `HttpError` if one occurred.762 """763 message = (764 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"765 "For more information check: https://httpstatuses.com/{0.status_code}"766 )767768 if StatusCode.is_client_error(self.status_code):769 message = message.format(self, error_type="Client Error")770 elif StatusCode.is_server_error(self.status_code):771 message = message.format(self, error_type="Server Error")772 else:773 message = ""774775 if message:776 raise HttpError(message)777778 def json(self) -> typing.Any:779 return jsonlib.loads(self.content.decode("utf-8"))780781 @property782 def cookies(self) -> "Cookies":783 if not hasattr(self, "_cookies"):784 assert self.request is not None785 self._cookies = Cookies()786 self._cookies.extract_cookies(self)787 return self._cookies788789 def __repr__(self) -> str:790 return f"<Response({self.status_code}, {self.reason_phrase!r})>"791792793class AsyncResponse(BaseResponse):794 def __init__(795 self,796 status_code: int,797 *,798 reason_phrase: str = None,799 protocol: str = None,800 headers: HeaderTypes = None,801 content: AsyncResponseContent = b"",802 on_close: typing.Callable = None,803 request: AsyncRequest = None,804 history: typing.List["BaseResponse"] = None,805 ):806 super().__init__(807 status_code=status_code,808 reason_phrase=reason_phrase,809 protocol=protocol,810 headers=headers,811 request=request,812 on_close=on_close,813 )814815 self.history = [] if history is None else list(history)816817 if isinstance(content, bytes):818 self.is_closed = True819 self.is_stream_consumed = True820 self._raw_content = content821 else:822 self.is_closed = False823 self.is_stream_consumed = False824 self._raw_stream = content825826 async def read(self) -> bytes:827 """828 Read and return the response content.829 """830 if not hasattr(self, "_content"):831 self._content = b"".join([part async for part in self.stream()])832 return self._content833834 async def stream(self) -> typing.AsyncIterator[bytes]:835 """836 A byte-iterator over the decoded response content.837 This allows us to handle gzip, deflate, and brotli encoded responses.838 """839 if hasattr(self, "_content"):840 yield self._content841 else:842 async for chunk in self.raw():843 yield self.decoder.decode(chunk)844 yield self.decoder.flush()845846 async def raw(self) -> typing.AsyncIterator[bytes]:847 """848 A byte-iterator over the raw response content.849 """850 if hasattr(self, "_raw_content"):851 yield self._raw_content852 else:853 if self.is_stream_consumed:854 raise StreamConsumed()855 if self.is_closed:856 raise ResponseClosed()857858 self.is_stream_consumed = True859 async for part in self._raw_stream:860 yield part861 await self.close()862863 async def close(self) -> None:864 """865 Close the response and release the connection.866 Automatically called if the response body is read to completion.867 """868 if not self.is_closed:869 self.is_closed = True870 if self.on_close is not None:871 await self.on_close()872873874class Response(BaseResponse):875 def __init__(876 self,877 status_code: int,878 *,879 reason_phrase: str = None,880 protocol: str = None,881 headers: HeaderTypes = None,882 content: ResponseContent = b"",883 on_close: typing.Callable = None,884 request: Request = None,885 history: typing.List["BaseResponse"] = None,886 ):887 super().__init__(888 status_code=status_code,889 reason_phrase=reason_phrase,890 protocol=protocol,891 headers=headers,892 request=request,893 on_close=on_close,894 )895896 self.history = [] if history is None else list(history)897898 if isinstance(content, bytes):899 self.is_closed = True900 self.is_stream_consumed = True901 self._raw_content = content902 else:903 self.is_closed = False904 self.is_stream_consumed = False905 self._raw_stream = content906907 def read(self) -> bytes:908 """909 Read and return the response content.910 """911 if not hasattr(self, "_content"):912 self._content = b"".join([part for part in self.stream()])913 return self._content914915 def stream(self) -> typing.Iterator[bytes]:916 """917 A byte-iterator over the decoded response content.918 This allows us to handle gzip, deflate, and brotli encoded responses.919 """920 if hasattr(self, "_content"):921 yield self._content922 else:923 for chunk in self.raw():924 yield self.decoder.decode(chunk)925 yield self.decoder.flush()926927 def raw(self) -> typing.Iterator[bytes]:928 """929 A byte-iterator over the raw response content.930 """931 if hasattr(self, "_raw_content"):932 yield self._raw_content933 else:934 if self.is_stream_consumed:935 raise StreamConsumed()936 if self.is_closed:937 raise ResponseClosed()938939 self.is_stream_consumed = True940 for part in self._raw_stream:941 yield part942 self.close()943944 def close(self) -> None:945 """946 Close the response and release the connection.947 Automatically called if the response body is read to completion.948 """949 if not self.is_closed:950 self.is_closed = True951 if self.on_close is not None:952 self.on_close()953954955class Cookies(MutableMapping):956 """957 HTTP Cookies, as a mutable mapping.958 """959960 def __init__(self, cookies: CookieTypes = None) -> None:961 if cookies is None or isinstance(cookies, dict):962 self.jar = CookieJar()963 if isinstance(cookies, dict):964 for key, value in cookies.items():965 self.set(key, value)966 elif isinstance(cookies, Cookies):967 self.jar = CookieJar()968 for cookie in cookies.jar:969 self.jar.set_cookie(cookie)970 else:971 self.jar = cookies972973 def extract_cookies(self, response: BaseResponse) -> None:974 """975 Loads any cookies based on the response `Set-Cookie` headers.976 """977 assert response.request is not None978 urlib_response = self._CookieCompatResponse(response)979 urllib_request = self._CookieCompatRequest(response.request)980981 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore982983 def set_cookie_header(self, request: BaseRequest) -> None:984 """985 Sets an appropriate 'Cookie:' HTTP header on the `Request`.986 """987 urllib_request = self._CookieCompatRequest(request)988 self.jar.add_cookie_header(urllib_request)989990 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:991 """992 Set a cookie value by name. May optionally include domain and path.993 """994 kwargs = dict(995 version=0,996 name=name,997 value=value,998 port=None,999 port_specified=False,1000 domain=domain,1001 domain_specified=bool(domain),1002 domain_initial_dot=domain.startswith("."),1003 path=path,1004 path_specified=bool(path),1005 secure=False,1006 expires=None,1007 discard=True,1008 comment=None,1009 comment_url=None,1010 rest={"HttpOnly": None},1011 rfc2109=False,1012 )1013 cookie = Cookie(**kwargs) # type: ignore1014 self.jar.set_cookie(cookie)10151016 def get( # type: ignore1017 self, name: str, default: str = None, domain: str = None, path: str = None1018 ) -> typing.Optional[str]:1019 """1020 Get a cookie by name. May optionally include domain and path1021 in order to specify exactly which cookie to retrieve.1022 """1023 value = None1024 for cookie in self.jar:1025 if cookie.name == name:1026 if domain is None or cookie.domain == domain: # type: ignore1027 if path is None or cookie.path == path:1028 if value is not None:1029 message = f"Multiple cookies exist with name={name}"1030 raise CookieConflict(message)1031 value = cookie.value10321033 if value is None:1034 return default1035 return value10361037 def delete(self, name: str, domain: str = None, path: str = None) -> None:1038 """1039 Delete a cookie by name. May optionally include domain and path1040 in order to specify exactly which cookie to delete.1041 """1042 if domain is not None and path is not None:1043 return self.jar.clear(domain, path, name)10441045 remove = []1046 for cookie in self.jar:1047 if cookie.name == name:1048 if domain is None or cookie.domain == domain: # type: ignore1049 if path is None or cookie.path == path:1050 remove.append(cookie)10511052 for cookie in remove:1053 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10541055 def clear(self, domain: str = None, path: str = None) -> None:1056 """1057 Delete all cookies. Optionally include a domain and path in1058 order to only delete a subset of all the cookies.1059 """1060 args = []1061 if domain is not None:1062 args.append(domain)1063 if path is not None:1064 assert domain is not None1065 args.append(path)1066 self.jar.clear(*args)10671068 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1069 cookies = Cookies(cookies)1070 for cookie in cookies.jar:1071 self.jar.set_cookie(cookie)10721073 def __setitem__(self, name: str, value: str) -> None:1074 return self.set(name, value)10751076 def __getitem__(self, name: str) -> str:1077 value = self.get(name)1078 if value is None:1079 raise KeyError(name)1080 return value10811082 def __delitem__(self, name: str) -> None:1083 return self.delete(name)10841085 def __len__(self) -> int:1086 return len(self.jar)10871088 def __iter__(self) -> typing.Iterator[str]:1089 return (cookie.name for cookie in self.jar)10901091 def __bool__(self) -> bool:1092 for cookie in self.jar:1093 return True1094 return False10951096 class _CookieCompatRequest(urllib.request.Request):1097 """1098 Wraps a `Request` instance up in a compatability interface suitable1099 for use with `CookieJar` operations.1100 """11011102 def __init__(self, request: BaseRequest) -> None:1103 super().__init__(1104 url=str(request.url),1105 headers=dict(request.headers),1106 method=request.method,1107 )1108 self.request = request11091110 def add_unredirected_header(self, key: str, value: str) -> None:1111 super().add_unredirected_header(key, value)1112 self.request.headers[key] = value11131114 class _CookieCompatResponse:1115 """1116 Wraps a `Request` instance up in a compatability interface suitable1117 for use with `CookieJar` operations.1118 """11191120 def __init__(self, response: BaseResponse):1121 self.response = response11221123 def info(self) -> email.message.Message:1124 info = email.message.Message()1125 for key, value in self.response.headers.items():1126 info[key] = value1127 return info
added:http3/status_codes.py+133 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 """1718 def __new__(cls, value: int, phrase: str = "") -> "StatusCode":19 obj = int.__new__(cls, value) # type: ignore20 obj._value_ = value2122 obj.phrase = phrase23 return obj2425 def __str__(self) -> str:26 return str(self.value)2728 @classmethod29 def enum_or_int(cls, value: int) -> int:30 try:31 return StatusCode(value)32 except ValueError:33 return value3435 @classmethod36 def get_reason_phrase(cls, value: int) -> str:37 try:38 return StatusCode(value).phrase # type: ignore39 except ValueError:40 return ""4142 @classmethod43 def is_redirect(cls, value: int) -> bool:44 return value in (45 StatusCode.MOVED_PERMANENTLY, # 301 (Cacheable redirect. Method may change to GET.)46 StatusCode.FOUND, # 302 (Uncacheable redirect. Method may change to GET.)47 StatusCode.SEE_OTHER, # 303 (Client should make a GET or HEAD request.)48 StatusCode.TEMPORARY_REDIRECT, # 307 (Equiv. 302, but retain method)49 StatusCode.PERMANENT_REDIRECT, # 308 (Equiv. 301, but retain method)50 )5152 @classmethod53 def is_client_error(cls, value: int) -> bool:54 return value >= 400 and value <= 4995556 @classmethod57 def is_server_error(cls, value: int) -> bool:58 return value >= 500 and value <= 5995960 # informational61 CONTINUE = 100, "Continue"62 SWITCHING_PROTOCOLS = 101, "Switching Protocols"63 PROCESSING = 102, "Processing"6465 # success66 OK = 200, "OK"67 CREATED = 201, "Created"68 ACCEPTED = 202, "Accepted"69 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"70 NO_CONTENT = 204, "No Content"71 RESET_CONTENT = 205, "Reset Content"72 PARTIAL_CONTENT = 206, "Partial Content"73 MULTI_STATUS = 207, "Multi-Status"74 ALREADY_REPORTED = 208, "Already Reported"75 IM_USED = 226, "IM Used"7677 # redirection78 MULTIPLE_CHOICES = 300, "Multiple Choices"79 MOVED_PERMANENTLY = 301, "Moved Permanently"80 FOUND = 302, "Found"81 SEE_OTHER = 303, "See Other"82 NOT_MODIFIED = 304, "Not Modified"83 USE_PROXY = 305, "Use Proxy"84 TEMPORARY_REDIRECT = 307, "Temporary Redirect"85 PERMANENT_REDIRECT = 308, "Permanent Redirect"8687 # client error88 BAD_REQUEST = 400, "Bad Request"89 UNAUTHORIZED = 401, "Unauthorized"90 PAYMENT_REQUIRED = 402, "Payment Required"91 FORBIDDEN = 403, "Forbidden"92 NOT_FOUND = 404, "Not Found"93 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"94 NOT_ACCEPTABLE = 406, "Not Acceptable"95 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"96 REQUEST_TIMEOUT = 408, "Request Timeout"97 CONFLICT = 409, "Conflict"98 GONE = 410, "Gone"99 LENGTH_REQUIRED = 411, "Length Required"100 PRECONDITION_FAILED = 412, "Precondition Failed"101 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"102 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"103 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"104 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"105 EXPECTATION_FAILED = 417, "Expectation Failed"106 MISDIRECTED_REQUEST = 421, "Misdirected Request"107 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"108 LOCKED = 423, "Locked"109 FAILED_DEPENDENCY = 424, "Failed Dependency"110 UPGRADE_REQUIRED = 426, "Upgrade Required"111 PRECONDITION_REQUIRED = 428, "Precondition Required"112 TOO_MANY_REQUESTS = 429, "Too Many Requests"113 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"114115 # server errors116 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"117 NOT_IMPLEMENTED = 501, "Not Implemented"118 BAD_GATEWAY = 502, "Bad Gateway"119 SERVICE_UNAVAILABLE = 503, "Service Unavailable"120 GATEWAY_TIMEOUT = 504, "Gateway Timeout"121 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"122 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"123 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"124 LOOP_DETECTED = 508, "Loop Detected"125 NOT_EXTENDED = 510, "Not Extended"126 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"127128129codes = StatusCode130131# Include lower-case styles for `requests` compatability.132for code in codes:133 setattr(codes, code._name_.lower(), int(code))
added:http3/utils.py+31 added
1import codecs2import typing345def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:6 """7 Coerce str/bytes into a strictly byte-wise HTTP header key.8 """9 if isinstance(value, bytes):10 return value.lower()11 return value.encode(encoding or "ascii").lower()121314def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:15 """16 Coerce str/bytes into a strictly byte-wise HTTP header value.17 """18 if isinstance(value, bytes):19 return value20 return value.encode(encoding or "ascii")212223def is_known_encoding(encoding: str) -> bool:24 """25 Return `True` if `encoding` is a known codec.26 """27 try:28 codecs.lookup(encoding)29 except LookupError:30 return False31 return True
deleted:httpcore/dispatch/__init__.py-4 removed
1"""2Dispatch classes handle the raw network connections and the implementation3details of making the HTTP request and receiving the response.4"""
deleted:httpcore/dispatch/connection_pool.py-164 removed
1import typing23from ..concurrency import AsyncioBackend4from ..config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_TIMEOUT_CONFIG,8 CertTypes,9 PoolLimits,10 TimeoutTypes,11 VerifyTypes,12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout15from ..interfaces import AsyncDispatcher, ConcurrencyBackend16from ..models import AsyncRequest, AsyncResponse, Origin17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]202122class ConnectionStore:23 """24 We need to maintain collections of connections in a way that allows us to:2526 * Lookup connections by origin.27 * Iterate over connections by insertion time.28 * Return the total number of connections.29 """3031 def __init__(self) -> None:32 self.all = {} # type: typing.Dict[HTTPConnection, float]33 self.by_origin = (34 {}35 ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3637 def pop_by_origin(38 self, origin: Origin, http2_only: bool = False39 ) -> typing.Optional[HTTPConnection]:40 try:41 connections = self.by_origin[origin]42 except KeyError:43 return None4445 connection = next(reversed(list(connections.keys())))46 if http2_only and not connection.is_http2:47 return None4849 del connections[connection]50 if not connections:51 del self.by_origin[origin]52 del self.all[connection]5354 return connection5556 def add(self, connection: HTTPConnection) -> None:57 self.all[connection] = 0.058 try:59 self.by_origin[connection.origin][connection] = 0.060 except KeyError:61 self.by_origin[connection.origin] = {connection: 0.0}6263 def remove(self, connection: HTTPConnection) -> None:64 del self.all[connection]65 del self.by_origin[connection.origin][connection]66 if not self.by_origin[connection.origin]:67 del self.by_origin[connection.origin]6869 def clear(self) -> None:70 self.all.clear()71 self.by_origin.clear()7273 def __iter__(self) -> typing.Iterator[HTTPConnection]:74 return iter(self.all.keys())7576 def __len__(self) -> int:77 return len(self.all)787980class ConnectionPool(AsyncDispatcher):81 def __init__(82 self,83 *,84 verify: VerifyTypes = True,85 cert: CertTypes = None,86 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,87 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,88 backend: ConcurrencyBackend = None,89 ):90 self.verify = verify91 self.cert = cert92 self.timeout = timeout93 self.pool_limits = pool_limits94 self.is_closed = False9596 self.keepalive_connections = ConnectionStore()97 self.active_connections = ConnectionStore()9899 self.backend = AsyncioBackend() if backend is None else backend100 self.max_connections = self.backend.get_semaphore(pool_limits)101102 @property103 def num_connections(self) -> int:104 return len(self.keepalive_connections) + len(self.active_connections)105106 async def send(107 self,108 request: AsyncRequest,109 verify: VerifyTypes = None,110 cert: CertTypes = None,111 timeout: TimeoutTypes = None,112 ) -> AsyncResponse:113 connection = await self.acquire_connection(request.url.origin)114 try:115 response = await connection.send(116 request, verify=verify, cert=cert, timeout=timeout117 )118 except BaseException as exc:119 self.active_connections.remove(connection)120 self.max_connections.release()121 raise exc122 return response123124 async def acquire_connection(self, origin: Origin) -> HTTPConnection:125 connection = self.active_connections.pop_by_origin(origin, http2_only=True)126 if connection is None:127 connection = self.keepalive_connections.pop_by_origin(origin)128129 if connection is None:130 await self.max_connections.acquire()131 connection = HTTPConnection(132 origin,133 verify=self.verify,134 cert=self.cert,135 timeout=self.timeout,136 backend=self.backend,137 release_func=self.release_connection,138 )139140 self.active_connections.add(connection)141142 return connection143144 async def release_connection(self, connection: HTTPConnection) -> None:145 if connection.is_closed:146 self.active_connections.remove(connection)147 self.max_connections.release()148 elif (149 self.pool_limits.soft_limit is not None150 and self.num_connections > self.pool_limits.soft_limit151 ):152 self.active_connections.remove(connection)153 self.max_connections.release()154 await connection.close()155 else:156 self.active_connections.remove(connection)157 self.keepalive_connections.add(connection)158159 async def close(self) -> None:160 self.is_closed = True161 connections = list(self.keepalive_connections)162 self.keepalive_connections.clear()163 for connection in connections:164 await connection.close()
deleted:httpcore/dispatch/connection.py-107 removed
1import functools2import typing34import h2.connection5import h1167from ..concurrency import AsyncioBackend8from ..config import (9 DEFAULT_SSL_CONFIG,10 DEFAULT_TIMEOUT_CONFIG,11 CertTypes,12 SSLConfig,13 TimeoutConfig,14 TimeoutTypes,15 VerifyTypes,16)17from ..exceptions import ConnectTimeout18from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol19from ..models import AsyncRequest, AsyncResponse, Origin20from .http2 import HTTP2Connection21from .http11 import HTTP11Connection2223# Callback signature: async def callback(conn: HTTPConnection) -> None24ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]252627class HTTPConnection(AsyncDispatcher):28 def __init__(29 self,30 origin: typing.Union[str, Origin],31 verify: VerifyTypes = True,32 cert: CertTypes = None,33 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,34 backend: ConcurrencyBackend = None,35 release_func: typing.Optional[ReleaseCallback] = None,36 ):37 self.origin = Origin(origin) if isinstance(origin, str) else origin38 self.ssl = SSLConfig(cert=cert, verify=verify)39 self.timeout = TimeoutConfig(timeout)40 self.backend = AsyncioBackend() if backend is None else backend41 self.release_func = release_func42 self.h11_connection = None # type: typing.Optional[HTTP11Connection]43 self.h2_connection = None # type: typing.Optional[HTTP2Connection]4445 async def send(46 self,47 request: AsyncRequest,48 verify: VerifyTypes = None,49 cert: CertTypes = None,50 timeout: TimeoutTypes = None,51 ) -> AsyncResponse:52 if self.h11_connection is None and self.h2_connection is None:53 await self.connect(verify=verify, cert=cert, timeout=timeout)5455 if self.h2_connection is not None:56 response = await self.h2_connection.send(request, timeout=timeout)57 else:58 assert self.h11_connection is not None59 response = await self.h11_connection.send(request, timeout=timeout)6061 return response6263 async def connect(64 self,65 verify: VerifyTypes = None,66 cert: CertTypes = None,67 timeout: TimeoutTypes = None,68 ) -> None:69 ssl = self.ssl.with_overrides(verify=verify, cert=cert)70 timeout = self.timeout if timeout is None else TimeoutConfig(timeout)7172 host = self.origin.host73 port = self.origin.port74 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None7576 if self.release_func is None:77 on_release = None78 else:79 on_release = functools.partial(self.release_func, self)8081 reader, writer, protocol = await self.backend.connect(82 host, port, ssl_context, timeout83 )84 if protocol == Protocol.HTTP_2:85 self.h2_connection = HTTP2Connection(reader, writer, on_release=on_release)86 else:87 self.h11_connection = HTTP11Connection(88 reader, writer, on_release=on_release89 )9091 async def close(self) -> None:92 if self.h2_connection is not None:93 await self.h2_connection.close()94 elif self.h11_connection is not None:95 await self.h11_connection.close()9697 @property98 def is_http2(self) -> bool:99 return self.h2_connection is not None100101 @property102 def is_closed(self) -> bool:103 if self.h2_connection is not None:104 return self.h2_connection.is_closed105 else:106 assert self.h11_connection is not None107 return self.h11_connection.is_closed
deleted:httpcore/dispatch/http11.py-127 removed
1import typing23import h1145from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes6from ..exceptions import ConnectTimeout, ReadTimeout7from ..interfaces import BaseReader, BaseWriter8from ..models import AsyncRequest, AsyncResponse910H11Event = typing.Union[11 h11.Request,12 h11.Response,13 h11.InformationalResponse,14 h11.Data,15 h11.EndOfMessage,16 h11.ConnectionClosed,17]181920# Callback signature: async def callback() -> None21# In practice the callback will be a functools partial, which binds22# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.23OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]242526class HTTP11Connection:27 READ_NUM_BYTES = 40962829 def __init__(30 self,31 reader: BaseReader,32 writer: BaseWriter,33 on_release: typing.Optional[OnReleaseCallback] = None,34 ):35 self.reader = reader36 self.writer = writer37 self.on_release = on_release38 self.h11_state = h11.Connection(our_role=h11.CLIENT)3940 async def send(41 self, request: AsyncRequest, timeout: TimeoutTypes = None42 ) -> AsyncResponse:43 timeout = None if timeout is None else TimeoutConfig(timeout)4445 #  Start sending the request.46 method = request.method.encode("ascii")47 target = request.url.full_path.encode("ascii")48 headers = request.headers.raw49 if "Host" not in request.headers:50 host = request.url.authority.encode("ascii")51 headers = [(b"host", host)] + headers52 event = h11.Request(method=method, target=target, headers=headers)53 await self._send_event(event, timeout)5455 # Send the request body.56 async for data in request.stream():57 event = h11.Data(data=data)58 await self._send_event(event, timeout)5960 # Finalize sending the request.61 event = h11.EndOfMessage()62 await self._send_event(event, timeout)6364 # Start getting the response.65 event = await self._receive_event(timeout)66 if isinstance(event, h11.InformationalResponse):67 event = await self._receive_event(timeout)6869 assert isinstance(event, h11.Response)70 reason_phrase = event.reason.decode("ascii", errors="ignore")71 status_code = event.status_code72 headers = event.headers73 content = self._body_iter(timeout)7475 return AsyncResponse(76 status_code=status_code,77 reason_phrase=reason_phrase,78 protocol="HTTP/1.1",79 headers=headers,80 content=content,81 on_close=self.response_closed,82 request=request,83 )8485 async def close(self) -> None:86 event = h11.ConnectionClosed()87 self.h11_state.send(event)88 await self.writer.close()8990 async def _body_iter(91 self, timeout: TimeoutConfig = None92 ) -> typing.AsyncIterator[bytes]:93 event = await self._receive_event(timeout)94 while isinstance(event, h11.Data):95 yield event.data96 event = await self._receive_event(timeout)97 assert isinstance(event, h11.EndOfMessage)9899 async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:100 data = self.h11_state.send(event)101 await self.writer.write(data, timeout)102103 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:104 event = self.h11_state.next_event()105106 while event is h11.NEED_DATA:107 data = await self.reader.read(self.READ_NUM_BYTES, timeout)108 self.h11_state.receive_data(data)109 event = self.h11_state.next_event()110111 return event112113 async def response_closed(self) -> None:114 if (115 self.h11_state.our_state is h11.DONE116 and self.h11_state.their_state is h11.DONE117 ):118 self.h11_state.start_next_cycle()119 else:120 await self.close()121122 if self.on_release is not None:123 await self.on_release()124125 @property126 def is_closed(self) -> bool:127 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)
deleted:httpcore/dispatch/http2.py-141 removed
1import functools2import typing34import h2.connection5import h2.events67from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes8from ..exceptions import ConnectTimeout, ReadTimeout9from ..interfaces import BaseReader, BaseWriter10from ..models import AsyncRequest, AsyncResponse111213class HTTP2Connection:14 READ_NUM_BYTES = 40961516 def __init__(17 self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None18 ):19 self.reader = reader20 self.writer = writer21 self.on_release = on_release22 self.h2_state = h2.connection.H2Connection()23 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]24 self.initialized = False2526 async def send(27 self, request: AsyncRequest, timeout: TimeoutTypes = None28 ) -> AsyncResponse:29 timeout = None if timeout is None else TimeoutConfig(timeout)3031 #  Start sending the request.32 if not self.initialized:33 self.initiate_connection()3435 stream_id = await self.send_headers(request, timeout)36 self.events[stream_id] = []3738 # Send the request body.39 async for data in request.stream():40 await self.send_data(stream_id, data, timeout)4142 # Finalize sending the request.43 await self.end_stream(stream_id, timeout)4445 # Start getting the response.46 while True:47 event = await self.receive_event(stream_id, timeout)48 if isinstance(event, h2.events.ResponseReceived):49 break5051 status_code = 20052 headers = []53 for k, v in event.headers:54 if k == b":status":55 status_code = int(v.decode("ascii", errors="ignore"))56 elif not k.startswith(b":"):57 headers.append((k, v))5859 content = self.body_iter(stream_id, timeout)60 on_close = functools.partial(self.response_closed, stream_id=stream_id)6162 return AsyncResponse(63 status_code=status_code,64 protocol="HTTP/2",65 headers=headers,66 content=content,67 on_close=on_close,68 request=request,69 )7071 async def close(self) -> None:72 await self.writer.close()7374 def initiate_connection(self) -> None:75 self.h2_state.initiate_connection()76 data_to_send = self.h2_state.data_to_send()77 self.writer.write_no_block(data_to_send)78 self.initialized = True7980 async def send_headers(81 self, request: AsyncRequest, timeout: TimeoutConfig = None82 ) -> int:83 stream_id = self.h2_state.get_next_available_stream_id()84 headers = [85 (b":method", request.method.encode("ascii")),86 (b":authority", request.url.authority.encode("ascii")),87 (b":scheme", request.url.scheme.encode("ascii")),88 (b":path", request.url.full_path.encode("ascii")),89 ] + request.headers.raw90 self.h2_state.send_headers(stream_id, headers)91 data_to_send = self.h2_state.data_to_send()92 await self.writer.write(data_to_send, timeout)93 return stream_id9495 async def send_data(96 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None97 ) -> None:98 self.h2_state.send_data(stream_id, data)99 data_to_send = self.h2_state.data_to_send()100 await self.writer.write(data_to_send, timeout)101102 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:103 self.h2_state.end_stream(stream_id)104 data_to_send = self.h2_state.data_to_send()105 await self.writer.write(data_to_send, timeout)106107 async def body_iter(108 self, stream_id: int, timeout: TimeoutConfig = None109 ) -> typing.AsyncIterator[bytes]:110 while True:111 event = await self.receive_event(stream_id, timeout)112 if isinstance(event, h2.events.DataReceived):113 self.h2_state.acknowledge_received_data(len(event.data), stream_id)114 yield event.data115 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):116 break117118 async def receive_event(119 self, stream_id: int, timeout: TimeoutConfig = None120 ) -> h2.events.Event:121 while not self.events[stream_id]:122 data = await self.reader.read(self.READ_NUM_BYTES, timeout)123 events = self.h2_state.receive_data(data)124 for event in events:125 if getattr(event, "stream_id", 0):126 self.events[event.stream_id].append(event)127128 data_to_send = self.h2_state.data_to_send()129 await self.writer.write(data_to_send, timeout)130131 return self.events[stream_id].pop(0)132133 async def response_closed(self, stream_id: int) -> None:134 del self.events[stream_id]135136 if not self.events and self.on_release is not None:137 await self.on_release()138139 @property140 def is_closed(self) -> bool:141 return False
deleted:httpcore/dispatch/threaded.py-97 removed
1from ..config import CertTypes, TimeoutTypes, VerifyTypes2from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3from ..models import (4 AsyncRequest,5 AsyncRequestData,6 AsyncResponse,7 AsyncResponseContent,8 Request,9 RequestData,10 Response,11 ResponseContent,12)131415class ThreadedDispatcher(AsyncDispatcher):16 """17 The ThreadedDispatcher class is used to mediate between the Client18 (which always uses async under the hood), and a synchronous `Dispatch`19 class.20 """2122 def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23 self.sync_dispatcher = dispatch24 self.backend = backend2526 async def send(27 self,28 request: AsyncRequest,29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,32 ) -> AsyncResponse:33 concurrency_backend = self.backend3435 data = getattr(request, "content", getattr(request, "content_aiter", None))36 sync_data = self._sync_request_data(data)3738 sync_request = Request(39 method=request.method,40 url=request.url,41 headers=request.headers,42 data=sync_data,43 )4445 func = self.sync_dispatcher.send46 kwargs = {47 "request": sync_request,48 "verify": verify,49 "cert": cert,50 "timeout": timeout,51 }52 sync_response = await self.backend.run_in_threadpool(func, **kwargs)53 assert isinstance(sync_response, Response)5455 content = getattr(56 sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57 )5859 async_content = self._async_response_content(content)6061 async def async_on_close() -> None:62 nonlocal concurrency_backend, sync_response63 await concurrency_backend.run_in_threadpool(sync_response.close)6465 return AsyncResponse(66 status_code=sync_response.status_code,67 reason_phrase=sync_response.reason_phrase,68 protocol=sync_response.protocol,69 headers=sync_response.headers,70 content=async_content,71 on_close=async_on_close,72 request=request,73 history=sync_response.history,74 )7576 async def close(self) -> None:77 """78 The `.close()` method runs the `Dispatcher.close()` within a threadpool,79 so as not to block the async event loop.80 """81 func = self.sync_dispatcher.close82 await self.backend.run_in_threadpool(func)8384 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85 if isinstance(content, bytes):86 return content8788 # Coerce an async iterator into an iterator, with each item in the89 # iteration run within the event loop.90 assert hasattr(content, "__iter__")91 return self.backend.iterate_in_threadpool(content)9293 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94 if isinstance(data, bytes):95 return data9697 return self.backend.iterate(data)
deleted:httpcore/__init__.py-52 removed
1from .api import delete, get, head, options, patch, post, put, request2from .client import AsyncClient, Client3from .concurrency import AsyncioBackend4from .config import (5 CertTypes,6 PoolLimits,7 SSLConfig,8 TimeoutConfig,9 TimeoutTypes,10 VerifyTypes,11)12from .dispatch.connection import HTTPConnection13from .dispatch.connection_pool import ConnectionPool14from .exceptions import (15 ConnectTimeout,16 CookieConflict,17 DecodingError,18 InvalidURL,19 PoolTimeout,20 ProtocolError,21 ReadTimeout,22 RedirectBodyUnavailable,23 RedirectLoop,24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27 Timeout,28 TooManyRedirects,29 WriteTimeout,30)31from .interfaces import (32 AsyncDispatcher,33 BaseReader,34 BaseWriter,35 ConcurrencyBackend,36 Dispatcher,37 Protocol,38)39from .models import (40 URL,41 AsyncRequest,42 AsyncResponse,43 Cookies,44 Headers,45 Origin,46 QueryParams,47 Request,48 Response,49)50from .status_codes import StatusCode, codes5152__version__ = "0.4.0"
deleted:httpcore/api.py-261 removed
1import typing23from .client import Client4from .config import CertTypes, TimeoutTypes, VerifyTypes5from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 RequestData,11 Response,12 URLTypes,13)141516def request(17 method: str,18 url: URLTypes,19 *,20 params: QueryParamTypes = None,21 data: RequestData = b"",22 json: typing.Any = None,23 headers: HeaderTypes = None,24 cookies: CookieTypes = None,25 # files26 auth: AuthTypes = None,27 timeout: TimeoutTypes = None,28 allow_redirects: bool = True,29 # proxies30 cert: CertTypes = None,31 verify: VerifyTypes = True,32 stream: bool = False,33) -> Response:34 with Client() as client:35 return client.request(36 method=method,37 url=url,38 data=data,39 json=json,40 params=params,41 headers=headers,42 cookies=cookies,43 stream=stream,44 auth=auth,45 allow_redirects=allow_redirects,46 cert=cert,47 verify=verify,48 timeout=timeout,49 )505152def get(53 url: URLTypes,54 *,55 params: QueryParamTypes = None,56 headers: HeaderTypes = None,57 cookies: CookieTypes = None,58 stream: bool = False,59 auth: AuthTypes = None,60 allow_redirects: bool = True,61 cert: CertTypes = None,62 verify: VerifyTypes = True,63 timeout: TimeoutTypes = None,64) -> Response:65 return request(66 "GET",67 url,68 params=params,69 headers=headers,70 cookies=cookies,71 stream=stream,72 auth=auth,73 allow_redirects=allow_redirects,74 cert=cert,75 verify=verify,76 timeout=timeout,77 )787980def options(81 url: URLTypes,82 *,83 params: QueryParamTypes = None,84 headers: HeaderTypes = None,85 cookies: CookieTypes = None,86 stream: bool = False,87 auth: AuthTypes = None,88 allow_redirects: bool = True,89 cert: CertTypes = None,90 verify: VerifyTypes = True,91 timeout: TimeoutTypes = None,92) -> Response:93 return request(94 "OPTIONS",95 url,96 params=params,97 headers=headers,98 cookies=cookies,99 stream=stream,100 auth=auth,101 allow_redirects=allow_redirects,102 cert=cert,103 verify=verify,104 timeout=timeout,105 )106107108def head(109 url: URLTypes,110 *,111 params: QueryParamTypes = None,112 headers: HeaderTypes = None,113 cookies: CookieTypes = None,114 stream: bool = False,115 auth: AuthTypes = None,116 allow_redirects: bool = False, #  Note: Differs to usual default.117 cert: CertTypes = None,118 verify: VerifyTypes = True,119 timeout: TimeoutTypes = None,120) -> Response:121 return request(122 "HEAD",123 url,124 params=params,125 headers=headers,126 cookies=cookies,127 stream=stream,128 auth=auth,129 allow_redirects=allow_redirects,130 cert=cert,131 verify=verify,132 timeout=timeout,133 )134135136def post(137 url: URLTypes,138 *,139 data: RequestData = b"",140 json: typing.Any = None,141 params: QueryParamTypes = None,142 headers: HeaderTypes = None,143 cookies: CookieTypes = None,144 stream: bool = False,145 auth: AuthTypes = None,146 allow_redirects: bool = True,147 cert: CertTypes = None,148 verify: VerifyTypes = True,149 timeout: TimeoutTypes = None,150) -> Response:151 return request(152 "POST",153 url,154 data=data,155 json=json,156 params=params,157 headers=headers,158 cookies=cookies,159 stream=stream,160 auth=auth,161 allow_redirects=allow_redirects,162 cert=cert,163 verify=verify,164 timeout=timeout,165 )166167168def put(169 url: URLTypes,170 *,171 data: RequestData = b"",172 json: typing.Any = None,173 params: QueryParamTypes = None,174 headers: HeaderTypes = None,175 cookies: CookieTypes = None,176 stream: bool = False,177 auth: AuthTypes = None,178 allow_redirects: bool = True,179 cert: CertTypes = None,180 verify: VerifyTypes = True,181 timeout: TimeoutTypes = None,182) -> Response:183 return request(184 "PUT",185 url,186 data=data,187 json=json,188 params=params,189 headers=headers,190 cookies=cookies,191 stream=stream,192 auth=auth,193 allow_redirects=allow_redirects,194 cert=cert,195 verify=verify,196 timeout=timeout,197 )198199200def patch(201 url: URLTypes,202 *,203 data: RequestData = b"",204 json: typing.Any = None,205 params: QueryParamTypes = None,206 headers: HeaderTypes = None,207 cookies: CookieTypes = None,208 stream: bool = False,209 auth: AuthTypes = None,210 allow_redirects: bool = True,211 cert: CertTypes = None,212 verify: VerifyTypes = True,213 timeout: TimeoutTypes = None,214) -> Response:215 return request(216 "PATCH",217 url,218 data=data,219 json=json,220 params=params,221 headers=headers,222 cookies=cookies,223 stream=stream,224 auth=auth,225 allow_redirects=allow_redirects,226 cert=cert,227 verify=verify,228 timeout=timeout,229 )230231232def delete(233 url: URLTypes,234 *,235 data: RequestData = b"",236 json: typing.Any = None,237 params: QueryParamTypes = None,238 headers: HeaderTypes = None,239 cookies: CookieTypes = None,240 stream: bool = False,241 auth: AuthTypes = None,242 allow_redirects: bool = True,243 cert: CertTypes = None,244 verify: VerifyTypes = True,245 timeout: TimeoutTypes = None,246) -> Response:247 return request(248 "DELETE",249 url,250 data=data,251 json=json,252 params=params,253 headers=headers,254 cookies=cookies,255 stream=stream,256 auth=auth,257 allow_redirects=allow_redirects,258 cert=cert,259 verify=verify,260 timeout=timeout,261 )
deleted:httpcore/auth.py-38 removed
1import typing2from base64 import b64encode34from .models import AsyncRequest567class AuthBase:8 """9 Base class that all auth implementations derive from.10 """1112 def __call__(self, request: AsyncRequest) -> AsyncRequest:13 raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover141516class HTTPBasicAuth(AuthBase):17 def __init__(18 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]19 ) -> None:20 self.username = username21 self.password = password2223 def __call__(self, request: AsyncRequest) -> AsyncRequest:24 request.headers["Authorization"] = self.build_auth_header()25 return request2627 def build_auth_header(self) -> str:28 username, password = self.username, self.password2930 if isinstance(username, str):31 username = username.encode("latin1")3233 if isinstance(password, str):34 password = password.encode("latin1")3536 userpass = b":".join((username, password))37 token = b64encode(userpass).decode().strip()38 return f"Basic {token}"
deleted:httpcore/client.py-831 removed
1import typing2from types import TracebackType34from .auth import HTTPBasicAuth5from .concurrency import AsyncioBackend6from .config import (7 DEFAULT_MAX_REDIRECTS,8 DEFAULT_POOL_LIMITS,9 DEFAULT_TIMEOUT_CONFIG,10 CertTypes,11 PoolLimits,12 TimeoutTypes,13 VerifyTypes,14)15from .dispatch.connection_pool import ConnectionPool16from .dispatch.threaded import ThreadedDispatcher17from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects18from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher19from .models import (20 URL,21 AsyncRequest,22 AsyncRequestData,23 AsyncResponse,24 AsyncResponseContent,25 AuthTypes,26 Cookies,27 CookieTypes,28 Headers,29 HeaderTypes,30 QueryParamTypes,31 Request,32 RequestData,33 Response,34 ResponseContent,35 URLTypes,36)37from .status_codes import codes383940class BaseClient:41 def __init__(42 self,43 auth: AuthTypes = None,44 cookies: CookieTypes = None,45 verify: VerifyTypes = True,46 cert: CertTypes = None,47 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,48 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,49 max_redirects: int = DEFAULT_MAX_REDIRECTS,50 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,51 backend: ConcurrencyBackend = None,52 ):53 if backend is None:54 backend = AsyncioBackend()5556 if dispatch is None:57 async_dispatch = ConnectionPool(58 verify=verify,59 cert=cert,60 timeout=timeout,61 pool_limits=pool_limits,62 backend=backend,63 ) # type: AsyncDispatcher64 elif isinstance(dispatch, Dispatcher):65 async_dispatch = ThreadedDispatcher(dispatch, backend)66 else:67 async_dispatch = dispatch6869 self.auth = auth70 self.cookies = Cookies(cookies)71 self.max_redirects = max_redirects72 self.dispatch = async_dispatch73 self.concurrency_backend = backend7475 def merge_cookies(76 self, cookies: CookieTypes = None77 ) -> typing.Optional[CookieTypes]:78 if cookies or self.cookies:79 merged_cookies = Cookies(self.cookies)80 merged_cookies.update(cookies)81 return merged_cookies82 return cookies8384 async def send(85 self,86 request: AsyncRequest,87 *,88 stream: bool = False,89 auth: AuthTypes = None,90 allow_redirects: bool = True,91 verify: VerifyTypes = None,92 cert: CertTypes = None,93 timeout: TimeoutTypes = None,94 ) -> AsyncResponse:95 if auth is None:96 auth = self.auth9798 url = request.url99 if auth is None and (url.username or url.password):100 auth = HTTPBasicAuth(username=url.username, password=url.password)101102 if auth is not None:103 if isinstance(auth, tuple):104 auth = HTTPBasicAuth(username=auth[0], password=auth[1])105 request = auth(request)106107 response = await self.send_handling_redirects(108 request,109 verify=verify,110 cert=cert,111 timeout=timeout,112 allow_redirects=allow_redirects,113 )114115 if not stream:116 try:117 await response.read()118 finally:119 await response.close()120121 return response122123 async def send_handling_redirects(124 self,125 request: AsyncRequest,126 *,127 cert: CertTypes = None,128 verify: VerifyTypes = None,129 timeout: TimeoutTypes = None,130 allow_redirects: bool = True,131 history: typing.List[AsyncResponse] = None,132 ) -> AsyncResponse:133 if history is None:134 history = []135136 while True:137 # We perform these checks here, so that calls to `response.next()`138 # will raise redirect errors if appropriate.139 if len(history) > self.max_redirects:140 raise TooManyRedirects()141 if request.url in [response.url for response in history]:142 raise RedirectLoop()143144 response = await self.dispatch.send(145 request, verify=verify, cert=cert, timeout=timeout146 )147 assert isinstance(response, AsyncResponse)148 response.history = list(history)149 self.cookies.extract_cookies(response)150 history = [response] + history151 if not response.is_redirect:152 break153154 if allow_redirects:155 request = self.build_redirect_request(request, response)156 else:157158 async def send_next() -> AsyncResponse:159 nonlocal request, response, verify, cert, allow_redirects, timeout, history160 request = self.build_redirect_request(request, response)161 response = await self.send_handling_redirects(162 request,163 allow_redirects=allow_redirects,164 verify=verify,165 cert=cert,166 timeout=timeout,167 history=history,168 )169 return response170171 response.next = send_next # type: ignore172 break173174 return response175176 def build_redirect_request(177 self, request: AsyncRequest, response: AsyncResponse178 ) -> AsyncRequest:179 method = self.redirect_method(request, response)180 url = self.redirect_url(request, response)181 headers = self.redirect_headers(request, url)182 content = self.redirect_content(request, method)183 cookies = self.merge_cookies(request.cookies)184 return AsyncRequest(185 method=method, url=url, headers=headers, data=content, cookies=cookies186 )187188 def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:189 """190 When being redirected we may want to change the method of the request191 based on certain specs or browser behavior.192 """193 method = request.method194195 # https://tools.ietf.org/html/rfc7231#section-6.4.4196 if response.status_code == codes.SEE_OTHER and method != "HEAD":197 method = "GET"198199 # Do what the browsers do, despite standards...200 # Turn 302s into GETs.201 if response.status_code == codes.FOUND and method != "HEAD":202 method = "GET"203204 # If a POST is responded to with a 301, turn it into a GET.205 # This bizarre behaviour is explained in 'requests' issue 1704.206 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":207 method = "GET"208209 return method210211 def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:212 """213 Return the URL for the redirect to follow.214 """215 location = response.headers["Location"]216217 url = URL(location, allow_relative=True)218219 # Facilitate relative 'Location' headers, as allowed by RFC 7231.220 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')221 if url.is_relative_url:222 url = url.resolve_with(request.url)223224 # Attach previous fragment if needed (RFC 7231 7.1.2)225 if request.url.fragment and not url.fragment:226 url = url.copy_with(fragment=request.url.fragment)227228 return url229230 def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:231 """232 Strip Authorization headers when responses are redirected away from233 the origin.234 """235 headers = Headers(request.headers)236 if url.origin != request.url.origin:237 del headers["Authorization"]238 return headers239240 def redirect_content(self, request: AsyncRequest, method: str) -> bytes:241 """242 Return the body that should be used for the redirect request.243 """244 if method != request.method and method == "GET":245 return b""246 if request.is_streaming:247 raise RedirectBodyUnavailable()248 return request.content249250251class AsyncClient(BaseClient):252 async def get(253 self,254 url: URLTypes,255 *,256 params: QueryParamTypes = None,257 headers: HeaderTypes = None,258 cookies: CookieTypes = None,259 stream: bool = False,260 auth: AuthTypes = None,261 allow_redirects: bool = True,262 cert: CertTypes = None,263 verify: VerifyTypes = None,264 timeout: TimeoutTypes = None,265 ) -> AsyncResponse:266 return await self.request(267 "GET",268 url,269 params=params,270 headers=headers,271 cookies=cookies,272 stream=stream,273 auth=auth,274 allow_redirects=allow_redirects,275 verify=verify,276 cert=cert,277 timeout=timeout,278 )279280 async def options(281 self,282 url: URLTypes,283 *,284 params: QueryParamTypes = None,285 headers: HeaderTypes = None,286 cookies: CookieTypes = None,287 stream: bool = False,288 auth: AuthTypes = None,289 allow_redirects: bool = True,290 cert: CertTypes = None,291 verify: VerifyTypes = None,292 timeout: TimeoutTypes = None,293 ) -> AsyncResponse:294 return await self.request(295 "OPTIONS",296 url,297 params=params,298 headers=headers,299 cookies=cookies,300 stream=stream,301 auth=auth,302 allow_redirects=allow_redirects,303 verify=verify,304 cert=cert,305 timeout=timeout,306 )307308 async def head(309 self,310 url: URLTypes,311 *,312 params: QueryParamTypes = None,313 headers: HeaderTypes = None,314 cookies: CookieTypes = None,315 stream: bool = False,316 auth: AuthTypes = None,317 allow_redirects: bool = False, #  Note: Differs to usual default.318 cert: CertTypes = None,319 verify: VerifyTypes = None,320 timeout: TimeoutTypes = None,321 ) -> AsyncResponse:322 return await self.request(323 "HEAD",324 url,325 params=params,326 headers=headers,327 cookies=cookies,328 stream=stream,329 auth=auth,330 allow_redirects=allow_redirects,331 verify=verify,332 cert=cert,333 timeout=timeout,334 )335336 async def post(337 self,338 url: URLTypes,339 *,340 data: AsyncRequestData = b"",341 json: typing.Any = None,342 params: QueryParamTypes = None,343 headers: HeaderTypes = None,344 cookies: CookieTypes = None,345 stream: bool = False,346 auth: AuthTypes = None,347 allow_redirects: bool = True,348 cert: CertTypes = None,349 verify: VerifyTypes = None,350 timeout: TimeoutTypes = None,351 ) -> AsyncResponse:352 return await self.request(353 "POST",354 url,355 data=data,356 json=json,357 params=params,358 headers=headers,359 cookies=cookies,360 stream=stream,361 auth=auth,362 allow_redirects=allow_redirects,363 verify=verify,364 cert=cert,365 timeout=timeout,366 )367368 async def put(369 self,370 url: URLTypes,371 *,372 data: AsyncRequestData = b"",373 json: typing.Any = None,374 params: QueryParamTypes = None,375 headers: HeaderTypes = None,376 cookies: CookieTypes = None,377 stream: bool = False,378 auth: AuthTypes = None,379 allow_redirects: bool = True,380 cert: CertTypes = None,381 verify: VerifyTypes = None,382 timeout: TimeoutTypes = None,383 ) -> AsyncResponse:384 return await self.request(385 "PUT",386 url,387 data=data,388 json=json,389 params=params,390 headers=headers,391 cookies=cookies,392 stream=stream,393 auth=auth,394 allow_redirects=allow_redirects,395 verify=verify,396 cert=cert,397 timeout=timeout,398 )399400 async def patch(401 self,402 url: URLTypes,403 *,404 data: AsyncRequestData = b"",405 json: typing.Any = None,406 params: QueryParamTypes = None,407 headers: HeaderTypes = None,408 cookies: CookieTypes = None,409 stream: bool = False,410 auth: AuthTypes = None,411 allow_redirects: bool = True,412 cert: CertTypes = None,413 verify: VerifyTypes = None,414 timeout: TimeoutTypes = None,415 ) -> AsyncResponse:416 return await self.request(417 "PATCH",418 url,419 data=data,420 json=json,421 params=params,422 headers=headers,423 cookies=cookies,424 stream=stream,425 auth=auth,426 allow_redirects=allow_redirects,427 verify=verify,428 cert=cert,429 timeout=timeout,430 )431432 async def delete(433 self,434 url: URLTypes,435 *,436 data: AsyncRequestData = b"",437 json: typing.Any = None,438 params: QueryParamTypes = None,439 headers: HeaderTypes = None,440 cookies: CookieTypes = None,441 stream: bool = False,442 auth: AuthTypes = None,443 allow_redirects: bool = True,444 cert: CertTypes = None,445 verify: VerifyTypes = None,446 timeout: TimeoutTypes = None,447 ) -> AsyncResponse:448 return await self.request(449 "DELETE",450 url,451 data=data,452 json=json,453 params=params,454 headers=headers,455 cookies=cookies,456 stream=stream,457 auth=auth,458 allow_redirects=allow_redirects,459 verify=verify,460 cert=cert,461 timeout=timeout,462 )463464 async def request(465 self,466 method: str,467 url: URLTypes,468 *,469 data: AsyncRequestData = b"",470 json: typing.Any = None,471 params: QueryParamTypes = None,472 headers: HeaderTypes = None,473 cookies: CookieTypes = None,474 stream: bool = False,475 auth: AuthTypes = None,476 allow_redirects: bool = True,477 cert: CertTypes = None,478 verify: VerifyTypes = None,479 timeout: TimeoutTypes = None,480 ) -> AsyncResponse:481 request = AsyncRequest(482 method,483 url,484 data=data,485 json=json,486 params=params,487 headers=headers,488 cookies=self.merge_cookies(cookies),489 )490 response = await self.send(491 request,492 stream=stream,493 auth=auth,494 allow_redirects=allow_redirects,495 verify=verify,496 cert=cert,497 timeout=timeout,498 )499 return response500501 async def close(self) -> None:502 await self.dispatch.close()503504 async def __aenter__(self) -> "AsyncClient":505 return self506507 async def __aexit__(508 self,509 exc_type: typing.Type[BaseException] = None,510 exc_value: BaseException = None,511 traceback: TracebackType = None,512 ) -> None:513 await self.close()514515516class Client(BaseClient):517 def _async_request_data(self, data: RequestData) -> AsyncRequestData:518 """519 If the request data is an bytes iterator then return an async bytes520 iterator onto the request data.521 """522 if isinstance(data, (bytes, dict)):523 return data524525 # Coerce an iterator into an async iterator, with each item in the526 # iteration running as a thread-pooled operation.527 assert hasattr(data, "__iter__")528 return self.concurrency_backend.iterate_in_threadpool(data)529530 def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:531 if isinstance(data, bytes):532 return data533534 # Coerce an async iterator into an iterator, with each item in the535 # iteration run within the event loop.536 assert hasattr(data, "__aiter__")537 return self.concurrency_backend.iterate(data)538539 def request(540 self,541 method: str,542 url: URLTypes,543 *,544 data: RequestData = b"",545 json: typing.Any = None,546 params: QueryParamTypes = None,547 headers: HeaderTypes = None,548 cookies: CookieTypes = None,549 stream: bool = False,550 auth: AuthTypes = None,551 allow_redirects: bool = True,552 cert: CertTypes = None,553 verify: VerifyTypes = None,554 timeout: TimeoutTypes = None,555 ) -> Response:556 request = AsyncRequest(557 method,558 url,559 data=self._async_request_data(data),560 json=json,561 params=params,562 headers=headers,563 cookies=self.merge_cookies(cookies),564 )565 concurrency_backend = self.concurrency_backend566567 coroutine = self.send568 args = [request]569 kwargs = dict(570 stream=True,571 auth=auth,572 allow_redirects=allow_redirects,573 verify=verify,574 cert=cert,575 timeout=timeout,576 )577 async_response = concurrency_backend.run(coroutine, *args, **kwargs)578579 content = getattr(580 async_response, "_raw_content", getattr(async_response, "_raw_stream", None)581 )582583 sync_content = self._sync_data(content)584585 def sync_on_close() -> None:586 nonlocal concurrency_backend, async_response587 concurrency_backend.run(async_response.on_close)588589 response = Response(590 status_code=async_response.status_code,591 reason_phrase=async_response.reason_phrase,592 protocol=async_response.protocol,593 headers=async_response.headers,594 content=sync_content,595 on_close=sync_on_close,596 request=async_response.request,597 history=async_response.history,598 )599 if not stream:600 try:601 response.read()602 finally:603 response.close()604 return response605606 def get(607 self,608 url: URLTypes,609 *,610 params: QueryParamTypes = None,611 headers: HeaderTypes = None,612 cookies: CookieTypes = None,613 stream: bool = False,614 auth: AuthTypes = None,615 allow_redirects: bool = True,616 cert: CertTypes = None,617 verify: VerifyTypes = None,618 timeout: TimeoutTypes = None,619 ) -> Response:620 return self.request(621 "GET",622 url,623 params=params,624 headers=headers,625 cookies=cookies,626 stream=stream,627 auth=auth,628 allow_redirects=allow_redirects,629 verify=verify,630 cert=cert,631 timeout=timeout,632 )633634 def options(635 self,636 url: URLTypes,637 *,638 params: QueryParamTypes = None,639 headers: HeaderTypes = None,640 cookies: CookieTypes = None,641 stream: bool = False,642 auth: AuthTypes = None,643 allow_redirects: bool = True,644 cert: CertTypes = None,645 verify: VerifyTypes = None,646 timeout: TimeoutTypes = None,647 ) -> Response:648 return self.request(649 "OPTIONS",650 url,651 params=params,652 headers=headers,653 cookies=cookies,654 stream=stream,655 auth=auth,656 allow_redirects=allow_redirects,657 verify=verify,658 cert=cert,659 timeout=timeout,660 )661662 def head(663 self,664 url: URLTypes,665 *,666 params: QueryParamTypes = None,667 headers: HeaderTypes = None,668 cookies: CookieTypes = None,669 stream: bool = False,670 auth: AuthTypes = None,671 allow_redirects: bool = False, #  Note: Differs to usual default.672 cert: CertTypes = None,673 verify: VerifyTypes = None,674 timeout: TimeoutTypes = None,675 ) -> Response:676 return self.request(677 "HEAD",678 url,679 params=params,680 headers=headers,681 cookies=cookies,682 stream=stream,683 auth=auth,684 allow_redirects=allow_redirects,685 verify=verify,686 cert=cert,687 timeout=timeout,688 )689690 def post(691 self,692 url: URLTypes,693 *,694 data: RequestData = b"",695 json: typing.Any = None,696 params: QueryParamTypes = None,697 headers: HeaderTypes = None,698 cookies: CookieTypes = None,699 stream: bool = False,700 auth: AuthTypes = None,701 allow_redirects: bool = True,702 cert: CertTypes = None,703 verify: VerifyTypes = None,704 timeout: TimeoutTypes = None,705 ) -> Response:706 return self.request(707 "POST",708 url,709 data=data,710 json=json,711 params=params,712 headers=headers,713 cookies=cookies,714 stream=stream,715 auth=auth,716 allow_redirects=allow_redirects,717 verify=verify,718 cert=cert,719 timeout=timeout,720 )721722 def put(723 self,724 url: URLTypes,725 *,726 data: RequestData = b"",727 json: typing.Any = None,728 params: QueryParamTypes = None,729 headers: HeaderTypes = None,730 cookies: CookieTypes = None,731 stream: bool = False,732 auth: AuthTypes = None,733 allow_redirects: bool = True,734 cert: CertTypes = None,735 verify: VerifyTypes = None,736 timeout: TimeoutTypes = None,737 ) -> Response:738 return self.request(739 "PUT",740 url,741 data=data,742 json=json,743 params=params,744 headers=headers,745 cookies=cookies,746 stream=stream,747 auth=auth,748 allow_redirects=allow_redirects,749 verify=verify,750 cert=cert,751 timeout=timeout,752 )753754 def patch(755 self,756 url: URLTypes,757 *,758 data: RequestData = b"",759 json: typing.Any = None,760 params: QueryParamTypes = None,761 headers: HeaderTypes = None,762 cookies: CookieTypes = None,763 stream: bool = False,764 auth: AuthTypes = None,765 allow_redirects: bool = True,766 cert: CertTypes = None,767 verify: VerifyTypes = None,768 timeout: TimeoutTypes = None,769 ) -> Response:770 return self.request(771 "PATCH",772 url,773 data=data,774 json=json,775 params=params,776 headers=headers,777 cookies=cookies,778 stream=stream,779 auth=auth,780 allow_redirects=allow_redirects,781 verify=verify,782 cert=cert,783 timeout=timeout,784 )785786 def delete(787 self,788 url: URLTypes,789 *,790 data: RequestData = b"",791 json: typing.Any = None,792 params: QueryParamTypes = None,793 headers: HeaderTypes = None,794 cookies: CookieTypes = None,795 stream: bool = False,796 auth: AuthTypes = None,797 allow_redirects: bool = True,798 cert: CertTypes = None,799 verify: VerifyTypes = None,800 timeout: TimeoutTypes = None,801 ) -> Response:802 return self.request(803 "DELETE",804 url,805 data=data,806 json=json,807 params=params,808 headers=headers,809 cookies=cookies,810 stream=stream,811 auth=auth,812 allow_redirects=allow_redirects,813 verify=verify,814 cert=cert,815 timeout=timeout,816 )817818 def close(self) -> None:819 coroutine = self.dispatch.close820 self.concurrency_backend.run(coroutine)821822 def __enter__(self) -> "Client":823 return self824825 def __exit__(826 self,827 exc_type: typing.Type[BaseException] = None,828 exc_value: BaseException = None,829 traceback: TracebackType = None,830 ) -> None:831 self.close()
deleted:httpcore/concurrency.py-195 removed
1"""2The `Reader` and `Writer` classes here provide a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.67These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import functools13import ssl14import typing1516from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18from .interfaces import (19 BasePoolSemaphore,20 BaseReader,21 BaseWriter,22 ConcurrencyBackend,23 Protocol,24)2526SSL_MONKEY_PATCH_APPLIED = False272829def ssl_monkey_patch() -> None:30 """31 Monky-patch for https://bugs.python.org/issue367093233 This prevents console errors when outstanding HTTPS connections34 still exist at the point of exiting.3536 Clients which have been opened using a `with` block, or which have37 had `close()` closed, will not exhibit this issue in the first place.38 """39 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore4041 _write = MonkeyPatch.write4243 def _fixed_write(self, data: bytes) -> None: # type: ignore44 if not self._loop.is_closed():45 _write(self, data)4647 MonkeyPatch.write = _fixed_write484950class Reader(BaseReader):51 def __init__(52 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig53 ) -> None:54 self.stream_reader = stream_reader55 self.timeout = timeout5657 async def read(self, n: int, timeout: TimeoutConfig = None) -> bytes:58 if timeout is None:59 timeout = self.timeout6061 try:62 data = await asyncio.wait_for(63 self.stream_reader.read(n), timeout.read_timeout64 )65 except asyncio.TimeoutError:66 raise ReadTimeout()6768 return data697071class Writer(BaseWriter):72 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):73 self.stream_writer = stream_writer74 self.timeout = timeout7576 def write_no_block(self, data: bytes) -> None:77 self.stream_writer.write(data) # pragma: nocover7879 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:80 if not data:81 return8283 if timeout is None:84 timeout = self.timeout8586 self.stream_writer.write(data)87 try:88 await asyncio.wait_for( # type: ignore89 self.stream_writer.drain(), timeout.write_timeout90 )91 except asyncio.TimeoutError:92 raise WriteTimeout()9394 async def close(self) -> None:95 self.stream_writer.close()969798class PoolSemaphore(BasePoolSemaphore):99 def __init__(self, pool_limits: PoolLimits):100 self.pool_limits = pool_limits101102 @property103 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:104 if not hasattr(self, "_semaphore"):105 max_connections = self.pool_limits.hard_limit106 if max_connections is None:107 self._semaphore = None108 else:109 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)110 return self._semaphore111112 async def acquire(self) -> None:113 if self.semaphore is None:114 return115116 timeout = self.pool_limits.pool_timeout117 try:118 await asyncio.wait_for(self.semaphore.acquire(), timeout)119 except asyncio.TimeoutError:120 raise PoolTimeout()121122 def release(self) -> None:123 if self.semaphore is None:124 return125126 self.semaphore.release()127128129class AsyncioBackend(ConcurrencyBackend):130 def __init__(self) -> None:131 global SSL_MONKEY_PATCH_APPLIED132133 if not SSL_MONKEY_PATCH_APPLIED:134 ssl_monkey_patch()135 SSL_MONKEY_PATCH_APPLIED = True136137 @property138 def loop(self) -> asyncio.AbstractEventLoop:139 if not hasattr(self, "_loop"):140 try:141 self._loop = asyncio.get_event_loop()142 except RuntimeError:143 self._loop = asyncio.new_event_loop()144 return self._loop145146 async def connect(147 self,148 hostname: str,149 port: int,150 ssl_context: typing.Optional[ssl.SSLContext],151 timeout: TimeoutConfig,152 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:153 try:154 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore155 asyncio.open_connection(hostname, port, ssl=ssl_context),156 timeout.connect_timeout,157 )158 except asyncio.TimeoutError:159 raise ConnectTimeout()160161 ssl_object = stream_writer.get_extra_info("ssl_object")162 if ssl_object is None:163 ident = "http/1.1"164 else:165 ident = ssl_object.selected_alpn_protocol()166 if ident is None:167 ident = ssl_object.selected_npn_protocol()168169 reader = Reader(stream_reader=stream_reader, timeout=timeout)170 writer = Writer(stream_writer=stream_writer, timeout=timeout)171 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11172173 return (reader, writer, protocol)174175 async def run_in_threadpool(176 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any177 ) -> typing.Any:178 if kwargs:179 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here180 func = functools.partial(func, **kwargs)181 return await self.loop.run_in_executor(None, func, *args)182183 def run(184 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any185 ) -> typing.Any:186 loop = self.loop187 if loop.is_running():188 self._loop = asyncio.new_event_loop()189 try:190 return self.loop.run_until_complete(coroutine(*args, **kwargs))191 finally:192 self._loop = loop193194 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:195 return PoolSemaphore(limits)
deleted:httpcore/config.py-196 removed
1import asyncio2import os3import ssl4import typing56import certifi78CertTypes = typing.Union[str, typing.Tuple[str, str]]9VerifyTypes = typing.Union[str, bool]10TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]111213class SSLConfig:14 """15 SSL Configuration.16 """1718 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):19 self.cert = cert20 self.verify = verify2122 def __eq__(self, other: typing.Any) -> bool:23 return (24 isinstance(other, self.__class__)25 and self.cert == other.cert26 and self.verify == other.verify27 )2829 def __repr__(self) -> str:30 class_name = self.__class__.__name__31 return f"{class_name}(cert={self.cert}, verify={self.verify})"3233 def with_overrides(34 self, cert: CertTypes = None, verify: VerifyTypes = None35 ) -> "SSLConfig":36 cert = self.cert if cert is None else cert37 verify = self.verify if verify is None else verify38 if (cert == self.cert) and (verify == self.verify):39 return self40 return SSLConfig(cert=cert, verify=verify)4142 async def load_ssl_context(self) -> ssl.SSLContext:43 if not hasattr(self, "ssl_context"):44 if not self.verify:45 self.ssl_context = self.load_ssl_context_no_verify()46 else:47 # Run the SSL loading in a threadpool, since it makes disk accesses.48 loop = asyncio.get_event_loop()49 self.ssl_context = await loop.run_in_executor(50 None, self.load_ssl_context_verify51 )5253 return self.ssl_context5455 def load_ssl_context_no_verify(self) -> ssl.SSLContext:56 """57 Return an SSL context for unverified connections.58 """59 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)60 context.options |= ssl.OP_NO_SSLv261 context.options |= ssl.OP_NO_SSLv362 context.options |= ssl.OP_NO_COMPRESSION63 context.set_default_verify_paths()64 return context6566 def load_ssl_context_verify(self) -> ssl.SSLContext:67 """68 Return an SSL context for verified connections.69 """70 if isinstance(self.verify, bool):71 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH72 elif os.path.exists(self.verify):73 ca_bundle_path = self.verify74 else:75 raise IOError(76 "Could not find a suitable TLS CA certificate bundle, "77 "invalid path: {}".format(self.verify)78 )7980 context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)8182 context.verify_mode = ssl.CERT_REQUIRED8384 context.options |= ssl.OP_NO_SSLv285 context.options |= ssl.OP_NO_SSLv386 context.options |= ssl.OP_NO_COMPRESSION8788 # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST89 # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the90 # blacklist defined in this section allows only the AES GCM and ChaCha2091 # cipher suites with ephemeral key negotiation.92 context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")9394 if ssl.HAS_ALPN:95 context.set_alpn_protocols(["h2", "http/1.1"])96 if ssl.HAS_NPN:97 context.set_npn_protocols(["h2", "http/1.1"])9899 if os.path.isfile(ca_bundle_path):100 context.load_verify_locations(cafile=ca_bundle_path)101 elif os.path.isdir(ca_bundle_path):102 context.load_verify_locations(capath=ca_bundle_path)103104 if self.cert is not None:105 if isinstance(self.cert, str):106 context.load_cert_chain(certfile=self.cert)107 else:108 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])109110 return context111112113class TimeoutConfig:114 """115 Timeout values.116 """117118 def __init__(119 self,120 timeout: TimeoutTypes = None,121 *,122 connect_timeout: float = None,123 read_timeout: float = None,124 write_timeout: float = None,125 ):126 if timeout is None:127 self.connect_timeout = connect_timeout128 self.read_timeout = read_timeout129 self.write_timeout = write_timeout130 else:131 # Specified as a single timeout value132 assert connect_timeout is None133 assert read_timeout is None134 assert write_timeout is None135 if isinstance(timeout, TimeoutConfig):136 self.connect_timeout = timeout.connect_timeout137 self.read_timeout = timeout.read_timeout138 self.write_timeout = timeout.write_timeout139 elif isinstance(timeout, tuple):140 self.connect_timeout = timeout[0]141 self.read_timeout = timeout[1]142 self.write_timeout = timeout[2]143 else:144 self.connect_timeout = timeout145 self.read_timeout = timeout146 self.write_timeout = timeout147148 def __eq__(self, other: typing.Any) -> bool:149 return (150 isinstance(other, self.__class__)151 and self.connect_timeout == other.connect_timeout152 and self.read_timeout == other.read_timeout153 and self.write_timeout == other.write_timeout154 )155156 def __repr__(self) -> str:157 class_name = self.__class__.__name__158 if len(set([self.connect_timeout, self.read_timeout, self.write_timeout])) == 1:159 return f"{class_name}(timeout={self.connect_timeout})"160 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"161162163class PoolLimits:164 """165 Limits on the number of connections in a connection pool.166 """167168 def __init__(169 self,170 *,171 soft_limit: int = None,172 hard_limit: int = None,173 pool_timeout: float = None,174 ):175 self.soft_limit = soft_limit176 self.hard_limit = hard_limit177 self.pool_timeout = pool_timeout178179 def __eq__(self, other: typing.Any) -> bool:180 return (181 isinstance(other, self.__class__)182 and self.soft_limit == other.soft_limit183 and self.hard_limit == other.hard_limit184 and self.pool_timeout == other.pool_timeout185 )186187 def __repr__(self) -> str:188 class_name = self.__class__.__name__189 return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"190191192DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)193DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)194DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)195DEFAULT_CA_BUNDLE_PATH = certifi.where()196DEFAULT_MAX_REDIRECTS = 20
deleted:httpcore/decoders.py-149 removed
1"""2Handlers for Content-Encoding.34See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5"""6import typing7import zlib89import httpcore.exceptions1011try:12 import brotli13except ImportError: # pragma: nocover14 brotli = None151617class Decoder:18 def decode(self, data: bytes) -> bytes:19 raise NotImplementedError() # pragma: nocover2021 def flush(self) -> bytes:22 raise NotImplementedError() # pragma: nocover232425class IdentityDecoder(Decoder):26 """27 Handle unencoded data.28 """2930 def decode(self, data: bytes) -> bytes:31 return data3233 def flush(self) -> bytes:34 return b""353637class DeflateDecoder(Decoder):38 """39 Handle 'deflate' decoding.4041 See: https://stackoverflow.com/questions/183869942 """4344 def __init__(self) -> None:45 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)4647 def decode(self, data: bytes) -> bytes:48 try:49 return self.decompressor.decompress(data)50 except zlib.error as exc:51 raise httpcore.exceptions.DecodingError from exc5253 def flush(self) -> bytes:54 try:55 return self.decompressor.flush()56 except zlib.error as exc: # pragma: nocover57 raise httpcore.exceptions.DecodingError from exc585960class GZipDecoder(Decoder):61 """62 Handle 'gzip' decoding.6364 See: https://stackoverflow.com/questions/183869965 """6667 def __init__(self) -> None:68 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)6970 def decode(self, data: bytes) -> bytes:71 try:72 return self.decompressor.decompress(data)73 except zlib.error as exc:74 raise httpcore.exceptions.DecodingError from exc7576 def flush(self) -> bytes:77 try:78 return self.decompressor.flush()79 except zlib.error as exc: # pragma: nocover80 raise httpcore.exceptions.DecodingError from exc818283class BrotliDecoder(Decoder):84 """85 Handle 'brotli' decoding.8687 Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/88 """8990 def __init__(self) -> None:91 assert (92 brotli is not None93 ), "The 'brotlipy' library must be installed to use 'BrotliDecoder'"94 self.decompressor = brotli.Decompressor()9596 def decode(self, data: bytes) -> bytes:97 try:98 return self.decompressor.decompress(data)99 except brotli.Error as exc:100 raise httpcore.exceptions.DecodingError from exc101102 def flush(self) -> bytes:103 try:104 self.decompressor.finish()105 return b""106 except brotli.Error as exc: # pragma: nocover107 raise httpcore.exceptions.DecodingError from exc108109110class MultiDecoder(Decoder):111 """112 Handle the case where multiple encodings have been applied.113 """114115 def __init__(self, children: typing.Sequence[Decoder]) -> None:116 """117 'children' should be a sequence of decoders in the order in which118 each was applied.119 """120 # Note that we reverse the order for decoding.121 self.children = list(reversed(children))122123 def decode(self, data: bytes) -> bytes:124 for child in self.children:125 data = child.decode(data)126 return data127128 def flush(self) -> bytes:129 data = b""130 for child in self.children:131 data = child.decode(data) + child.flush()132 return data133134135SUPPORTED_DECODERS = {136 "identity": IdentityDecoder,137 "deflate": DeflateDecoder,138 "gzip": GZipDecoder,139 "br": BrotliDecoder,140}141142143if brotli is None:144 SUPPORTED_DECODERS.pop("br") # pragma: nocover145146147ACCEPT_ENCODING = ", ".join(148 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]149)
deleted:httpcore/exceptions.py-128 removed
1# Timeout exceptions...234class Timeout(Exception):5 """6 A base class for all timeouts.7 """8910class ConnectTimeout(Timeout):11 """12 Timeout while establishing a connection.13 """141516class ReadTimeout(Timeout):17 """18 Timeout while reading response data.19 """202122class WriteTimeout(Timeout):23 """24 Timeout while writing request data.25 """262728class PoolTimeout(Timeout):29 """30 Timeout while waiting to acquire a connection from the pool.31 """323334# HTTP exceptions...353637class HttpError(Exception):38 """39 An Http error occurred.40 """414243class ProtocolError(Exception):44 """45 Malformed HTTP.46 """474849class DecodingError(Exception):50 """51 Decoding of the response failed.52 """535455# Redirect exceptions...565758class RedirectError(Exception):59 """60 Base class for HTTP redirect errors.61 """626364class TooManyRedirects(RedirectError):65 """66 Too many redirects.67 """686970class RedirectBodyUnavailable(RedirectError):71 """72 Got a redirect response, but the request body was streaming, and is73 no longer available.74 """757677class RedirectLoop(RedirectError):78 """79 Infinite redirect loop.80 """818283# Stream exceptions...848586class StreamException(Exception):87 """88 The base class for stream exceptions.8990 The developer made an error in accessing the request stream in91 an invalid way.92 """939495class StreamConsumed(StreamException):96 """97 Attempted to read or stream response content, but the content has already98 been streamed.99 """100101102class ResponseNotRead(StreamException):103 """104 Attempted to access response content, without having called `read()`105 after a streaming response.106 """107108109class ResponseClosed(StreamException):110 """111 Attempted to read or stream response content, but the request has been112 closed.113 """114115116# Other cases...117118119class InvalidURL(Exception):120 """121 URL was missing a hostname, or was not one of HTTP/HTTPS.122 """123124125class CookieConflict(Exception):126 """127 Attempted to lookup a cookie by name, but multiple cookies existed.128 """
deleted:httpcore/interfaces.py-209 removed
1import enum2import ssl3import typing4from types import TracebackType56from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7from .models import (8 URL,9 AsyncRequest,10 AsyncRequestData,11 AsyncResponse,12 Headers,13 HeaderTypes,14 QueryParamTypes,15 Request,16 RequestData,17 Response,18 URLTypes,19)202122class Protocol(str, enum.Enum):23 HTTP_11 = "HTTP/1.1"24 HTTP_2 = "HTTP/2"252627class AsyncDispatcher:28 """29 Base class for async dispatcher classes, that handle sending the request.3031 Stubs out the interface, as well as providing a `.request()` convienence32 implementation, to make it easy to use or test stand-alone dispatchers,33 without requiring a complete `Client` instance.34 """3536 async def request(37 self,38 method: str,39 url: URLTypes,40 *,41 data: AsyncRequestData = b"",42 params: QueryParamTypes = None,43 headers: HeaderTypes = None,44 verify: VerifyTypes = None,45 cert: CertTypes = None,46 timeout: TimeoutTypes = None47 ) -> AsyncResponse:48 request = AsyncRequest(method, url, data=data, params=params, headers=headers)49 return await self.send(request, verify=verify, cert=cert, timeout=timeout)5051 async def send(52 self,53 request: AsyncRequest,54 verify: VerifyTypes = None,55 cert: CertTypes = None,56 timeout: TimeoutTypes = None,57 ) -> AsyncResponse:58 raise NotImplementedError() # pragma: nocover5960 async def close(self) -> None:61 pass # pragma: nocover6263 async def __aenter__(self) -> "AsyncDispatcher":64 return self6566 async def __aexit__(67 self,68 exc_type: typing.Type[BaseException] = None,69 exc_value: BaseException = None,70 traceback: TracebackType = None,71 ) -> None:72 await self.close()737475class Dispatcher:76 """77 Base class for syncronous dispatcher classes, that handle sending the request.7879 Stubs out the interface, as well as providing a `.request()` convienence80 implementation, to make it easy to use or test stand-alone dispatchers,81 without requiring a complete `Client` instance.82 """8384 def request(85 self,86 method: str,87 url: URLTypes,88 *,89 data: RequestData = b"",90 params: QueryParamTypes = None,91 headers: HeaderTypes = None,92 verify: VerifyTypes = None,93 cert: CertTypes = None,94 timeout: TimeoutTypes = None95 ) -> Response:96 request = Request(method, url, data=data, params=params, headers=headers)97 return self.send(request, verify=verify, cert=cert, timeout=timeout)9899 def send(100 self,101 request: Request,102 verify: VerifyTypes = None,103 cert: CertTypes = None,104 timeout: TimeoutTypes = None,105 ) -> Response:106 raise NotImplementedError() # pragma: nocover107108 def close(self) -> None:109 pass # pragma: nocover110111 def __enter__(self) -> "Dispatcher":112 return self113114 def __exit__(115 self,116 exc_type: typing.Type[BaseException] = None,117 exc_value: BaseException = None,118 traceback: TracebackType = None,119 ) -> None:120 self.close()121122123class BaseReader:124 """125 A stream reader. Abstracts away any asyncio-specfic interfaces126 into a more generic base class, that we can use with alternate127 backend, or for stand-alone test cases.128 """129130 async def read(self, n: int, timeout: TimeoutConfig = None) -> bytes:131 raise NotImplementedError() # pragma: no cover132133134class BaseWriter:135 """136 A stream writer. Abstracts away any asyncio-specfic interfaces137 into a more generic base class, that we can use with alternate138 backend, or for stand-alone test cases.139 """140141 def write_no_block(self, data: bytes) -> None:142 raise NotImplementedError() # pragma: no cover143144 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:145 raise NotImplementedError() # pragma: no cover146147 async def close(self) -> None:148 raise NotImplementedError() # pragma: no cover149150151class BasePoolSemaphore:152 """153 A semaphore for use with connection pooling.154155 Abstracts away any asyncio-specfic interfaces.156 """157158 async def acquire(self) -> None:159 raise NotImplementedError() # pragma: no cover160161 def release(self) -> None:162 raise NotImplementedError() # pragma: no cover163164165class ConcurrencyBackend:166 async def connect(167 self,168 hostname: str,169 port: int,170 ssl_context: typing.Optional[ssl.SSLContext],171 timeout: TimeoutConfig,172 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:173 raise NotImplementedError() # pragma: no cover174175 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:176 raise NotImplementedError() # pragma: no cover177178 async def run_in_threadpool(179 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any180 ) -> typing.Any:181 raise NotImplementedError() # pragma: no cover182183 async def iterate_in_threadpool(self, iterator): # type: ignore184 class IterationComplete(Exception):185 pass186187 def next_wrapper(iterator): # type: ignore188 try:189 return next(iterator)190 except StopIteration:191 raise IterationComplete()192193 while True:194 try:195 yield await self.run_in_threadpool(next_wrapper, iterator)196 except IterationComplete:197 break198199 def run(200 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any201 ) -> typing.Any:202 raise NotImplementedError() # pragma: no cover203204 def iterate(self, async_iterator): # type: ignore205 while True:206 try:207 yield self.run(async_iterator.__anext__)208 except StopAsyncIteration:209 break
deleted:httpcore/models.py-1127 removed
1import cgi2import email.message3import json as jsonlib4import typing5import urllib.request6from collections.abc import MutableMapping7from http.cookiejar import Cookie, CookieJar8from urllib.parse import parse_qsl, urlencode910import chardet11import rfc39861213from .decoders import (14 ACCEPT_ENCODING,15 SUPPORTED_DECODERS,16 Decoder,17 IdentityDecoder,18 MultiDecoder,19)20from .exceptions import (21 CookieConflict,22 HttpError,23 InvalidURL,24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27)28from .status_codes import StatusCode29from .utils import is_known_encoding, normalize_header_key, normalize_header_value3031URLTypes = typing.Union["URL", str]3233QueryParamTypes = typing.Union[34 "QueryParams",35 typing.Mapping[str, str],36 typing.List[typing.Tuple[typing.Any, typing.Any]],37 str,38]3940HeaderTypes = typing.Union[41 "Headers",42 typing.Dict[typing.AnyStr, typing.AnyStr],43 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44]4546CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]4748AuthTypes = typing.Union[49 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],50 typing.Callable[["AsyncRequest"], "AsyncRequest"],51]5253AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5455RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]5657AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]5859ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]606162class URL:63 def __init__(64 self,65 url: URLTypes,66 allow_relative: bool = False,67 params: QueryParamTypes = None,68 ) -> None:69 if isinstance(url, rfc3986.uri.URIReference):70 self.components = url71 elif isinstance(url, str):72 self.components = rfc3986.api.uri_reference(url)73 else:74 self.components = url.components7576 # Handle IDNA domain names.77 if self.components.authority:78 idna_authority = self.components.authority.encode("idna").decode("ascii")79 if idna_authority != self.components.authority:80 self.components = self.components.copy_with(authority=idna_authority)8182 # Normalize scheme and domain name.83 self.components = self.components.normalize()8485 # Add any query parameters.86 if params:87 query_string = str(QueryParams(params))88 self.components = self.components.copy_with(query=query_string)8990 # Enforce absolute URLs by default.91 if not allow_relative:92 if not self.scheme:93 raise InvalidURL("No scheme included in URL.")94 if self.scheme not in ("http", "https"):95 raise InvalidURL('URL scheme must be "http" or "https".')96 if not self.host:97 raise InvalidURL("No host included in URL.")9899 @property100 def scheme(self) -> str:101 return self.components.scheme or ""102103 @property104 def authority(self) -> str:105 return self.components.authority or ""106107 @property108 def username(self) -> str:109 userinfo = self.components.userinfo or ""110 return userinfo.partition(":")[0]111112 @property113 def password(self) -> str:114 userinfo = self.components.userinfo or ""115 return userinfo.partition(":")[2]116117 @property118 def host(self) -> str:119 return self.components.host or ""120121 @property122 def port(self) -> int:123 port = self.components.port124 if port is None:125 return {"https": 443, "http": 80}[self.scheme]126 return int(port)127128 @property129 def path(self) -> str:130 return self.components.path or "/"131132 @property133 def query(self) -> str:134 return self.components.query or ""135136 @property137 def full_path(self) -> str:138 path = self.path139 if self.query:140 path += "?" + self.query141 return path142143 @property144 def fragment(self) -> str:145 return self.components.fragment or ""146147 @property148 def is_ssl(self) -> bool:149 return self.components.scheme == "https"150151 @property152 def is_absolute_url(self) -> bool:153 """154 Return `True` for absolute URLs such as 'http://example.com/path',155 and `False` for relative URLs such as '/path'.156 """157 # We don't use rfc3986's `is_absolute` because it treats158 # URLs with a fragment portion as not absolute.159 # What we actually care about is if the URL provides160 # a scheme and hostname to which connections should be made.161 return self.components.scheme and self.components.host162163 @property164 def is_relative_url(self) -> bool:165 return not self.is_absolute_url166167 @property168 def origin(self) -> "Origin":169 return Origin(self)170171 def copy_with(self, **kwargs: typing.Any) -> "URL":172 return URL(self.components.copy_with(**kwargs))173174 def resolve_with(self, base_url: URLTypes) -> "URL":175 """176 Return an absolute URL, using base_url as the base.177 """178 # We drop any fragment portion, because RFC 3986 strictly179 # treats URLs with a fragment portion as not being absolute URLs.180 base_url = URL(base_url).copy_with(fragment=None)181 return URL(self.components.resolve_with(base_url.components))182183 def __hash__(self) -> int:184 return hash(str(self))185186 def __eq__(self, other: typing.Any) -> bool:187 return isinstance(other, URL) and str(self) == str(other)188189 def __str__(self) -> str:190 return self.components.unsplit()191192 def __repr__(self) -> str:193 class_name = self.__class__.__name__194 url_str = str(self)195 return f"{class_name}({url_str!r})"196197198class Origin:199 """200 The URL scheme and authority information, as a comparable, hashable object.201 """202203 def __init__(self, url: URLTypes) -> None:204 if not isinstance(url, URL):205 url = URL(url)206 self.is_ssl = url.is_ssl207 self.host = url.host208 self.port = url.port209210 def __eq__(self, other: typing.Any) -> bool:211 return (212 isinstance(other, self.__class__)213 and self.is_ssl == other.is_ssl214 and self.host == other.host215 and self.port == other.port216 )217218 def __hash__(self) -> int:219 return hash((self.is_ssl, self.host, self.port))220221222class QueryParams(typing.Mapping[str, str]):223 """224 URL query parameters, as a multi-dict.225 """226227 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:228 assert len(args) < 2, "Too many arguments."229 assert not (args and kwargs), "Cannot mix named and unnamed arguments."230231 value = args[0] if args else kwargs232233 if isinstance(value, str):234 items = parse_qsl(value)235 elif isinstance(value, QueryParams):236 items = value.multi_items()237 elif isinstance(value, list):238 items = value239 else:240 items = value.items() # type: ignore241242 self._list = [(str(k), str(v)) for k, v in items]243 self._dict = {str(k): str(v) for k, v in items}244245 def getlist(self, key: typing.Any) -> typing.List[str]:246 return [item_value for item_key, item_value in self._list if item_key == key]247248 def keys(self) -> typing.KeysView:249 return self._dict.keys()250251 def values(self) -> typing.ValuesView:252 return self._dict.values()253254 def items(self) -> typing.ItemsView:255 return self._dict.items()256257 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:258 return list(self._list)259260 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:261 if key in self._dict:262 return self._dict[key]263 return default264265 def __getitem__(self, key: typing.Any) -> str:266 return self._dict[key]267268 def __contains__(self, key: typing.Any) -> bool:269 return key in self._dict270271 def __iter__(self) -> typing.Iterator[typing.Any]:272 return iter(self.keys())273274 def __len__(self) -> int:275 return len(self._dict)276277 def __eq__(self, other: typing.Any) -> bool:278 if not isinstance(other, self.__class__):279 return False280 return sorted(self._list) == sorted(other._list)281282 def __str__(self) -> str:283 return urlencode(self._list)284285 def __repr__(self) -> str:286 class_name = self.__class__.__name__287 query_string = str(self)288 return f"{class_name}({query_string!r})"289290291class Headers(typing.MutableMapping[str, str]):292 """293 HTTP headers, as a case-insensitive multi-dict.294 """295296 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:297 if headers is None:298 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]299 elif isinstance(headers, Headers):300 self._list = list(headers.raw)301 elif isinstance(headers, dict):302 self._list = [303 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))304 for k, v in headers.items()305 ]306 else:307 self._list = [308 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))309 for k, v in headers310 ]311 self._encoding = encoding312313 @property314 def encoding(self) -> str:315 """316 Header encoding is mandated as ascii, but we allow fallbacks to utf-8317 or iso-8859-1.318 """319 if self._encoding is None:320 for encoding in ["ascii", "utf-8"]:321 for key, value in self.raw:322 try:323 key.decode(encoding)324 value.decode(encoding)325 except UnicodeDecodeError:326 break327 else:328 # The else block runs if 'break' did not occur, meaning329 # all values fitted the encoding.330 self._encoding = encoding331 break332 else:333 # The ISO-8859-1 encoding covers all 256 code points in a byte,334 # so will never raise decode errors.335 self._encoding = "iso-8859-1"336 return self._encoding337338 @encoding.setter339 def encoding(self, value: str) -> None:340 self._encoding = value341342 @property343 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:344 """345 Returns a list of the raw header items, as byte pairs.346 May be mutated in-place.347 """348 return self._list349350 def keys(self) -> typing.List[str]: # type: ignore351 return [key.decode(self.encoding) for key, value in self._list]352353 def values(self) -> typing.List[str]: # type: ignore354 return [value.decode(self.encoding) for key, value in self._list]355356 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore357 return [358 (key.decode(self.encoding), value.decode(self.encoding))359 for key, value in self._list360 ]361362 def get(self, key: str, default: typing.Any = None) -> typing.Any:363 try:364 return self[key]365 except KeyError:366 return default367368 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:369 """370 Return multiple header values.371 """372 get_header_key = key.lower().encode(self.encoding)373374 values = [375 item_value.decode(self.encoding)376 for item_key, item_value in self._list377 if item_key == get_header_key378 ]379380 if not split_commas:381 return values382383 split_values = []384 for value in values:385 split_values.extend([item.strip() for item in value.split(",")])386 return split_values387388 def __getitem__(self, key: str) -> str:389 """390 Return a single header value.391392 If there are multiple headers with the same key, then we concatenate393 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2394 """395 normalized_key = key.lower().encode(self.encoding)396397 items = []398 for header_key, header_value in self._list:399 if header_key == normalized_key:400 items.append(header_value.decode(self.encoding))401402 if items:403 return ", ".join(items)404405 raise KeyError(key)406407 def __setitem__(self, key: str, value: str) -> None:408 """409 Set the header `key` to `value`, removing any duplicate entries.410 Retains insertion order.411 """412 set_key = key.lower().encode(self.encoding)413 set_value = value.encode(self.encoding)414415 found_indexes = []416 for idx, (item_key, item_value) in enumerate(self._list):417 if item_key == set_key:418 found_indexes.append(idx)419420 for idx in reversed(found_indexes[1:]):421 del self._list[idx]422423 if found_indexes:424 idx = found_indexes[0]425 self._list[idx] = (set_key, set_value)426 else:427 self._list.append((set_key, set_value))428429 def __delitem__(self, key: str) -> None:430 """431 Remove the header `key`.432 """433 del_key = key.lower().encode(self.encoding)434435 pop_indexes = []436 for idx, (item_key, item_value) in enumerate(self._list):437 if item_key == del_key:438 pop_indexes.append(idx)439440 for idx in reversed(pop_indexes):441 del self._list[idx]442443 def __contains__(self, key: typing.Any) -> bool:444 get_header_key = key.lower().encode(self.encoding)445 for header_key, header_value in self._list:446 if header_key == get_header_key:447 return True448 return False449450 def __iter__(self) -> typing.Iterator[typing.Any]:451 return iter(self.keys())452453 def __len__(self) -> int:454 return len(self._list)455456 def __eq__(self, other: typing.Any) -> bool:457 if not isinstance(other, Headers):458 return False459 return sorted(self._list) == sorted(other._list)460461 def __repr__(self) -> str:462 class_name = self.__class__.__name__463464 encoding_str = ""465 if self.encoding != "ascii":466 encoding_str = f", encoding={self.encoding!r}"467468 as_dict = dict(self.items())469 if len(as_dict) == len(self):470 return f"{class_name}({as_dict!r}{encoding_str})"471 as_list = self.items()472 return f"{class_name}({as_list!r}{encoding_str})"473474475class BaseRequest:476 def __init__(477 self,478 method: str,479 url: typing.Union[str, URL],480 *,481 params: QueryParamTypes = None,482 headers: HeaderTypes = None,483 cookies: CookieTypes = None,484 ):485 self.method = method.upper()486 self.url = URL(url, params=params)487 self.headers = Headers(headers)488 if cookies:489 self._cookies = Cookies(cookies)490 self._cookies.set_cookie_header(self)491492 def encode_json(self, json: typing.Any) -> bytes:493 return jsonlib.dumps(json).encode("utf-8")494495 def urlencode_data(self, data: dict) -> bytes:496 return urlencode(data, doseq=True).encode("utf-8")497498 def prepare(self) -> None:499 content = getattr(self, "content", None) # type: bytes500 is_streaming = getattr(self, "is_streaming", False)501502 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]503504 has_user_agent = "user-agent" in self.headers505 has_accept = "accept" in self.headers506 has_content_length = (507 "content-length" in self.headers or "transfer-encoding" in self.headers508 )509 has_accept_encoding = "accept-encoding" in self.headers510511 if not has_user_agent:512 auto_headers.append((b"user-agent", b"httpcore"))513 if not has_accept:514 auto_headers.append((b"accept", b"*/*"))515 if not has_content_length:516 if is_streaming:517 auto_headers.append((b"transfer-encoding", b"chunked"))518 elif content:519 content_length = str(len(content)).encode()520 auto_headers.append((b"content-length", content_length))521 if not has_accept_encoding:522 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))523524 for item in reversed(auto_headers):525 self.headers.raw.insert(0, item)526527 @property528 def cookies(self) -> "Cookies":529 if not hasattr(self, "_cookies"):530 self._cookies = Cookies()531 return self._cookies532533 def __repr__(self) -> str:534 class_name = self.__class__.__name__535 url = str(self.url)536 return f"<{class_name}({self.method!r}, {url!r})>"537538539class AsyncRequest(BaseRequest):540 def __init__(541 self,542 method: str,543 url: typing.Union[str, URL],544 *,545 params: QueryParamTypes = None,546 headers: HeaderTypes = None,547 cookies: CookieTypes = None,548 data: AsyncRequestData = b"",549 json: typing.Any = None,550 ):551 super().__init__(552 method=method, url=url, params=params, headers=headers, cookies=cookies553 )554555 if json is not None:556 self.is_streaming = False557 self.content = self.encode_json(json)558 self.headers["Content-Type"] = "application/json"559 elif isinstance(data, bytes):560 self.is_streaming = False561 self.content = data562 elif isinstance(data, dict):563 self.is_streaming = False564 self.content = self.urlencode_data(data)565 self.headers["Content-Type"] = "application/x-www-form-urlencoded"566 else:567 assert hasattr(data, "__aiter__")568 self.is_streaming = True569 self.content_aiter = data570571 self.prepare()572573 async def read(self) -> bytes:574 """575 Read and return the response content.576 """577 if not hasattr(self, "content"):578 self.content = b"".join([part async for part in self.stream()])579 return self.content580581 async def stream(self) -> typing.AsyncIterator[bytes]:582 if self.is_streaming:583 async for part in self.content_aiter:584 yield part585 elif self.content:586 yield self.content587588589class Request(BaseRequest):590 def __init__(591 self,592 method: str,593 url: typing.Union[str, URL],594 *,595 params: QueryParamTypes = None,596 headers: HeaderTypes = None,597 cookies: CookieTypes = None,598 data: RequestData = b"",599 json: typing.Any = None,600 ):601 super().__init__(602 method=method, url=url, params=params, headers=headers, cookies=cookies603 )604605 if json is not None:606 self.is_streaming = False607 self.content = self.encode_json(json)608 self.headers["Content-Type"] = "application/json"609 elif isinstance(data, bytes):610 self.is_streaming = False611 self.content = data612 elif isinstance(data, dict):613 self.is_streaming = False614 self.content = self.urlencode_data(data)615 self.headers["Content-Type"] = "application/x-www-form-urlencoded"616 else:617 assert hasattr(data, "__iter__")618 self.is_streaming = True619 self.content_iter = data620621 self.prepare()622623 def read(self) -> bytes:624 if not hasattr(self, "content"):625 self.content = b"".join([part for part in self.stream()])626 return self.content627628 def stream(self) -> typing.Iterator[bytes]:629 if self.is_streaming:630 for part in self.content_iter:631 yield part632 elif self.content:633 yield self.content634635636class BaseResponse:637 def __init__(638 self,639 status_code: int,640 *,641 reason_phrase: str = None,642 protocol: str = None,643 headers: HeaderTypes = None,644 request: BaseRequest = None,645 on_close: typing.Callable = None,646 ):647 self.status_code = StatusCode.enum_or_int(status_code)648 self.reason_phrase = StatusCode.get_reason_phrase(status_code)649 self.protocol = protocol650 self.headers = Headers(headers)651652 self.request = request653 self.on_close = on_close654 self.next = None # typing.Optional[typing.Callable]655656 @property657 def url(self) -> typing.Optional[URL]:658 """659 Returns the URL for which the request was made.660661 Requires that `request` was provided when instantiating the response.662 """663 return None if self.request is None else self.request.url664665 @property666 def content(self) -> bytes:667 if not hasattr(self, "_content"):668 if hasattr(self, "_raw_content"):669 raw_content = getattr(self, "_raw_content") # type: bytes670 content = self.decoder.decode(raw_content)671 content += self.decoder.flush()672 self._content = content673 else:674 raise ResponseNotRead()675 return self._content676677 @property678 def text(self) -> str:679 if not hasattr(self, "_text"):680 content = self.content681 if not content:682 self._text = ""683 else:684 encoding = self.encoding685 self._text = content.decode(encoding, errors="replace")686 return self._text687688 @property689 def encoding(self) -> str:690 if not hasattr(self, "_encoding"):691 encoding = self.charset_encoding692 if encoding is None or not is_known_encoding(encoding):693 encoding = self.apparent_encoding694 if encoding is None or not is_known_encoding(encoding):695 encoding = "utf-8"696 self._encoding = encoding697 return self._encoding698699 @encoding.setter700 def encoding(self, value: str) -> None:701 self._encoding = value702703 @property704 def charset_encoding(self) -> typing.Optional[str]:705 """706 Return the encoding, as specified by the Content-Type header.707 """708 content_type = self.headers.get("Content-Type")709 if content_type is None:710 return None711712 parsed = cgi.parse_header(content_type)713 media_type, params = parsed[0], parsed[-1]714 if "charset" in params:715 return params["charset"].strip("'\"")716717 # RFC 2616 specifies that 'iso-8859-1' should be used as the default718 # for 'text/*' media types, if no charset is provided.719 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1720 if media_type.startswith("text/"):721 return "iso-8859-1"722723 return None724725 @property726 def apparent_encoding(self) -> typing.Optional[str]:727 """728 Return the encoding, as it appears to autodetection.729 """730 return chardet.detect(self.content)["encoding"]731732 @property733 def decoder(self) -> Decoder:734 """735 Returns a decoder instance which can be used to decode the raw byte736 content, depending on the Content-Encoding used in the response.737 """738 if not hasattr(self, "_decoder"):739 decoders = [] # type: typing.List[Decoder]740 values = self.headers.getlist("content-encoding", split_commas=True)741 for value in values:742 value = value.strip().lower()743 decoder_cls = SUPPORTED_DECODERS[value]744 decoders.append(decoder_cls())745746 if len(decoders) == 1:747 self._decoder = decoders[0]748 elif len(decoders) > 1:749 self._decoder = MultiDecoder(decoders)750 else:751 self._decoder = IdentityDecoder()752753 return self._decoder754755 @property756 def is_redirect(self) -> bool:757 return StatusCode.is_redirect(self.status_code) and "location" in self.headers758759 def raise_for_status(self) -> None:760 """761 Raise the `HttpError` if one occurred.762 """763 message = (764 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"765 "For more information check: https://httpstatuses.com/{0.status_code}"766 )767768 if StatusCode.is_client_error(self.status_code):769 message = message.format(self, error_type="Client Error")770 elif StatusCode.is_server_error(self.status_code):771 message = message.format(self, error_type="Server Error")772 else:773 message = ""774775 if message:776 raise HttpError(message)777778 def json(self) -> typing.Any:779 return jsonlib.loads(self.content.decode("utf-8"))780781 @property782 def cookies(self) -> "Cookies":783 if not hasattr(self, "_cookies"):784 assert self.request is not None785 self._cookies = Cookies()786 self._cookies.extract_cookies(self)787 return self._cookies788789 def __repr__(self) -> str:790 return f"<Response({self.status_code}, {self.reason_phrase!r})>"791792793class AsyncResponse(BaseResponse):794 def __init__(795 self,796 status_code: int,797 *,798 reason_phrase: str = None,799 protocol: str = None,800 headers: HeaderTypes = None,801 content: AsyncResponseContent = b"",802 on_close: typing.Callable = None,803 request: AsyncRequest = None,804 history: typing.List["BaseResponse"] = None,805 ):806 super().__init__(807 status_code=status_code,808 reason_phrase=reason_phrase,809 protocol=protocol,810 headers=headers,811 request=request,812 on_close=on_close,813 )814815 self.history = [] if history is None else list(history)816817 if isinstance(content, bytes):818 self.is_closed = True819 self.is_stream_consumed = True820 self._raw_content = content821 else:822 self.is_closed = False823 self.is_stream_consumed = False824 self._raw_stream = content825826 async def read(self) -> bytes:827 """828 Read and return the response content.829 """830 if not hasattr(self, "_content"):831 self._content = b"".join([part async for part in self.stream()])832 return self._content833834 async def stream(self) -> typing.AsyncIterator[bytes]:835 """836 A byte-iterator over the decoded response content.837 This allows us to handle gzip, deflate, and brotli encoded responses.838 """839 if hasattr(self, "_content"):840 yield self._content841 else:842 async for chunk in self.raw():843 yield self.decoder.decode(chunk)844 yield self.decoder.flush()845846 async def raw(self) -> typing.AsyncIterator[bytes]:847 """848 A byte-iterator over the raw response content.849 """850 if hasattr(self, "_raw_content"):851 yield self._raw_content852 else:853 if self.is_stream_consumed:854 raise StreamConsumed()855 if self.is_closed:856 raise ResponseClosed()857858 self.is_stream_consumed = True859 async for part in self._raw_stream:860 yield part861 await self.close()862863 async def close(self) -> None:864 """865 Close the response and release the connection.866 Automatically called if the response body is read to completion.867 """868 if not self.is_closed:869 self.is_closed = True870 if self.on_close is not None:871 await self.on_close()872873874class Response(BaseResponse):875 def __init__(876 self,877 status_code: int,878 *,879 reason_phrase: str = None,880 protocol: str = None,881 headers: HeaderTypes = None,882 content: ResponseContent = b"",883 on_close: typing.Callable = None,884 request: Request = None,885 history: typing.List["BaseResponse"] = None,886 ):887 super().__init__(888 status_code=status_code,889 reason_phrase=reason_phrase,890 protocol=protocol,891 headers=headers,892 request=request,893 on_close=on_close,894 )895896 self.history = [] if history is None else list(history)897898 if isinstance(content, bytes):899 self.is_closed = True900 self.is_stream_consumed = True901 self._raw_content = content902 else:903 self.is_closed = False904 self.is_stream_consumed = False905 self._raw_stream = content906907 def read(self) -> bytes:908 """909 Read and return the response content.910 """911 if not hasattr(self, "_content"):912 self._content = b"".join([part for part in self.stream()])913 return self._content914915 def stream(self) -> typing.Iterator[bytes]:916 """917 A byte-iterator over the decoded response content.918 This allows us to handle gzip, deflate, and brotli encoded responses.919 """920 if hasattr(self, "_content"):921 yield self._content922 else:923 for chunk in self.raw():924 yield self.decoder.decode(chunk)925 yield self.decoder.flush()926927 def raw(self) -> typing.Iterator[bytes]:928 """929 A byte-iterator over the raw response content.930 """931 if hasattr(self, "_raw_content"):932 yield self._raw_content933 else:934 if self.is_stream_consumed:935 raise StreamConsumed()936 if self.is_closed:937 raise ResponseClosed()938939 self.is_stream_consumed = True940 for part in self._raw_stream:941 yield part942 self.close()943944 def close(self) -> None:945 """946 Close the response and release the connection.947 Automatically called if the response body is read to completion.948 """949 if not self.is_closed:950 self.is_closed = True951 if self.on_close is not None:952 self.on_close()953954955class Cookies(MutableMapping):956 """957 HTTP Cookies, as a mutable mapping.958 """959960 def __init__(self, cookies: CookieTypes = None) -> None:961 if cookies is None or isinstance(cookies, dict):962 self.jar = CookieJar()963 if isinstance(cookies, dict):964 for key, value in cookies.items():965 self.set(key, value)966 elif isinstance(cookies, Cookies):967 self.jar = CookieJar()968 for cookie in cookies.jar:969 self.jar.set_cookie(cookie)970 else:971 self.jar = cookies972973 def extract_cookies(self, response: BaseResponse) -> None:974 """975 Loads any cookies based on the response `Set-Cookie` headers.976 """977 assert response.request is not None978 urlib_response = self._CookieCompatResponse(response)979 urllib_request = self._CookieCompatRequest(response.request)980981 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore982983 def set_cookie_header(self, request: BaseRequest) -> None:984 """985 Sets an appropriate 'Cookie:' HTTP header on the `Request`.986 """987 urllib_request = self._CookieCompatRequest(request)988 self.jar.add_cookie_header(urllib_request)989990 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:991 """992 Set a cookie value by name. May optionally include domain and path.993 """994 kwargs = dict(995 version=0,996 name=name,997 value=value,998 port=None,999 port_specified=False,1000 domain=domain,1001 domain_specified=bool(domain),1002 domain_initial_dot=domain.startswith("."),1003 path=path,1004 path_specified=bool(path),1005 secure=False,1006 expires=None,1007 discard=True,1008 comment=None,1009 comment_url=None,1010 rest={"HttpOnly": None},1011 rfc2109=False,1012 )1013 cookie = Cookie(**kwargs) # type: ignore1014 self.jar.set_cookie(cookie)10151016 def get( # type: ignore1017 self, name: str, default: str = None, domain: str = None, path: str = None1018 ) -> typing.Optional[str]:1019 """1020 Get a cookie by name. May optionally include domain and path1021 in order to specify exactly which cookie to retrieve.1022 """1023 value = None1024 for cookie in self.jar:1025 if cookie.name == name:1026 if domain is None or cookie.domain == domain: # type: ignore1027 if path is None or cookie.path == path:1028 if value is not None:1029 message = f"Multiple cookies exist with name={name}"1030 raise CookieConflict(message)1031 value = cookie.value10321033 if value is None:1034 return default1035 return value10361037 def delete(self, name: str, domain: str = None, path: str = None) -> None:1038 """1039 Delete a cookie by name. May optionally include domain and path1040 in order to specify exactly which cookie to delete.1041 """1042 if domain is not None and path is not None:1043 return self.jar.clear(domain, path, name)10441045 remove = []1046 for cookie in self.jar:1047 if cookie.name == name:1048 if domain is None or cookie.domain == domain: # type: ignore1049 if path is None or cookie.path == path:1050 remove.append(cookie)10511052 for cookie in remove:1053 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10541055 def clear(self, domain: str = None, path: str = None) -> None:1056 """1057 Delete all cookies. Optionally include a domain and path in1058 order to only delete a subset of all the cookies.1059 """1060 args = []1061 if domain is not None:1062 args.append(domain)1063 if path is not None:1064 assert domain is not None1065 args.append(path)1066 self.jar.clear(*args)10671068 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1069 cookies = Cookies(cookies)1070 for cookie in cookies.jar:1071 self.jar.set_cookie(cookie)10721073 def __setitem__(self, name: str, value: str) -> None:1074 return self.set(name, value)10751076 def __getitem__(self, name: str) -> str:1077 value = self.get(name)1078 if value is None:1079 raise KeyError(name)1080 return value10811082 def __delitem__(self, name: str) -> None:1083 return self.delete(name)10841085 def __len__(self) -> int:1086 return len(self.jar)10871088 def __iter__(self) -> typing.Iterator[str]:1089 return (cookie.name for cookie in self.jar)10901091 def __bool__(self) -> bool:1092 for cookie in self.jar:1093 return True1094 return False10951096 class _CookieCompatRequest(urllib.request.Request):1097 """1098 Wraps a `Request` instance up in a compatability interface suitable1099 for use with `CookieJar` operations.1100 """11011102 def __init__(self, request: BaseRequest) -> None:1103 super().__init__(1104 url=str(request.url),1105 headers=dict(request.headers),1106 method=request.method,1107 )1108 self.request = request11091110 def add_unredirected_header(self, key: str, value: str) -> None:1111 super().add_unredirected_header(key, value)1112 self.request.headers[key] = value11131114 class _CookieCompatResponse:1115 """1116 Wraps a `Request` instance up in a compatability interface suitable1117 for use with `CookieJar` operations.1118 """11191120 def __init__(self, response: BaseResponse):1121 self.response = response11221123 def info(self) -> email.message.Message:1124 info = email.message.Message()1125 for key, value in self.response.headers.items():1126 info[key] = value1127 return info
deleted:httpcore/status_codes.py-129 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 """1718 def __new__(cls, value: int, phrase: str = "") -> "StatusCode":19 obj = int.__new__(cls, value) # type: ignore20 obj._value_ = value2122 obj.phrase = phrase23 return obj2425 def __str__(self) -> str:26 return str(self.value)2728 @classmethod29 def enum_or_int(cls, value: int) -> int:30 try:31 return StatusCode(value)32 except ValueError:33 return value3435 @classmethod36 def get_reason_phrase(cls, value: int) -> str:37 try:38 return StatusCode(value).phrase # type: ignore39 except ValueError:40 return ""4142 @classmethod43 def is_redirect(cls, value: int) -> bool:44 return value in (45 StatusCode.MOVED_PERMANENTLY, # 301 (Cacheable redirect. Method may change to GET.)46 StatusCode.FOUND, # 302 (Uncacheable redirect. Method may change to GET.)47 StatusCode.SEE_OTHER, # 303 (Client should make a GET or HEAD request.)48 StatusCode.TEMPORARY_REDIRECT, # 307 (Equiv. 302, but retain method)49 StatusCode.PERMANENT_REDIRECT, # 308 (Equiv. 301, but retain method)50 )5152 @classmethod53 def is_client_error(cls, value: int) -> bool:54 return value >= 400 and value <= 4995556 @classmethod57 def is_server_error(cls, value: int) -> bool:58 return value >= 500 and value <= 5995960 # informational61 CONTINUE = 100, "Continue"62 SWITCHING_PROTOCOLS = 101, "Switching Protocols"63 PROCESSING = 102, "Processing"6465 # success66 OK = 200, "OK"67 CREATED = 201, "Created"68 ACCEPTED = 202, "Accepted"69 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"70 NO_CONTENT = 204, "No Content"71 RESET_CONTENT = 205, "Reset Content"72 PARTIAL_CONTENT = 206, "Partial Content"73 MULTI_STATUS = 207, "Multi-Status"74 ALREADY_REPORTED = 208, "Already Reported"75 IM_USED = 226, "IM Used"7677 # redirection78 MULTIPLE_CHOICES = 300, "Multiple Choices"79 MOVED_PERMANENTLY = 301, "Moved Permanently"80 FOUND = 302, "Found"81 SEE_OTHER = 303, "See Other"82 NOT_MODIFIED = 304, "Not Modified"83 USE_PROXY = 305, "Use Proxy"84 TEMPORARY_REDIRECT = 307, "Temporary Redirect"85 PERMANENT_REDIRECT = 308, "Permanent Redirect"8687 # client error88 BAD_REQUEST = 400, "Bad Request"89 UNAUTHORIZED = 401, "Unauthorized"90 PAYMENT_REQUIRED = 402, "Payment Required"91 FORBIDDEN = 403, "Forbidden"92 NOT_FOUND = 404, "Not Found"93 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"94 NOT_ACCEPTABLE = 406, "Not Acceptable"95 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"96 REQUEST_TIMEOUT = 408, "Request Timeout"97 CONFLICT = 409, "Conflict"98 GONE = 410, "Gone"99 LENGTH_REQUIRED = 411, "Length Required"100 PRECONDITION_FAILED = 412, "Precondition Failed"101 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"102 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"103 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"104 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"105 EXPECTATION_FAILED = 417, "Expectation Failed"106 MISDIRECTED_REQUEST = 421, "Misdirected Request"107 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"108 LOCKED = 423, "Locked"109 FAILED_DEPENDENCY = 424, "Failed Dependency"110 UPGRADE_REQUIRED = 426, "Upgrade Required"111 PRECONDITION_REQUIRED = 428, "Precondition Required"112 TOO_MANY_REQUESTS = 429, "Too Many Requests"113 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"114115 # server errors116 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"117 NOT_IMPLEMENTED = 501, "Not Implemented"118 BAD_GATEWAY = 502, "Bad Gateway"119 SERVICE_UNAVAILABLE = 503, "Service Unavailable"120 GATEWAY_TIMEOUT = 504, "Gateway Timeout"121 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"122 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"123 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"124 LOOP_DETECTED = 508, "Loop Detected"125 NOT_EXTENDED = 510, "Not Extended"126 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"127128129codes = StatusCode
deleted:httpcore/utils.py-31 removed
1import codecs2import typing345def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:6 """7 Coerce str/bytes into a strictly byte-wise HTTP header key.8 """9 if isinstance(value, bytes):10 return value.lower()11 return value.encode(encoding or "ascii").lower()121314def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:15 """16 Coerce str/bytes into a strictly byte-wise HTTP header value.17 """18 if isinstance(value, bytes):19 return value20 return value.encode(encoding or "ascii")212223def is_known_encoding(encoding: str) -> bool:24 """25 Return `True` if `encoding` is a known codec.26 """27 try:28 codecs.lookup(encoding)29 except LookupError:30 return False31 return True
modified:scripts/clean+2 added-2 removed
7 unmodified lines
8fi9if [ -d 'htmlcov' ] ; then10 rm -r htmlcov11fi12if [ -d 'httpcore.egg-info' ] ; then13 rm -r httpcore.egg-info12if [ -d 'http3.egg-info' ] ; then13 rm -r http3.egg-info14fi
modified:scripts/lint+4 added-4 removed
5 unmodified lines
6fi78set -x910${PREFIX}autoflake --in-place --recursive httpcore tests11${PREFIX}black httpcore tests12${PREFIX}isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply httpcore tests13${PREFIX}mypy httpcore --ignore-missing-imports --disallow-untyped-defs10${PREFIX}autoflake --in-place --recursive http3 tests11${PREFIX}black http3 tests12${PREFIX}isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply http3 tests13${PREFIX}mypy http3 --ignore-missing-imports --disallow-untyped-defs1415scripts/clean
modified:scripts/publish+1 added-1 removed
1#!/bin/sh -e23export PACKAGE="httpcore"3export PACKAGE="http3"4export VERSION=`cat ${PACKAGE}/__init__.py | grep __version__ | sed "s/__version__ = //" | sed "s/'//g"`5export PREFIX=""6if [ -d 'venv' ] ; then7 export PREFIX="venv/bin/"
21 unmodified lines
modified:scripts/test+1 added-1 removed
1#!/bin/sh -e23export PACKAGE="httpcore"3export PACKAGE="http3"4export PREFIX=""5if [ -d 'venv' ] ; then6 export PREFIX="venv/bin/"7fi
5 unmodified lines
modified:tests/client/test_async_client.py+16 added-16 removed
1import pytest23import httpcore3import http3456@pytest.mark.asyncio7async def test_get(server):8 url = "http://127.0.0.1:8000/"9 async with httpcore.AsyncClient() as client:9 async with http3.AsyncClient() as client:10 response = await client.get(url)11 assert response.status_code == 20012 assert response.text == "Hello, world!"13 assert response.protocol == "HTTP/1.1"
3 unmodified lines
1718@pytest.mark.asyncio19async def test_post(server):20 url = "http://127.0.0.1:8000/"21 async with httpcore.AsyncClient() as client:21 async with http3.AsyncClient() as client:22 response = await client.post(url, data=b"Hello, world!")23 assert response.status_code == 200242526@pytest.mark.asyncio27async def test_post_json(server):28 url = "http://127.0.0.1:8000/"29 async with httpcore.AsyncClient() as client:29 async with http3.AsyncClient() as client:30 response = await client.post(url, json={"text": "Hello, world!"})31 assert response.status_code == 200323334@pytest.mark.asyncio35async def test_stream_response(server):36 async with httpcore.AsyncClient() as client:36 async with http3.AsyncClient() as client:37 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)38 assert response.status_code == 20039 body = await response.read()40 assert body == b"Hello, world!"
1 unmodified line
424344@pytest.mark.asyncio45async def test_access_content_stream_response(server):46 async with httpcore.AsyncClient() as client:46 async with http3.AsyncClient() as client:47 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)48 assert response.status_code == 20049 with pytest.raises(httpcore.ResponseNotRead):49 with pytest.raises(http3.ResponseNotRead):50 response.content515253@pytest.mark.asyncio
1 unmodified line
55 async def hello_world():56 yield b"Hello, "57 yield b"world!"5859 async with httpcore.AsyncClient() as client:59 async with http3.AsyncClient() as client:60 response = await client.request(61 "POST", "http://127.0.0.1:8000/", data=hello_world()62 )63 assert response.status_code == 200646566@pytest.mark.asyncio67async def test_raise_for_status(server):68 async with httpcore.AsyncClient() as client:68 async with http3.AsyncClient() as client:69 for status_code in (200, 400, 404, 500, 505):70 response = await client.request(71 "GET", f"http://127.0.0.1:8000/status/{status_code}"72 )7374 if 400 <= status_code < 600:75 with pytest.raises(httpcore.exceptions.HttpError):75 with pytest.raises(http3.exceptions.HttpError):76 response.raise_for_status()77 else:78 assert response.raise_for_status() is None798081@pytest.mark.asyncio82async def test_options(server):83 url = "http://127.0.0.1:8000/"84 async with httpcore.AsyncClient() as client:84 async with http3.AsyncClient() as client:85 response = await client.options(url)86 assert response.status_code == 20087 assert response.text == "Hello, world!"888990@pytest.mark.asyncio91async def test_head(server):92 url = "http://127.0.0.1:8000/"93 async with httpcore.AsyncClient() as client:93 async with http3.AsyncClient() as client:94 response = await client.head(url)95 assert response.status_code == 20096 assert response.text == ""979899@pytest.mark.asyncio100async def test_put(server):101 url = "http://127.0.0.1:8000/"102 async with httpcore.AsyncClient() as client:102 async with http3.AsyncClient() as client:103 response = await client.put(url, data=b"Hello, world!")104 assert response.status_code == 200105106107@pytest.mark.asyncio108async def test_patch(server):109 url = "http://127.0.0.1:8000/"110 async with httpcore.AsyncClient() as client:110 async with http3.AsyncClient() as client:111 response = await client.patch(url, data=b"Hello, world!")112 assert response.status_code == 200113114115@pytest.mark.asyncio116async def test_delete(server):117 url = "http://127.0.0.1:8000/"118 async with httpcore.AsyncClient() as client:118 async with http3.AsyncClient() as client:119 response = await client.delete(url)120 assert response.status_code == 200121 assert response.text == "Hello, world!"122
3 unmodified lines
126 url = "http://127.0.0.1:8000/echo_body"127 headers = {"Expect": "100-continue"}128 data = b"Echo request body"129130 async with httpcore.AsyncClient() as client:130 async with http3.AsyncClient() as client:131 response = await client.post(url, headers=headers, data=data)132133 assert response.status_code == 200134 assert response.content == data
modified:tests/client/test_auth.py+1 added-1 removed
1import json23import pytest45from httpcore import (5from http3 import (6 URL,7 AsyncDispatcher,8 AsyncRequest,9 AsyncResponse,
63 unmodified lines
modified:tests/client/test_client.py+16 added-16 removed
1 unmodified line
2import functools34import pytest56import httpcore6import http3789def threadpool(func):10 """
14 unmodified lines
2526@threadpool27def test_get(server):28 url = "http://127.0.0.1:8000/"29 with httpcore.Client() as http:29 with http3.Client() as http:30 response = http.get(url)31 assert response.status_code == 20032 assert response.url == httpcore.URL(url)32 assert response.url == http3.URL(url)33 assert response.content == b"Hello, world!"34 assert response.text == "Hello, world!"35 assert response.protocol == "HTTP/1.1"36 assert response.encoding == "iso-8859-1"37 assert response.request.url == httpcore.URL(url)37 assert response.request.url == http3.URL(url)38 assert response.headers39 assert response.is_redirect is False40 assert repr(response) == "<Response(200, 'OK')>"414243@threadpool44def test_post(server):45 with httpcore.Client() as http:45 with http3.Client() as http:46 response = http.post("http://127.0.0.1:8000/", data=b"Hello, world!")47 assert response.status_code == 20048 assert response.reason_phrase == "OK"495051@threadpool52def test_post_json(server):53 with httpcore.Client() as http:53 with http3.Client() as http:54 response = http.post("http://127.0.0.1:8000/", json={"text": "Hello, world!"})55 assert response.status_code == 20056 assert response.reason_phrase == "OK"575859@threadpool60def test_stream_response(server):61 with httpcore.Client() as http:61 with http3.Client() as http:62 response = http.get("http://127.0.0.1:8000/", stream=True)63 assert response.status_code == 20064 content = response.read()65 assert content == b"Hello, world!"666768@threadpool69def test_stream_iterator(server):70 with httpcore.Client() as http:70 with http3.Client() as http:71 response = http.get("http://127.0.0.1:8000/", stream=True)72 assert response.status_code == 20073 body = b""74 for chunk in response.stream():
2 unmodified lines
777879@threadpool80def test_raw_iterator(server):81 with httpcore.Client() as http:81 with http3.Client() as http:82 response = http.get("http://127.0.0.1:8000/", stream=True)83 assert response.status_code == 20084 body = b""85 for chunk in response.raw():
3 unmodified lines
899091@threadpool92def test_raise_for_status(server):93 with httpcore.Client() as client:93 with http3.Client() as client:94 for status_code in (200, 400, 404, 500, 505):95 response = client.request(96 "GET", "http://127.0.0.1:8000/status/{}".format(status_code)97 )9899 if 400 <= status_code < 600:100 with pytest.raises(httpcore.exceptions.HttpError):100 with pytest.raises(http3.exceptions.HttpError):101 response.raise_for_status()102 else:103 assert response.raise_for_status() is None104105106@threadpool107def test_options(server):108 with httpcore.Client() as http:108 with http3.Client() as http:109 response = http.options("http://127.0.0.1:8000/")110 assert response.status_code == 200111 assert response.reason_phrase == "OK"112113114@threadpool115def test_head(server):116 with httpcore.Client() as http:116 with http3.Client() as http:117 response = http.head("http://127.0.0.1:8000/")118 assert response.status_code == 200119 assert response.reason_phrase == "OK"120121122@threadpool123def test_put(server):124 with httpcore.Client() as http:124 with http3.Client() as http:125 response = http.put("http://127.0.0.1:8000/", data=b"Hello, world!")126 assert response.status_code == 200127 assert response.reason_phrase == "OK"128129130@threadpool131def test_patch(server):132 with httpcore.Client() as http:132 with http3.Client() as http:133 response = http.patch("http://127.0.0.1:8000/", data=b"Hello, world!")134 assert response.status_code == 200135 assert response.reason_phrase == "OK"136137138@threadpool139def test_delete(server):140 with httpcore.Client() as http:140 with http3.Client() as http:141 response = http.delete("http://127.0.0.1:8000/")142 assert response.status_code == 200143 assert response.reason_phrase == "OK"
modified:tests/client/test_cookies.py+1 added-1 removed
1 unmodified line
2from http.cookiejar import Cookie, CookieJar34import pytest56from httpcore import (6from http3 import (7 URL,8 AsyncDispatcher,9 AsyncRequest,10 AsyncResponse,
117 unmodified lines
modified:tests/client/test_redirects.py+1 added-1 removed
1 unmodified line
2from urllib.parse import parse_qs34import pytest56from httpcore import (6from http3 import (7 URL,8 AsyncClient,9 AsyncDispatcher,10 AsyncRequest,
236 unmodified lines
modified:tests/dispatch/test_connection_pools.py+10 added-10 removed
1import pytest23import httpcore3import http3456@pytest.mark.asyncio7async def test_keepalive_connections(server):8 """9 Connections should default to staying in a keep-alive state.10 """11 async with httpcore.ConnectionPool() as http:11 async with http3.ConnectionPool() as http:12 response = await http.request("GET", "http://127.0.0.1:8000/")13 await response.read()14 assert len(http.active_connections) == 015 assert len(http.keepalive_connections) == 1
8 unmodified lines
24async def test_differing_connection_keys(server):25 """26 Connnections to differing connection keys should result in multiple connections.27 """28 async with httpcore.ConnectionPool() as http:28 async with http3.ConnectionPool() as http:29 response = await http.request("GET", "http://127.0.0.1:8000/")30 await response.read()31 assert len(http.active_connections) == 032 assert len(http.keepalive_connections) == 1
8 unmodified lines
41async def test_soft_limit(server):42 """43 The soft_limit config should limit the maximum number of keep-alive connections.44 """45 pool_limits = httpcore.PoolLimits(soft_limit=1)45 pool_limits = http3.PoolLimits(soft_limit=1)4647 async with httpcore.ConnectionPool(pool_limits=pool_limits) as http:47 async with http3.ConnectionPool(pool_limits=pool_limits) as http:48 response = await http.request("GET", "http://127.0.0.1:8000/")49 await response.read()50 assert len(http.active_connections) == 051 assert len(http.keepalive_connections) == 1
8 unmodified lines
60async def test_streaming_response_holds_connection(server):61 """62 A streaming request should hold the connection open until the response is read.63 """64 async with httpcore.ConnectionPool() as http:64 async with http3.ConnectionPool() as http:65 response = await http.request("GET", "http://127.0.0.1:8000/")66 assert len(http.active_connections) == 167 assert len(http.keepalive_connections) == 068
7 unmodified lines
76async def test_multiple_concurrent_connections(server):77 """78 Multiple conncurrent requests should open multiple conncurrent connections.79 """80 async with httpcore.ConnectionPool() as http:80 async with http3.ConnectionPool() as http:81 response_a = await http.request("GET", "http://127.0.0.1:8000/")82 assert len(http.active_connections) == 183 assert len(http.keepalive_connections) == 084
15 unmodified lines
100 """101 Using a `Connection: close` header should close the connection.102 """103 headers = [(b"connection", b"close")]104 async with httpcore.ConnectionPool() as http:104 async with http3.ConnectionPool() as http:105 response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)106 await response.read()107 assert len(http.active_connections) == 0108 assert len(http.keepalive_connections) == 0
3 unmodified lines
112async def test_standard_response_close(server):113 """114 A standard close should keep the connection open.115 """116 async with httpcore.ConnectionPool() as http:116 async with http3.ConnectionPool() as http:117 response = await http.request("GET", "http://127.0.0.1:8000/")118 await response.read()119 await response.close()120 assert len(http.active_connections) == 0
4 unmodified lines
125async def test_premature_response_close(server):126 """127 A premature close should close the connection.128 """129 async with httpcore.ConnectionPool() as http:129 async with http3.ConnectionPool() as http:130 response = await http.request("GET", "http://127.0.0.1:8000/")131 await response.close()132 assert len(http.active_connections) == 0133 assert len(http.keepalive_connections) == 0
modified:tests/dispatch/test_connections.py+1 added-1 removed
1import pytest23from httpcore import HTTPConnection, Request, SSLConfig3from http3 import HTTPConnection, Request, SSLConfig456@pytest.mark.asyncio7async def test_get(server):
38 unmodified lines
modified:tests/dispatch/test_http2.py+1 added-1 removed
1import json23import pytest45from httpcore import Client, Response5from http3 import Client, Response67from .utils import MockHTTP2Backend89
52 unmodified lines
modified:tests/dispatch/test_threaded.py+1 added-1 removed
1import json23import pytest45from httpcore import (5from http3 import (6 CertTypes,7 Client,8 Dispatcher,9 Request,
91 unmodified lines
modified:tests/dispatch/utils.py+1 added-1 removed
3 unmodified lines
4import h2.config5import h2.connection6import h2.events78from httpcore import (8from http3 import (9 AsyncioBackend,10 BaseReader,11 BaseWriter,12 Protocol,
103 unmodified lines
modified:tests/models/test_cookies.py+1 added-1 removed
1import pytest23from httpcore import CookieConflict, Cookies3from http3 import CookieConflict, Cookies456def test_cookies():7 cookies = Cookies({"name": "value"})
43 unmodified lines
modified:tests/models/test_headers.py+20 added-20 removed
1import httpcore1import http3234def test_headers():5 h = httpcore.Headers([("a", "123"), ("a", "456"), ("b", "789")])5 h = http3.Headers([("a", "123"), ("a", "456"), ("b", "789")])6 assert "a" in h7 assert "A" in h8 assert "b" in h9 assert "B" in h
7 unmodified lines
17 assert h.items() == [("a", "123"), ("a", "456"), ("b", "789")]18 assert list(h) == ["a", "a", "b"]19 assert dict(h) == {"a": "123, 456", "b": "789"}20 assert repr(h) == "Headers([('a', '123'), ('a', '456'), ('b', '789')])"21 assert h == httpcore.Headers([("a", "123"), ("b", "789"), ("a", "456")])21 assert h == http3.Headers([("a", "123"), ("b", "789"), ("a", "456")])22 assert h != [("a", "123"), ("A", "456"), ("b", "789")]2324 h = httpcore.Headers({"a": "123", "b": "789"})24 h = http3.Headers({"a": "123", "b": "789"})25 assert h["A"] == "123"26 assert h["B"] == "789"27 assert h.raw == [(b"a", b"123"), (b"b", b"789")]28 assert repr(h) == "Headers({'a': '123', 'b': '789'})"293031def test_header_mutations():32 h = httpcore.Headers()32 h = http3.Headers()33 assert dict(h) == {}34 h["a"] = "1"35 assert dict(h) == {"a": "1"}36 h["a"] = "2"
7 unmodified lines
44 assert h.raw == [(b"b", b"4")]454647def test_copy_headers():48 headers = httpcore.Headers({"custom": "example"})49 headers_copy = httpcore.Headers(headers)48 headers = http3.Headers({"custom": "example"})49 headers_copy = http3.Headers(headers)50 assert headers == headers_copy515253def test_headers_insert_retains_ordering():54 headers = httpcore.Headers({"a": "a", "b": "b", "c": "c"})54 headers = http3.Headers({"a": "a", "b": "b", "c": "c"})55 headers["b"] = "123"56 assert list(headers.values()) == ["a", "123", "c"]575859def test_headers_insert_appends_if_new():60 headers = httpcore.Headers({"a": "a", "b": "b", "c": "c"})60 headers = http3.Headers({"a": "a", "b": "b", "c": "c"})61 headers["d"] = "123"62 assert list(headers.values()) == ["a", "b", "c", "123"]636465def test_headers_insert_removes_all_existing():66 headers = httpcore.Headers([("a", "123"), ("a", "456")])66 headers = http3.Headers([("a", "123"), ("a", "456")])67 headers["a"] = "789"68 assert dict(headers) == {"a": "789"}697071def test_headers_delete_removes_all_existing():72 headers = httpcore.Headers([("a", "123"), ("a", "456")])72 headers = http3.Headers([("a", "123"), ("a", "456")])73 del headers["a"]74 assert dict(headers) == {}757677def test_headers_dict_repr():78 """79 Headers should display with a dict repr by default.80 """81 headers = httpcore.Headers({"custom": "example"})81 headers = http3.Headers({"custom": "example"})82 assert repr(headers) == "Headers({'custom': 'example'})"838485def test_headers_encoding_in_repr():86 """87 Headers should display an encoding in the repr if required.88 """89 headers = httpcore.Headers({b"custom": "example ☃".encode("utf-8")})89 headers = http3.Headers({b"custom": "example ☃".encode("utf-8")})90 assert repr(headers) == "Headers({'custom': 'example ☃'}, encoding='utf-8')"919293def test_headers_list_repr():94 """95 Headers should display with a list repr if they include multiple identical keys.96 """97 headers = httpcore.Headers([("custom", "example 1"), ("custom", "example 2")])97 headers = http3.Headers([("custom", "example 1"), ("custom", "example 2")])98 assert (99 repr(headers) == "Headers([('custom', 'example 1'), ('custom', 'example 2')])"100 )101
2 unmodified lines
104 """105 Headers should decode as ascii by default.106 """107 raw_headers = [(b"Custom", b"Example")]108 headers = httpcore.Headers(raw_headers)108 headers = http3.Headers(raw_headers)109 assert dict(headers) == {"custom": "Example"}110 assert headers.encoding == "ascii"111112
1 unmodified line
114 """115 Headers containing non-ascii codepoints should default to decoding as utf-8.116 """117 raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]118 headers = httpcore.Headers(raw_headers)118 headers = http3.Headers(raw_headers)119 assert dict(headers) == {"custom": "Code point: ☃"}120 assert headers.encoding == "utf-8"121122
1 unmodified line
124 """125 Headers containing non-UTF-8 codepoints should default to decoding as iso-8859-1.126 """127 raw_headers = [(b"Custom", "Code point: ÿ".encode("iso-8859-1"))]128 headers = httpcore.Headers(raw_headers)128 headers = http3.Headers(raw_headers)129 assert dict(headers) == {"custom": "Code point: ÿ"}130 assert headers.encoding == "iso-8859-1"131132
2 unmodified lines
135 An explicit encoding may be set on headers in order to force a136 particular decoding.137 """138 raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]139 headers = httpcore.Headers(raw_headers)139 headers = http3.Headers(raw_headers)140 headers.encoding = "iso-8859-1"141 assert dict(headers) == {"custom": "Code point: â\x98\x83"}142 assert headers.encoding == "iso-8859-1"143
1 unmodified line
145def test_multiple_headers():146 """147 Most headers should split by commas for `getlist`, except 'Set-Cookie'.148 """149 h = httpcore.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])149 h = http3.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])150 h.getlist("Set-Cookie") == ["a, b", "b"]151152 h = httpcore.Headers([("vary", "a, b"), ("vary", "c")])152 h = http3.Headers([("vary", "a, b"), ("vary", "c")])153 h.getlist("Vary") == ["a", "b", "c"]
modified:tests/models/test_queryparams.py+1 added-1 removed
1from httpcore import QueryParams1from http3 import QueryParams234def test_queryparams():5 q = QueryParams("a=123&a=456&b=789")
28 unmodified lines
modified:tests/models/test_requests.py+18 added-18 removed
1import pytest23import httpcore3import http3456def test_request_repr():7 request = httpcore.Request("GET", "http://example.org")7 request = http3.Request("GET", "http://example.org")8 assert repr(request) == "<Request('GET', 'http://example.org')>"91011def test_no_content():12 request = httpcore.Request("GET", "http://example.org")12 request = http3.Request("GET", "http://example.org")13 assert "Content-Length" not in request.headers141516def test_content_length_header():17 request = httpcore.Request("POST", "http://example.org", data=b"test 123")17 request = http3.Request("POST", "http://example.org", data=b"test 123")18 assert request.headers["Content-Length"] == "8"192021def test_url_encoded_data():22 for RequestClass in (httpcore.Request, httpcore.AsyncRequest):22 for RequestClass in (http3.Request, http3.AsyncRequest):23 request = RequestClass("POST", "http://example.org", data={"test": "123"})24 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"25 assert request.content == b"test=123"262728def test_json_encoded_data():29 for RequestClass in (httpcore.Request, httpcore.AsyncRequest):29 for RequestClass in (http3.Request, http3.AsyncRequest):30 request = RequestClass("POST", "http://example.org", json={"test": 123})31 assert request.headers["Content-Type"] == "application/json"32 assert request.content == b'{"test": 123}'33
3 unmodified lines
37 yield data # pragma: nocover3839 data = streaming_body(b"test 123")4041 request = httpcore.Request("POST", "http://example.org", data=data)41 request = http3.Request("POST", "http://example.org", data=data)42 assert "Content-Length" not in request.headers43 assert request.headers["Transfer-Encoding"] == "chunked"444546def test_override_host_header():47 headers = {"host": "1.2.3.4:80"}4849 request = httpcore.Request("GET", "http://example.org", headers=headers)49 request = http3.Request("GET", "http://example.org", headers=headers)50 assert request.headers["Host"] == "1.2.3.4:80"515253def test_override_accept_encoding_header():54 headers = {"Accept-Encoding": "identity"}5556 request = httpcore.Request("GET", "http://example.org", headers=headers)56 request = http3.Request("GET", "http://example.org", headers=headers)57 assert request.headers["Accept-Encoding"] == "identity"585960def test_override_content_length_header():
2 unmodified lines
6364 data = streaming_body(b"test 123")65 headers = {"Content-Length": "8"}6667 request = httpcore.Request("POST", "http://example.org", data=data, headers=headers)67 request = http3.Request("POST", "http://example.org", data=data, headers=headers)68 assert request.headers["Content-Length"] == "8"697071def test_url():72 url = "http://example.org"73 request = httpcore.Request("GET", url)73 request = http3.Request("GET", url)74 assert request.url.scheme == "http"75 assert request.url.port == 8076 assert request.url.full_path == "/"7778 url = "https://example.org/abc?foo=bar"79 request = httpcore.Request("GET", url)79 request = http3.Request("GET", url)80 assert request.url.scheme == "https"81 assert request.url.port == 44382 assert request.url.full_path == "/abc?foo=bar"838485def test_invalid_urls():86 with pytest.raises(httpcore.InvalidURL):87 httpcore.Request("GET", "example.org")86 with pytest.raises(http3.InvalidURL):87 http3.Request("GET", "example.org")8889 with pytest.raises(httpcore.InvalidURL):90 httpcore.Request("GET", "invalid://example.org")89 with pytest.raises(http3.InvalidURL):90 http3.Request("GET", "invalid://example.org")9192 with pytest.raises(httpcore.InvalidURL):93 httpcore.Request("GET", "http:///foo")92 with pytest.raises(http3.InvalidURL):93 http3.Request("GET", "http:///foo")
modified:tests/models/test_responses.py+28 added-28 removed
1import pytest23import httpcore3import http3456def streaming_body():7 yield b"Hello, "
5 unmodified lines
13 yield b"world!"141516def test_response():17 response = httpcore.Response(200, content=b"Hello, world!")17 response = http3.Response(200, content=b"Hello, world!")18 assert response.status_code == 20019 assert response.reason_phrase == "OK"20 assert response.text == "Hello, world!"212223def test_response_repr():24 response = httpcore.Response(200, content=b"Hello, world!")24 response = http3.Response(200, content=b"Hello, world!")25 assert repr(response) == "<Response(200, 'OK')>"262728def test_response_content_type_encoding():
1 unmodified line
30 Use the charset encoding in the Content-Type header if possible.31 """32 headers = {"Content-Type": "text-plain; charset=latin-1"}33 content = "Latin 1: ÿ".encode("latin-1")34 response = httpcore.Response(200, content=content, headers=headers)34 response = http3.Response(200, content=content, headers=headers)35 assert response.text == "Latin 1: ÿ"36 assert response.encoding == "latin-1"3738
1 unmodified line
40 """41 Autodetect encoding if there is no charset info in a Content-Type header.42 """43 content = "おはようございます。".encode("EUC-JP")44 response = httpcore.Response(200, content=content)44 response = http3.Response(200, content=content)45 assert response.text == "おはようございます。"46 assert response.encoding == "EUC-JP"4748
2 unmodified lines
51 Fallback to autodetection if we get an invalid charset in the Content-Type header.52 """53 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}54 content = "おはようございます。".encode("EUC-JP")55 response = httpcore.Response(200, content=content, headers=headers)55 response = http3.Response(200, content=content, headers=headers)56 assert response.text == "おはようございます。"57 assert response.encoding == "EUC-JP"5859
3 unmodified lines
63 See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.164 """65 content = b"Hello, world!"66 headers = {"Content-Type": "text/plain"}67 response = httpcore.Response(200, content=content, headers=headers)67 response = http3.Response(200, content=content, headers=headers)68 assert response.status_code == 20069 assert response.encoding == "iso-8859-1"70 assert response.text == "Hello, world!"71
1 unmodified line
73def test_response_default_encoding():74 """75 Default to utf-8 if all else fails.76 """77 response = httpcore.Response(200, content=b"")77 response = http3.Response(200, content=b"")78 assert response.text == ""79 assert response.encoding == "utf-8"8081
1 unmodified line
83 """84 Default to apparent encoding for non-text content-type headers.85 """86 headers = {"Content-Type": "image/png"}87 response = httpcore.Response(200, content=b"xyz", headers=headers)87 response = http3.Response(200, content=b"xyz", headers=headers)88 assert response.text == "xyz"89 assert response.encoding == "ascii"909192def test_response_set_explicit_encoding():93 headers = {94 "Content-Type": "text-plain; charset=utf-8"95 } # Deliberately incorrect charset96 response = httpcore.Response(96 response = http3.Response(97 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers98 )99 response.encoding = "latin-1"100 assert response.text == "Latin 1: ÿ"101 assert response.encoding == "latin-1"102103104def test_response_force_encoding():105 response = httpcore.Response(200, content="Snowman: ☃".encode("utf-8"))105 response = http3.Response(200, content="Snowman: ☃".encode("utf-8"))106 response.encoding = "iso-8859-1"107 assert response.status_code == 200108 assert response.reason_phrase == "OK"109 assert response.text == "Snowman: â\x98\x83"110 assert response.encoding == "iso-8859-1"111112113def test_read_response():114 response = httpcore.Response(200, content=b"Hello, world!")114 response = http3.Response(200, content=b"Hello, world!")115116 assert response.status_code == 200117 assert response.text == "Hello, world!"118 assert response.encoding == "ascii"
6 unmodified lines
125 assert response.is_closed126127128def test_raw_interface():129 response = httpcore.Response(200, content=b"Hello, world!")129 response = http3.Response(200, content=b"Hello, world!")130131 raw = b""132 for part in response.raw():133 raw += part134 assert raw == b"Hello, world!"135136137def test_stream_interface():138 response = httpcore.Response(200, content=b"Hello, world!")138 response = http3.Response(200, content=b"Hello, world!")139140 content = b""141 for part in response.stream():142 content += part
1 unmodified line
144145146@pytest.mark.asyncio147async def test_async_stream_interface():148 response = httpcore.AsyncResponse(200, content=b"Hello, world!")148 response = http3.AsyncResponse(200, content=b"Hello, world!")149150 content = b""151 async for part in response.stream():152 content += part153 assert content == b"Hello, world!"154155156def test_stream_interface_after_read():157 response = httpcore.Response(200, content=b"Hello, world!")157 response = http3.Response(200, content=b"Hello, world!")158159 response.read()160161 content = b""
3 unmodified lines
165166167@pytest.mark.asyncio168async def test_async_stream_interface_after_read():169 response = httpcore.AsyncResponse(200, content=b"Hello, world!")169 response = http3.AsyncResponse(200, content=b"Hello, world!")170171 await response.read()172173 content = b""
2 unmodified lines
176 assert content == b"Hello, world!"177178179def test_streaming_response():180 response = httpcore.Response(200, content=streaming_body())180 response = http3.Response(200, content=streaming_body())181182 assert response.status_code == 200183 assert not response.is_closed184
5 unmodified lines
190191192@pytest.mark.asyncio193async def test_async_streaming_response():194 response = httpcore.AsyncResponse(200, content=async_streaming_body())194 response = http3.AsyncResponse(200, content=async_streaming_body())195196 assert response.status_code == 200197 assert not response.is_closed198
4 unmodified lines
203 assert response.is_closed204205206def test_cannot_read_after_stream_consumed():207 response = httpcore.Response(200, content=streaming_body())207 response = http3.Response(200, content=streaming_body())208209 content = b""210 for part in response.stream():211 content += part212213 with pytest.raises(httpcore.StreamConsumed):213 with pytest.raises(http3.StreamConsumed):214 response.read()215216217@pytest.mark.asyncio218async def test_async_cannot_read_after_stream_consumed():219 response = httpcore.AsyncResponse(200, content=async_streaming_body())219 response = http3.AsyncResponse(200, content=async_streaming_body())220221 content = b""222 async for part in response.stream():223 content += part224225 with pytest.raises(httpcore.StreamConsumed):225 with pytest.raises(http3.StreamConsumed):226 await response.read()227228229def test_cannot_read_after_response_closed():230 response = httpcore.Response(200, content=streaming_body())230 response = http3.Response(200, content=streaming_body())231232 response.close()233234 with pytest.raises(httpcore.ResponseClosed):234 with pytest.raises(http3.ResponseClosed):235 response.read()236237238@pytest.mark.asyncio239async def test_async_cannot_read_after_response_closed():240 response = httpcore.AsyncResponse(200, content=async_streaming_body())240 response = http3.AsyncResponse(200, content=async_streaming_body())241242 await response.close()243244 with pytest.raises(httpcore.ResponseClosed):244 with pytest.raises(http3.ResponseClosed):245 await response.read()246247248def test_unknown_status_code():249 response = httpcore.Response(600)249 response = http3.Response(600)250 assert response.status_code == 600251 assert response.reason_phrase == ""252 assert response.text == ""
modified:tests/models/test_url.py+1 added-1 removed
1from httpcore import URL1from http3 import URL234def test_idna_url():5 url = URL("http://中国.icom.museum:80/")
39 unmodified lines
modified:tests/test_api.py+9 added-9 removed
1 unmodified line
2import functools34import pytest56import httpcore6import http3789def threadpool(func):10 """
13 unmodified lines
242526@threadpool27def test_get(server):28 response = httpcore.get("http://127.0.0.1:8000/")28 response = http3.get("http://127.0.0.1:8000/")29 assert response.status_code == 20030 assert response.reason_phrase == "OK"31 assert response.text == "Hello, world!"323334@threadpool35def test_post(server):36 response = httpcore.post("http://127.0.0.1:8000/", data=b"Hello, world!")36 response = http3.post("http://127.0.0.1:8000/", data=b"Hello, world!")37 assert response.status_code == 20038 assert response.reason_phrase == "OK"3940
3 unmodified lines
44 yield b"Hello"45 yield b", "46 yield b"world!"4748 response = httpcore.post("http://127.0.0.1:8000/", data=data())48 response = http3.post("http://127.0.0.1:8000/", data=data())49 assert response.status_code == 20050 assert response.reason_phrase == "OK"515253@threadpool54def test_options(server):55 response = httpcore.options("http://127.0.0.1:8000/")55 response = http3.options("http://127.0.0.1:8000/")56 assert response.status_code == 20057 assert response.reason_phrase == "OK"585960@threadpool61def test_head(server):62 response = httpcore.head("http://127.0.0.1:8000/")62 response = http3.head("http://127.0.0.1:8000/")63 assert response.status_code == 20064 assert response.reason_phrase == "OK"656667@threadpool68def test_put(server):69 response = httpcore.put("http://127.0.0.1:8000/", data=b"Hello, world!")69 response = http3.put("http://127.0.0.1:8000/", data=b"Hello, world!")70 assert response.status_code == 20071 assert response.reason_phrase == "OK"727374@threadpool75def test_patch(server):76 response = httpcore.patch("http://127.0.0.1:8000/", data=b"Hello, world!")76 response = http3.patch("http://127.0.0.1:8000/", data=b"Hello, world!")77 assert response.status_code == 20078 assert response.reason_phrase == "OK"798081@threadpool82def test_delete(server):83 response = httpcore.delete("http://127.0.0.1:8000/")83 response = http3.delete("http://127.0.0.1:8000/")84 assert response.status_code == 20085 assert response.reason_phrase == "OK"
modified:tests/test_config.py+23 added-23 removed
1 unmodified line
2import ssl34import pytest56import httpcore6import http3789@pytest.mark.asyncio10async def test_load_ssl_config():11 ssl_config = httpcore.SSLConfig()11 ssl_config = http3.SSLConfig()12 context = await ssl_config.load_ssl_context()13 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED141516@pytest.mark.asyncio17async def test_load_ssl_config_verify_non_existing_path():18 ssl_config = httpcore.SSLConfig(verify="/path/to/nowhere")18 ssl_config = http3.SSLConfig(verify="/path/to/nowhere")19 with pytest.raises(IOError):20 await ssl_config.load_ssl_context()212223@pytest.mark.asyncio24async def test_load_ssl_config_verify_existing_file():25 ssl_config = httpcore.SSLConfig(verify=httpcore.config.DEFAULT_CA_BUNDLE_PATH)25 ssl_config = http3.SSLConfig(verify=http3.config.DEFAULT_CA_BUNDLE_PATH)26 context = await ssl_config.load_ssl_context()27 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED282930@pytest.mark.asyncio31async def test_load_ssl_config_verify_directory():32 path = os.path.dirname(httpcore.config.DEFAULT_CA_BUNDLE_PATH)33 ssl_config = httpcore.SSLConfig(verify=path)32 path = os.path.dirname(http3.config.DEFAULT_CA_BUNDLE_PATH)33 ssl_config = http3.SSLConfig(verify=path)34 context = await ssl_config.load_ssl_context()35 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED363738@pytest.mark.asyncio39async def test_load_ssl_config_cert_and_key(cert_and_key_paths):40 cert_path, key_path = cert_and_key_paths41 ssl_config = httpcore.SSLConfig(cert=(cert_path, key_path))41 ssl_config = http3.SSLConfig(cert=(cert_path, key_path))42 context = await ssl_config.load_ssl_context()43 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED444546@pytest.mark.asyncio47async def test_load_ssl_config_cert_without_key_raises(cert_and_key_paths):48 cert_path, _ = cert_and_key_paths49 ssl_config = httpcore.SSLConfig(cert=cert_path)49 ssl_config = http3.SSLConfig(cert=cert_path)50 with pytest.raises(ssl.SSLError):51 await ssl_config.load_ssl_context()525354@pytest.mark.asyncio55async def test_load_ssl_config_no_verify(verify=False):56 ssl_config = httpcore.SSLConfig(verify=False)56 ssl_config = http3.SSLConfig(verify=False)57 context = await ssl_config.load_ssl_context()58 assert context.verify_mode == ssl.VerifyMode.CERT_NONE596061def test_ssl_repr():62 ssl = httpcore.SSLConfig(verify=False)62 ssl = http3.SSLConfig(verify=False)63 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"646566def test_timeout_repr():67 timeout = httpcore.TimeoutConfig(timeout=5.0)67 timeout = http3.TimeoutConfig(timeout=5.0)68 assert repr(timeout) == "TimeoutConfig(timeout=5.0)"6970 timeout = httpcore.TimeoutConfig(read_timeout=5.0)70 timeout = http3.TimeoutConfig(read_timeout=5.0)71 assert (72 repr(timeout)73 == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, write_timeout=None)"74 )757677def test_limits_repr():78 limits = httpcore.PoolLimits(hard_limit=100)78 limits = http3.PoolLimits(hard_limit=100)79 assert (80 repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100, pool_timeout=None)"81 )828384def test_ssl_eq():85 ssl = httpcore.SSLConfig(verify=False)86 assert ssl == httpcore.SSLConfig(verify=False)85 ssl = http3.SSLConfig(verify=False)86 assert ssl == http3.SSLConfig(verify=False)878889def test_timeout_eq():90 timeout = httpcore.TimeoutConfig(timeout=5.0)91 assert timeout == httpcore.TimeoutConfig(timeout=5.0)90 timeout = http3.TimeoutConfig(timeout=5.0)91 assert timeout == http3.TimeoutConfig(timeout=5.0)929394def test_limits_eq():95 limits = httpcore.PoolLimits(hard_limit=100)96 assert limits == httpcore.PoolLimits(hard_limit=100)95 limits = http3.PoolLimits(hard_limit=100)96 assert limits == http3.PoolLimits(hard_limit=100)979899def test_timeout_from_tuple():100 timeout = httpcore.TimeoutConfig(timeout=(5.0, 5.0, 5.0))101 assert timeout == httpcore.TimeoutConfig(timeout=5.0)100 timeout = http3.TimeoutConfig(timeout=(5.0, 5.0, 5.0))101 assert timeout == http3.TimeoutConfig(timeout=5.0)102103104def test_timeout_from_config_instance():105 timeout = httpcore.TimeoutConfig(timeout=(5.0))106 assert httpcore.TimeoutConfig(timeout) == httpcore.TimeoutConfig(timeout=5.0)105 timeout = http3.TimeoutConfig(timeout=(5.0))106 assert http3.TimeoutConfig(timeout) == http3.TimeoutConfig(timeout=5.0)
modified:tests/test_decoders.py+10 added-10 removed
1 unmodified line
23import brotli4import pytest56import httpcore6import http3789def test_deflate():10 body = b"test 123"11 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12 compressed_body = compressor.compress(body) + compressor.flush()1314 headers = [(b"Content-Encoding", b"deflate")]15 response = httpcore.Response(200, headers=headers, content=compressed_body)15 response = http3.Response(200, headers=headers, content=compressed_body)16 assert response.content == body171819def test_gzip():
1 unmodified line
21 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22 compressed_body = compressor.compress(body) + compressor.flush()2324 headers = [(b"Content-Encoding", b"gzip")]25 response = httpcore.Response(200, headers=headers, content=compressed_body)25 response = http3.Response(200, headers=headers, content=compressed_body)26 assert response.content == body272829def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)3233 headers = [(b"Content-Encoding", b"br")]34 response = httpcore.Response(200, headers=headers, content=compressed_body)34 response = http3.Response(200, headers=headers, content=compressed_body)35 assert response.content == body363738def test_multi():
7 unmodified lines
46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )4849 headers = [(b"Content-Encoding", b"deflate, gzip")]50 response = httpcore.Response(200, headers=headers, content=compressed_body)50 response = http3.Response(200, headers=headers, content=compressed_body)51 assert response.content == body525354def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)5758 headers = [(b"Content-Encoding", b"br, identity")]59 response = httpcore.Response(200, headers=headers, content=compressed_body)59 response = http3.Response(200, headers=headers, content=compressed_body)60 assert response.content == body6162 headers = [(b"Content-Encoding", b"identity, br")]63 response = httpcore.Response(200, headers=headers, content=compressed_body)63 response = http3.Response(200, headers=headers, content=compressed_body)64 assert response.content == body656667def test_streaming():
4 unmodified lines
72 yield compressor.compress(body)73 yield compressor.flush()7475 headers = [(b"Content-Encoding", b"gzip")]76 response = httpcore.Response(200, headers=headers, content=compress(body))76 response = http3.Response(200, headers=headers, content=compress(body))77 assert not hasattr(response, "body")78 assert response.read() == body7980
1 unmodified line
82def test_decoding_errors(header_value):83 headers = [(b"Content-Encoding", header_value)]84 body = b"test 123"85 compressed_body = brotli.compress(body)[3:]86 with pytest.raises(httpcore.exceptions.DecodingError):87 response = httpcore.Response(200, headers=headers, content=compressed_body)86 with pytest.raises(http3.exceptions.DecodingError):87 response = http3.Response(200, headers=headers, content=compressed_body)88 response.content
modified:tests/test_timeouts.py+1 added-1 removed
1import pytest23from httpcore import (3from http3 import (4 AsyncClient,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,
46 unmodified lines
added:mkdocs.yml+21 added
1site_name: HTTP32site_description: The next generation HTTP client.34theme:5 name: 'material'67repo_name: encode/http38repo_url: https://github.com/encode/http39edit_uri: ""1011nav:12 - Introduction: 'index.md'13 - QuickStart: 'quickstart.md'14 - Parallel Requests: 'parallel.md'15 - Async Client: 'async.md'16 - Requests Compatibility: 'compatibility.md'17 - Developer Interface: 'api.md'1819markdown_extensions:20 - admonition21 - codehilite
modified:README.md+13 added-13 removed
1# HTTPCore1# HTTP323<a href="https://travis-ci.org/encode/httpcore">4 <img src="https://travis-ci.org/encode/httpcore.svg?branch=master" alt="Build Status">3<a href="https://travis-ci.org/encode/http3">4 <img src="https://travis-ci.org/encode/http3.svg?branch=master" alt="Build Status">5</a>6<a href="https://codecov.io/gh/encode/httpcore">7 <img src="https://codecov.io/gh/encode/httpcore/branch/master/graph/badge.svg" alt="Coverage">6<a href="https://codecov.io/gh/encode/http3">7 <img src="https://codecov.io/gh/encode/http3/branch/master/graph/badge.svg" alt="Coverage">8</a>9<a href="https://pypi.org/project/httpcore/">10 <img src="https://badge.fury.io/py/httpcore.svg" alt="Package version">9<a href="https://pypi.org/project/http3/">10 <img src="https://badge.fury.io/py/http3.svg" alt="Package version">11</a>1213## Feature support14
25 unmodified lines
4041Making a request:4243```python44>>> import httpcore45>>> client = httpcore.Client()44>>> import http345>>> client = http3.Client()46>>> response = client.get('https://example.com')47>>> response.status_code48<HTTPStatus.OK: 200>49>>> response.protocol
6 unmodified lines
5657**Note**: Use `ipython` to try this from the console, since it supports `await`.5859```python60>>> import httpcore61>>> client = httpcore.AsyncClient()60>>> import http361>>> client = http3.AsyncClient()62>>> response = await client.get('https://example.com')63>>> response.status_code64<StatusCode.OK: 200>65>>> response.protocol
26 unmodified lines
9293*An HTTP client, with connection pooling, redirects, cookie persistence, etc.*9495```python96>>> client = Client()96>>> client = http3.Client()97>>> response = client.get('https://example.org')98```99100* `def __init__([auth], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [dispatch])`
38 unmodified lines
139*An HTTP request. Can be constructed explicitly for more control over exactly140what gets sent over the wire.*141142```python143>>> request = Request("GET", "https://example.org", headers={'host': 'example.org'})143>>> request = http3.Request("GET", "https://example.org", headers={'host': 'example.org'})144>>> response = client.send(request)145```146147* `def __init__(method, url, [params], [data], [json], [headers], [cookies])`
102 unmodified lines
modified:setup.py+5 added-5 removed
33 unmodified lines
34 ]353637setup(38 name="httpcore",38 name="http3",39 python_requires=">=3.6",40 version=get_version("httpcore"),41 url="https://github.com/encode/httpcore",40 version=get_version("http3"),41 url="https://github.com/encode/http3",42 license="BSD",43 description="...",43 description="The next generation HTTP client.",44 long_description=get_long_description(),45 long_description_content_type="text/markdown",46 author="Tom Christie",47 author_email="tom@tomchristie.com",48 packages=get_packages("httpcore"),48 packages=get_packages("http3"),49 data_files=[("", ["LICENSE.md"])],50 install_requires=[51 "certifi",52 "chardet==3.*",
18 unmodified lines