Skip to content
Myr

Renaming -> httpx (#129)

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

* Renaming -> httpx * Renaming to httpx

authored by Tom Christie · committed by GitHub · parent 0e8dae4 · Browse files · 83 files+5230 added−5218 removed
This commit

State

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

Diff stats

83 files+5230 added−5218 removed

  • tests:+187 added−187 removed
  • other:+5043 added−5031 removed

83 files+5230 added−5218 removed

added:docs/img/logo.jpgbinary

A binary file, added.

modified:docs/advanced.md+5 added-5 removed
modified:docs/api.md+2 added-2 removed
modified:docs/async.md+4 added-4 removed
1# Async Client23HTTP3 offers a standard synchronous API by default, but also gives you3HTTPX offers a standard synchronous API by default, but also gives you4the option of an async client if you need it.56Async is a concurrency model that is far more efficient than multi-threading,7and can provide significant performance benefits and enable the use of
6 unmodified lines
1415To make asynchronous requests, you'll need an `AsyncClient`.1617```python18>>> client = http3.AsyncClient()18>>> client = httpx.AsyncClient()19>>> r = await client.get('https://www.example.com/')20```2122## API Differences
1 unmodified line
24If you're using streaming responses then there are a few bits of API that25use async methods:2627```python28>>> client = http3.AsyncClient()28>>> client = httpx.AsyncClient()29>>> r = await client.get('https://www.example.com/', stream=True)30>>> try:31>>> async for chunk in r.stream():32>>> ...
10 unmodified lines
4344If you're making parallel requests, then you'll also need to use an async API:4546```python47>>> client = http3.AsyncClient()47>>> client = httpx.AsyncClient()48>>> async with client.parallel() as parallel:49>>> pending_one = parallel.get('https://example.com/1')50>>> pending_two = parallel.get('https://example.com/2')51>>> response_one = await pending_one.get_response()
8 unmodified lines
modified:docs/compatibility.md+2 added-2 removed
1# Requests Compatibility Guide23HTTP3 aims to be compatible with the `requests` API wherever possible.3HTTPX aims to be compatible with the `requests` API wherever possible.45This documentation outlines places where the API differs...67## QuickStart
1 unmodified line
9Pretty much all the API mentioned in the `requests` QuickStart should be identical10to the API in our own documentation. The following exceptions apply:1112* `Response.url` - Returns a `URL` instance, rather than a string. Use `str(response.url)` if you need a string instance.13* `http3.codes` - In our documentation we prefer the uppercased versions, such as `codes.NOT_FOUND`,13* `httpx.codes` - In our documentation we prefer the uppercased versions, such as `codes.NOT_FOUND`,14but also provide lower-cased versions for API compatibility with `requests`.15* `stream=True`. - Streaming responses provide the `.stream()` and `.raw()` byte iterator interfaces, rather than the `.iter_content()` method and the `.raw` socket interface.1617## Advanced Usage
3 unmodified lines
modified:docs/index.md+20 added-8 removed
1<h1 style="margin: 0">HTTP3</h1>1<p align="center" style="margin: 0 0 10px">2 <img width="350" height="208" src="http://127.0.0.1:8000/img/logo.jpg" alt='HTTPX'>3</p>45<h1 align="center" style="font-size: 3rem; margin: -15px 0">6HTTPX7</h1>89---1011<div align="center">12<p>13<a href="https://travis-ci.org/encode/http3">14 <img src="https://travis-ci.org/encode/http3.svg?branch=master" alt="Build Status">15</a>16<a href="https://codecov.io/gh/encode/http3">
1 unmodified line
18</a>19<a href="https://pypi.org/project/http3/">20 <img src="https://badge.fury.io/py/http3.svg" alt="Package version">21</a>22</p>2313HTTP3 is a next-generation HTTP client for Python 3.24<em>A next-generation HTTP client for Python.</em>25</div>2627!!! warning28 This project should be considered as an "alpha" release. It is substantially29 API complete, but there are still some areas that need more work.
2 unmodified lines
3233Let's get started...3435```python24>>> import http325>>> r = http3.get('https://www.example.org/')36>>> import httpx37>>> r = httpx.get('https://www.example.org/')38>>> r39<Response [200 OK]>40>>> r.status_code41200
6 unmodified lines
48```4950## Features5140HTTP3 builds on the well-established usability of `requests`, and gives you:52HTTPX builds on the well-established usability of `requests`, and gives you:5354* A requests-compatible API.55* HTTP/2 and HTTP/1.1 support.56* Support for [issuing HTTP requests in parallel](parallel.md). *(Coming soon)*
32 unmodified lines
89The [Developer Interface](api.md) provides a comprehensive API reference.9091## Dependencies9281The HTTP3 project relies on these excellent libraries:93The HTTPX project relies on these excellent libraries:9495* `h2` - HTTP/2 support.96* `h11` - HTTP/1.1 support.97* `certifi` - SSL certificates.
10 unmodified lines
108109Install with pip:110111```shell100$ pip install http3112$ pip install httpx113```114103HTTP3 requires Python 3.6+115HTTPX requires Python 3.6+
modified:docs/parallel.md+6 added-6 removed
1# Parallel Requests23!!! warning4 This page documents some proposed functionality that is not yet released.5 See [pull request #52](https://github.com/encode/http3/pull/52) for the5 See [pull request #52](https://github.com/encode/httpx/pull/52) for the6 first-pass of an implementation.78HTTP3 allows you to make HTTP requests in parallel in a highly efficient way,8HTTPX allows you to make HTTP requests in parallel in a highly efficient way,9using async under the hood, while still presenting a standard threaded interface.1011This has the huge benefit of allowing you to efficiently make parallel HTTP12requests without having to switch out to using async all the way through.
2 unmodified lines
1516Let's make two outgoing HTTP requests in parallel:1718```python19>>> with http3.parallel() as parallel:19>>> with httpx.parallel() as parallel:20>>> pending_one = parallel.get('https://example.com/1')21>>> pending_two = parallel.get('https://example.com/2')22>>> response_one = pending_one.get_response()23>>> response_two = pending_two.get_response()
3 unmodified lines
27responses sequentially, but rather deal with each response that comes back28as soon as it's available:2930```python31>>> with http3.parallel() as parallel:31>>> with httpx.parallel() as parallel:32>>> for counter in range(1, 10):33>>> parallel.get(f'https://example.com/{counter}')34>>> while parallel.has_pending_responses:35>>> r = parallel.next_response()
12 unmodified lines
48control the authentication or dispatch behaviour for all requests within the49block.5051```python52>>> client = http3.Client()52>>> client = httpx.Client()53>>> with client.parallel() as parallel:54>>> ...55```56
2 unmodified lines
59If you're working within an async framework, then you'll want to use a fully60async API for making requests.6162```python63>>> client = http3.AsyncClient()63>>> client = httpx.AsyncClient()64>>> async with client.parallel() as parallel:65>>> pending_one = await parallel.get('https://example.com/1')66>>> pending_two = await parallel.get('https://example.com/2')67>>> response_one = await pending_one.get_response()
4 unmodified lines
modified:docs/quickstart.md+36 added-36 removed
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` wherever5 The `httpx` library is designed to be API compatible with `requests` wherever6 possible.78First start by importing HTTP3:8First start by importing HTTPX:910```11>>> import http311>>> import httpx12```1314Now, let’s try to get a webpage.1516```python17>>> r = http3.get('https://httpbin.org/get')17>>> r = httpx.get('https://httpbin.org/get')18>>> r19<Response [200 OK]>20```2122Similarly, to make an HTTP POST request:2324```python25>>> r = http3.post('https://httpbin.org/post', data={'key': 'value'})25>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})26```2728The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2930```python31>>> r = http3.put('https://httpbin.org/put', data={'key': 'value'})32>>> r = http3.delete('https://httpbin.org/delete')33>>> r = http3.head('https://httpbin.org/get')34>>> r = http3.options('https://httpbin.org/get')31>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})32>>> r = httpx.delete('https://httpbin.org/delete')33>>> r = httpx.head('https://httpbin.org/get')34>>> r = httpx.options('https://httpbin.org/get')35```3637## Passing Parameters in URLs3839To include URL query parameters in the request, use the `params` keyword:4041```python42>>> params = {'key1': 'value1', 'key2': 'value2'}43>>> r = http3.get('https://httpbin.org/get', params=params)43>>> r = httpx.get('https://httpbin.org/get', params=params)44```4546To see how the values get encoding into the URL string, we can inspect the47resulting URL that was used to make the request:
6 unmodified lines
54You can also pass a list of items as a value:5556```python57>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}58>>> r = http3.get('https://httpbin.org/get', params=params)58>>> r = httpx.get('https://httpbin.org/get', params=params)59>>> r.url60URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')61```6263## Response Content6465HTTP3 will automatically handle decoding the response content into unicode text.65HTTPX will automatically handle decoding the response content into unicode text.6667```python68>>> r = http3.get('https://www.example.org/')68>>> r = httpx.get('https://www.example.org/')69>>> r.text70'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'71```72
36 unmodified lines
109110Often Web API responses will be encoded as JSON.111112```python113>>> r = http3.get('https://api.github.com/events')113>>> r = httpx.get('https://api.github.com/events')114>>> r.json()115[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]116```117
3 unmodified lines
121122```python123>>> url = 'http://httpbin.org/headers'124>>> headers = {'user-agent': 'my-app/0.0.1'}125>>> r = http3.get(url, headers=headers)125>>> r = httpx.get(url, headers=headers)126```127128## Sending Form Encoded Data129
2 unmodified lines
132which is used for HTML forms.133134```python135>>> data = {'key1': 'value1', 'key2': 'value2'}136>>> r = http3.post("https://httpbin.org/post", data=data)136>>> r = httpx.post("https://httpbin.org/post", data=data)137>>> print(r.text)138{139 ...140 "form": {
7 unmodified lines
148Form encoded data can also include multiple values form a given key.149150```python151>>> data = {'key1': ['value1', 'value2']}152>>> r = http3.post("https://httpbin.org/post", data=data)152>>> r = httpx.post("https://httpbin.org/post", data=data)153>>> print(r.text)154{155 ...156 "form": {
11 unmodified lines
168You can also upload files, using HTTP multipart encoding:169170```python171>>> files = {'upload-file': open('report.xls', 'rb')}172>>> r = http3.post("https://httpbin.org/post", files=files)172>>> r = httpx.post("https://httpbin.org/post", files=files)173>>> print(r.text)174{175 ...176 "files": {
7 unmodified lines
184of items for the file value:185186```python187>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}188>>> r = http3.post("https://httpbin.org/post", files=files)188>>> r = httpx.post("https://httpbin.org/post", files=files)189>>> print(r.text)190{191 ...192 "files": {
9 unmodified lines
202For more complicated data structures you'll often want to use JSON encoding instead.203204```python205>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}206>>> r = http3.post("https://httpbin.org/post", json=data)206>>> r = httpx.post("https://httpbin.org/post", json=data)207>>> print(r.text)208{209 ...210 "json": {
21 unmodified lines
232233We can inspect the HTTP status code of the response:234235```python236>>> r = http3.get('https://httpbin.org/get')236>>> r = httpx.get('https://httpbin.org/get')237>>> r.status_code238200239```240241HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.241HTTPX also includes an easy shortcut for accessing status codes by their text phrase.242243```python244>>> r.status_code == http3.codes.OK244>>> r.status_code == httpx.codes.OK245True246```247248We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):249250```python251>>> not_found = http3.get('https://httpbin.org/status/404')251>>> not_found = httpx.get('https://httpbin.org/status/404')252>>> not_found.status_code253404254>>> not_found.raise_for_status()255Traceback (most recent call last):256 File "/Users/tomchristie/GitHub/encode/httpcore/http3/models.py", line 776, in raise_for_status256 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status257 raise HttpError(message)258http3.exceptions.HttpError: 404 Not Found258httpx.exceptions.HttpError: 404 Not Found259```260261Any successful response codes will simply return `None` rather than raising an exception.262
37 unmodified lines
300301Any cookies that are set on the response can be easily accessed:302303```python304>>> r = http3.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)304>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)305>>> r.cookies['chocolate']306'chip'307```308309To include cookies in an outgoing request, use the `cookies` parameter:310311```python312>>> cookies = {"peanut": "butter"}313>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)313>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)314>>> r.json()315{'cookies': {'peanut': 'butter'}}316```317318Cookies are returned in a `Cookies` instance, which is a dict-like data structure319with additional API for accessing cookies by their domain or path.320321```python322>>> cookies = http3.Cookies()322>>> cookies = httpx.Cookies()323>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')324>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')325>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)325>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)326>>> r.json()327{'cookies': {'cookie_on_domain': 'hello, there!'}}328```329330## Redirection and History331332By default HTTP3 will follow redirects for anything except `HEAD` requests.332By default HTTPX will follow redirects for anything except `HEAD` requests.333334The `history` property of the response can be used to inspect any followed redirects.335It contains a list of all any redirect responses that were followed, in the order336in which they were made.337338For example, GitHub redirects all HTTP requests to HTTPS.339340```python341>>> r = http3.get('http://github.com/')341>>> r = httpx.get('http://github.com/')342>>> r.url343URL('https://github.com/')344>>> r.status_code345200
3 unmodified lines
349350You can modify the default redirection handling with the allow_redirects parameter:351352```python353>>> r = http3.get('http://github.com/', allow_redirects=False)353>>> r = httpx.get('http://github.com/', allow_redirects=False)354>>> r.status_code355301356>>> r.history357[]
1 unmodified line
359360If you’re making a `HEAD` request, you can use this to enable redirection:361362```python363>>> r = http3.head('http://github.com/', allow_redirects=True)363>>> r = httpx.head('http://github.com/', allow_redirects=True)364>>> r.url365'https://github.com/'366>>> r.history367[<Response [301 Moved Permanently]>]368```369370## Timeouts371372HTTP3 defaults to including reasonable timeouts for all network operations,372HTTPX defaults to including reasonable timeouts for all network operations,373meaning that if a connection is not properly established then it should always374raise an error rather than hanging indefinitely.375376The default timeout for network inactivity is five seconds. You can modify the377value to be more or less strict:378379```python380>>> http3.get('https://github.com/', timeout=0.001)380>>> httpx.get('https://github.com/', timeout=0.001)381```
deleted:http3/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:http3/dispatch/asgi.py-187 removed
1import asyncio2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import AsyncDispatcher6from ..models import AsyncRequest, AsyncResponse789class ASGIDispatch(AsyncDispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = http3.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the ASGIDispatch class:2425 ```26 dispatch = http3.ASGIDispatch(27 app=app,28 root_path="/submount",29 client=("1.2.3.4", 123)30 )31 client = http3.Client(dispatch=dispatch)32 ```33 """3435 def __init__(36 self,37 app: typing.Callable,38 raise_app_exceptions: bool = True,39 root_path: str = "",40 client: typing.Tuple[str, int] = ("127.0.0.1", 123),41 ) -> None:42 self.app = app43 self.raise_app_exceptions = raise_app_exceptions44 self.root_path = root_path45 self.client = client4647 async def send(48 self,49 request: AsyncRequest,50 verify: VerifyTypes = None,51 cert: CertTypes = None,52 timeout: TimeoutTypes = None,53 ) -> AsyncResponse:5455 scope = {56 "type": "http",57 "asgi": {"version": "3.0"},58 "http_version": "1.1",59 "method": request.method,60 "headers": request.headers.raw,61 "scheme": request.url.scheme,62 "path": request.url.path,63 "query_string": request.url.query.encode("ascii"),64 "server": request.url.host,65 "client": self.client,66 "root_path": self.root_path,67 }68 app = self.app69 app_exc = None70 status_code = None71 headers = None72 response_started = asyncio.Event()73 response_body = BodyIterator()74 request_stream = request.stream()7576 async def receive() -> dict:77 nonlocal request_stream7879 try:80 body = await request_stream.__anext__()81 except StopAsyncIteration:82 return {"type": "http.request", "body": b"", "more_body": False}83 return {"type": "http.request", "body": body, "more_body": True}8485 async def send(message: dict) -> None:86 nonlocal status_code, headers, response_started, response_body, request8788 if message["type"] == "http.response.start":89 status_code = message["status"]90 headers = message.get("headers", [])91 response_started.set()92 elif message["type"] == "http.response.body":93 body = message.get("body", b"")94 more_body = message.get("more_body", False)95 if body and request.method != "HEAD":96 await response_body.put(body)97 if not more_body:98 await response_body.done()99100 async def run_app() -> None:101 nonlocal app, scope, receive, send, app_exc, response_body102 try:103 await app(scope, receive, send)104 except Exception as exc:105 app_exc = exc106 finally:107 await response_body.done()108109 # Really we'd like to push all `asyncio` logic into concurrency.py,110 # with a standardized interface, so that we can support other event111 # loop implementations, such as Trio and Curio.112 # That's a bit fiddly here, so we're not yet supporting using a custom113 # `ConcurrencyBackend` with the `Client(app=asgi_app)` case.114 loop = asyncio.get_event_loop()115 app_task = loop.create_task(run_app())116 response_task = loop.create_task(response_started.wait())117118 tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]119120 await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)121122 if app_exc is not None and self.raise_app_exceptions:123 raise app_exc124125 assert response_started.is_set(), "application did not return a response."126 assert status_code is not None127 assert headers is not None128129 async def on_close() -> None:130 nonlocal app_task, response_body131 await response_body.drain()132 await app_task133 if app_exc is not None and self.raise_app_exceptions:134 raise app_exc135136 return AsyncResponse(137 status_code=status_code,138 protocol="HTTP/1.1",139 headers=headers,140 content=response_body.iterate(),141 on_close=on_close,142 request=request,143 )144145146class BodyIterator:147 """148 Provides a byte-iterator interface that the client can use to149 ingest the response content from.150 """151152 def __init__(self) -> None:153 self._queue = asyncio.Queue(154 maxsize=1155 ) # type: asyncio.Queue[typing.Union[bytes, object]]156 self._done = object()157158 async def iterate(self) -> typing.AsyncIterator[bytes]:159 """160 A byte-iterator, used by the client to consume the response body.161 """162 while True:163 data = await self._queue.get()164 if data is self._done:165 break166 assert isinstance(data, bytes)167 yield data168169 async def drain(self) -> None:170 """171 Drain any remaining body, in order to allow any blocked `put()` calls172 to complete.173 """174 async for chunk in self.iterate():175 pass # pragma: no cover176177 async def put(self, data: bytes) -> None:178 """179 Used by the server to add data to the response body.180 """181 await self._queue.put(data)182183 async def done(self) -> None:184 """185 Used by the server to signal the end of the response body.186 """187 await self._queue.put(self._done)
deleted:http3/dispatch/connection_pool.py-176 removed
1import typing23from ..concurrency import AsyncioBackend4from ..config import (5 DEFAULT_POOL_LIMITS,6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,8 PoolLimits,9 TimeoutTypes,10 VerifyTypes,11)12from ..exceptions import NotConnected13from ..interfaces import AsyncDispatcher, ConcurrencyBackend14from ..models import AsyncRequest, AsyncResponse, Origin15from .connection import HTTPConnection1617CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]181920class ConnectionStore:21 """22 We need to maintain collections of connections in a way that allows us to:2324 * Lookup connections by origin.25 * Iterate over connections by insertion time.26 * Return the total number of connections.27 """2829 def __init__(self) -> None:30 self.all = {} # type: typing.Dict[HTTPConnection, float]31 self.by_origin = (32 {}33 ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3435 def pop_by_origin(36 self, origin: Origin, http2_only: bool = False37 ) -> typing.Optional[HTTPConnection]:38 try:39 connections = self.by_origin[origin]40 except KeyError:41 return None4243 connection = next(reversed(list(connections.keys())))44 if http2_only and not connection.is_http2:45 return None4647 del connections[connection]48 if not connections:49 del self.by_origin[origin]50 del self.all[connection]5152 return connection5354 def add(self, connection: HTTPConnection) -> None:55 self.all[connection] = 0.056 try:57 self.by_origin[connection.origin][connection] = 0.058 except KeyError:59 self.by_origin[connection.origin] = {connection: 0.0}6061 def remove(self, connection: HTTPConnection) -> None:62 del self.all[connection]63 del self.by_origin[connection.origin][connection]64 if not self.by_origin[connection.origin]:65 del self.by_origin[connection.origin]6667 def clear(self) -> None:68 self.all.clear()69 self.by_origin.clear()7071 def __iter__(self) -> typing.Iterator[HTTPConnection]:72 return iter(self.all.keys())7374 def __len__(self) -> int:75 return len(self.all)767778class ConnectionPool(AsyncDispatcher):79 def __init__(80 self,81 *,82 verify: VerifyTypes = True,83 cert: CertTypes = None,84 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,85 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,86 backend: ConcurrencyBackend = None,87 ):88 self.verify = verify89 self.cert = cert90 self.timeout = timeout91 self.pool_limits = pool_limits92 self.is_closed = False9394 self.keepalive_connections = ConnectionStore()95 self.active_connections = ConnectionStore()9697 self.backend = AsyncioBackend() if backend is None else backend98 self.max_connections = self.backend.get_semaphore(pool_limits)99100 @property101 def num_connections(self) -> int:102 return len(self.keepalive_connections) + len(self.active_connections)103104 async def send(105 self,106 request: AsyncRequest,107 verify: VerifyTypes = None,108 cert: CertTypes = None,109 timeout: TimeoutTypes = None,110 ) -> AsyncResponse:111 allow_connection_reuse = True112 connection = None113 while connection is None:114 connection = await self.acquire_connection(115 origin=request.url.origin, allow_connection_reuse=allow_connection_reuse116 )117 try:118 response = await connection.send(119 request, verify=verify, cert=cert, timeout=timeout120 )121 except BaseException as exc:122 self.active_connections.remove(connection)123 self.max_connections.release()124 if isinstance(exc, NotConnected) and allow_connection_reuse:125 connection = None126 allow_connection_reuse = False127 else:128 raise exc129130 return response131132 async def acquire_connection(133 self, origin: Origin, allow_connection_reuse: bool = True134 ) -> HTTPConnection:135 connection = None136 if allow_connection_reuse:137 connection = self.active_connections.pop_by_origin(origin, http2_only=True)138 if connection is None:139 connection = self.keepalive_connections.pop_by_origin(origin)140141 if connection is None:142 await self.max_connections.acquire()143 connection = HTTPConnection(144 origin,145 verify=self.verify,146 cert=self.cert,147 timeout=self.timeout,148 backend=self.backend,149 release_func=self.release_connection,150 )151152 self.active_connections.add(connection)153154 return connection155156 async def release_connection(self, connection: HTTPConnection) -> None:157 if connection.is_closed:158 self.active_connections.remove(connection)159 self.max_connections.release()160 elif (161 self.pool_limits.soft_limit is not None162 and self.num_connections > self.pool_limits.soft_limit163 ):164 self.active_connections.remove(connection)165 self.max_connections.release()166 await connection.close()167 else:168 self.active_connections.remove(connection)169 self.keepalive_connections.add(connection)170171 async def close(self) -> None:172 self.is_closed = True173 connections = list(self.keepalive_connections)174 self.keepalive_connections.clear()175 for connection in connections:176 await connection.close()
deleted:http3/dispatch/connection.py-104 removed
1import functools2import typing34from ..concurrency import AsyncioBackend5from ..config import (6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,8 SSLConfig,9 TimeoutConfig,10 TimeoutTypes,11 VerifyTypes,12)13from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol14from ..models import AsyncRequest, AsyncResponse, Origin15from .http2 import HTTP2Connection16from .http11 import HTTP11Connection1718# Callback signature: async def callback(conn: HTTPConnection) -> None19ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]202122class HTTPConnection(AsyncDispatcher):23 def __init__(24 self,25 origin: typing.Union[str, Origin],26 verify: VerifyTypes = True,27 cert: CertTypes = None,28 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,29 backend: ConcurrencyBackend = None,30 release_func: typing.Optional[ReleaseCallback] = None,31 ):32 self.origin = Origin(origin) if isinstance(origin, str) else origin33 self.ssl = SSLConfig(cert=cert, verify=verify)34 self.timeout = TimeoutConfig(timeout)35 self.backend = AsyncioBackend() if backend is None else backend36 self.release_func = release_func37 self.h11_connection = None # type: typing.Optional[HTTP11Connection]38 self.h2_connection = None # type: typing.Optional[HTTP2Connection]3940 async def send(41 self,42 request: AsyncRequest,43 verify: VerifyTypes = None,44 cert: CertTypes = None,45 timeout: TimeoutTypes = None,46 ) -> AsyncResponse:47 if self.h11_connection is None and self.h2_connection is None:48 await self.connect(verify=verify, cert=cert, timeout=timeout)4950 if self.h2_connection is not None:51 response = await self.h2_connection.send(request, timeout=timeout)52 else:53 assert self.h11_connection is not None54 response = await self.h11_connection.send(request, timeout=timeout)5556 return response5758 async def connect(59 self,60 verify: VerifyTypes = None,61 cert: CertTypes = None,62 timeout: TimeoutTypes = None,63 ) -> None:64 ssl = self.ssl.with_overrides(verify=verify, cert=cert)65 timeout = self.timeout if timeout is None else TimeoutConfig(timeout)6667 host = self.origin.host68 port = self.origin.port69 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None7071 if self.release_func is None:72 on_release = None73 else:74 on_release = functools.partial(self.release_func, self)7576 reader, writer, protocol = await self.backend.connect(77 host, port, ssl_context, timeout78 )79 if protocol == Protocol.HTTP_2:80 self.h2_connection = HTTP2Connection(81 reader, writer, self.backend, on_release=on_release82 )83 else:84 self.h11_connection = HTTP11Connection(85 reader, writer, self.backend, on_release=on_release86 )8788 async def close(self) -> None:89 if self.h2_connection is not None:90 await self.h2_connection.close()91 elif self.h11_connection is not None:92 await self.h11_connection.close()9394 @property95 def is_http2(self) -> bool:96 return self.h2_connection is not None9798 @property99 def is_closed(self) -> bool:100 if self.h2_connection is not None:101 return self.h2_connection.is_closed102 else:103 assert self.h11_connection is not None104 return self.h11_connection.is_closed
deleted:http3/dispatch/http11.py-190 removed
1import typing23import h1145from ..concurrency import TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..exceptions import NotConnected8from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9from ..models import AsyncRequest, AsyncResponse1011H11Event = typing.Union[12 h11.Request,13 h11.Response,14 h11.InformationalResponse,15 h11.Data,16 h11.EndOfMessage,17 h11.ConnectionClosed,18]192021# Callback signature: async def callback() -> None22# In practice the callback will be a functools partial, which binds23# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.24OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]252627class HTTP11Connection:28 READ_NUM_BYTES = 40962930 def __init__(31 self,32 reader: BaseReader,33 writer: BaseWriter,34 backend: ConcurrencyBackend,35 on_release: typing.Optional[OnReleaseCallback] = None,36 ):37 self.reader = reader38 self.writer = writer39 self.backend = backend40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)42 self.timeout_flag = TimeoutFlag()4344 async def send(45 self, request: AsyncRequest, timeout: TimeoutTypes = None46 ) -> AsyncResponse:47 timeout = None if timeout is None else TimeoutConfig(timeout)4849 try:50 await self._send_request(request, timeout)51 except ConnectionResetError: # pragma: nocover52 # We're currently testing this case in HTTP/2.53 # Really we should test it here too, but this'll do in the meantime.54 raise NotConnected() from None5556 task, args = self._send_request_data, [request.stream(), timeout]57 async with self.backend.background_manager(task, args=args):58 http_version, status_code, headers = await self._receive_response(timeout)59 content = self._receive_response_data(timeout)6061 return AsyncResponse(62 status_code=status_code,63 protocol=http_version,64 headers=headers,65 content=content,66 on_close=self.response_closed,67 request=request,68 )6970 async def close(self) -> None:71 event = h11.ConnectionClosed()72 try:73 self.h11_state.send(event)74 except h11.LocalProtocolError: # pragma: no cover75 # Premature client disconnect76 pass77 await self.writer.close()7879 async def _send_request(80 self, request: AsyncRequest, timeout: TimeoutConfig = None81 ) -> None:82 """83 Send the request method, URL, and headers to the network.84 """85 method = request.method.encode("ascii")86 target = request.url.full_path.encode("ascii")87 headers = request.headers.raw88 event = h11.Request(method=method, target=target, headers=headers)89 await self._send_event(event, timeout)9091 async def _send_request_data(92 self, data: typing.AsyncIterator[bytes], timeout: TimeoutConfig = None93 ) -> None:94 """95 Send the request body to the network.96 """97 try:98 # Send the request body.99 async for chunk in data:100 event = h11.Data(data=chunk)101 await self._send_event(event, timeout)102103 # Finalize sending the request.104 event = h11.EndOfMessage()105 await self._send_event(event, timeout)106 except OSError: # pragma: nocover107 # Once we've sent the initial part of the request we don't actually108 # care about connection errors that occur when sending the body.109 # Ignore these, and defer to any exceptions on reading the response.110 self.h11_state.send_failed()111 finally:112 # Once we've sent the request, we enable read timeouts.113 self.timeout_flag.set_read_timeouts()114115 async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:116 """117 Send a single `h11` event to the network, waiting for the data to118 drain before returning.119 """120 bytes_to_send = self.h11_state.send(event)121 await self.writer.write(bytes_to_send, timeout)122123 async def _receive_response(124 self, timeout: TimeoutConfig = None125 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:126 """127 Read the response status and headers from the network.128 """129 while True:130 event = await self._receive_event(timeout)131 # As soon as we start seeing response events, we should enable132 # read timeouts, if we haven't already.133 self.timeout_flag.set_read_timeouts()134 if isinstance(event, h11.InformationalResponse):135 continue136 else:137 assert isinstance(event, h11.Response)138 break139 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")140 return (http_version, event.status_code, event.headers)141142 async def _receive_response_data(143 self, timeout: TimeoutConfig = None144 ) -> typing.AsyncIterator[bytes]:145 """146 Read the response data from the network.147 """148 while True:149 event = await self._receive_event(timeout)150 if isinstance(event, h11.Data):151 yield event.data152 else:153 assert isinstance(event, h11.EndOfMessage)154 break155156 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:157 """158 Read a single `h11` event, reading more data from the network if needed.159 """160 while True:161 event = self.h11_state.next_event()162 if event is h11.NEED_DATA:163 try:164 data = await self.reader.read(165 self.READ_NUM_BYTES, timeout, flag=self.timeout_flag166 )167 except OSError: # pragma: nocover168 data = b""169 self.h11_state.receive_data(data)170 else:171 break172 return event173174 async def response_closed(self) -> None:175 if (176 self.h11_state.our_state is h11.DONE177 and self.h11_state.their_state is h11.DONE178 ):179 # Get ready for another request/response cycle.180 self.h11_state.start_next_cycle()181 self.timeout_flag.set_write_timeouts()182 else:183 await self.close()184185 if self.on_release is not None:186 await self.on_release()187188 @property189 def is_closed(self) -> bool:190 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)
deleted:http3/dispatch/http2.py-178 removed
1import functools2import typing34import h2.connection5import h2.events67from ..concurrency import TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..exceptions import NotConnected10from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11from ..models import AsyncRequest, AsyncResponse121314class HTTP2Connection:15 READ_NUM_BYTES = 40961617 def __init__(18 self,19 reader: BaseReader,20 writer: BaseWriter,21 backend: ConcurrencyBackend,22 on_release: typing.Callable = None,23 ):24 self.reader = reader25 self.writer = writer26 self.backend = backend27 self.on_release = on_release28 self.h2_state = h2.connection.H2Connection()29 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]30 self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]31 self.initialized = False3233 async def send(34 self, request: AsyncRequest, timeout: TimeoutTypes = None35 ) -> AsyncResponse:36 timeout = None if timeout is None else TimeoutConfig(timeout)3738 #  Start sending the request.39 if not self.initialized:40 self.initiate_connection()4142 try:43 stream_id = await self.send_headers(request, timeout)44 except ConnectionResetError:45 raise NotConnected() from None4647 self.events[stream_id] = []48 self.timeout_flags[stream_id] = TimeoutFlag()4950 task, args = self.send_request_data, [stream_id, request.stream(), timeout]51 async with self.backend.background_manager(task, args=args):52 status_code, headers = await self.receive_response(stream_id, timeout)53 content = self.body_iter(stream_id, timeout)54 on_close = functools.partial(self.response_closed, stream_id=stream_id)5556 return AsyncResponse(57 status_code=status_code,58 protocol="HTTP/2",59 headers=headers,60 content=content,61 on_close=on_close,62 request=request,63 )6465 async def close(self) -> None:66 await self.writer.close()6768 def initiate_connection(self) -> None:69 self.h2_state.initiate_connection()70 data_to_send = self.h2_state.data_to_send()71 self.writer.write_no_block(data_to_send)72 self.initialized = True7374 async def send_headers(75 self, request: AsyncRequest, timeout: TimeoutConfig = None76 ) -> int:77 stream_id = self.h2_state.get_next_available_stream_id()78 headers = [79 (b":method", request.method.encode("ascii")),80 (b":authority", request.url.authority.encode("ascii")),81 (b":scheme", request.url.scheme.encode("ascii")),82 (b":path", request.url.full_path.encode("ascii")),83 ] + [(k, v) for k, v in request.headers.raw if k != b"host"]84 self.h2_state.send_headers(stream_id, headers)85 data_to_send = self.h2_state.data_to_send()86 await self.writer.write(data_to_send, timeout)87 return stream_id8889 async def send_request_data(90 self,91 stream_id: int,92 stream: typing.AsyncIterator[bytes],93 timeout: TimeoutConfig = None,94 ) -> None:95 try:96 async for data in stream:97 await self.send_data(stream_id, data, timeout)98 await self.end_stream(stream_id, timeout)99 finally:100 # Once we've sent the request we should enable read timeouts.101 self.timeout_flags[stream_id].set_read_timeouts()102103 async def send_data(104 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None105 ) -> None:106 flow_control = self.h2_state.local_flow_control_window(stream_id)107 chunk_size = min(len(data), flow_control)108 for idx in range(0, len(data), chunk_size):109 chunk = data[idx : idx + chunk_size]110 self.h2_state.send_data(stream_id, chunk)111 data_to_send = self.h2_state.data_to_send()112 await self.writer.write(data_to_send, timeout)113114 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:115 self.h2_state.end_stream(stream_id)116 data_to_send = self.h2_state.data_to_send()117 await self.writer.write(data_to_send, timeout)118119 async def receive_response(120 self, stream_id: int, timeout: TimeoutConfig = None121 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:122 """123 Read the response status and headers from the network.124 """125 while True:126 event = await self.receive_event(stream_id, timeout)127 # As soon as we start seeing response events, we should enable128 # read timeouts, if we haven't already.129 self.timeout_flags[stream_id].set_read_timeouts()130 if isinstance(event, h2.events.ResponseReceived):131 break132133 status_code = 200134 headers = []135 for k, v in event.headers:136 if k == b":status":137 status_code = int(v.decode("ascii", errors="ignore"))138 elif not k.startswith(b":"):139 headers.append((k, v))140 return (status_code, headers)141142 async def body_iter(143 self, stream_id: int, timeout: TimeoutConfig = None144 ) -> typing.AsyncIterator[bytes]:145 while True:146 event = await self.receive_event(stream_id, timeout)147 if isinstance(event, h2.events.DataReceived):148 self.h2_state.acknowledge_received_data(len(event.data), stream_id)149 yield event.data150 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):151 break152153 async def receive_event(154 self, stream_id: int, timeout: TimeoutConfig = None155 ) -> h2.events.Event:156 while not self.events[stream_id]:157 flag = self.timeout_flags[stream_id]158 data = await self.reader.read(self.READ_NUM_BYTES, timeout, flag=flag)159 events = self.h2_state.receive_data(data)160 for event in events:161 if getattr(event, "stream_id", 0):162 self.events[event.stream_id].append(event)163164 data_to_send = self.h2_state.data_to_send()165 await self.writer.write(data_to_send, timeout)166167 return self.events[stream_id].pop(0)168169 async def response_closed(self, stream_id: int) -> None:170 del self.events[stream_id]171 del self.timeout_flags[stream_id]172173 if not self.events and self.on_release is not None:174 await self.on_release()175176 @property177 def is_closed(self) -> bool:178 return False
deleted:http3/dispatch/threaded.py-96 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 protocol=sync_response.protocol,68 headers=sync_response.headers,69 content=async_content,70 on_close=async_on_close,71 request=request,72 history=sync_response.history,73 )7475 async def close(self) -> None:76 """77 The `.close()` method runs the `Dispatcher.close()` within a threadpool,78 so as not to block the async event loop.79 """80 func = self.sync_dispatcher.close81 await self.backend.run_in_threadpool(func)8283 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:84 if isinstance(content, bytes):85 return content8687 # Coerce an async iterator into an iterator, with each item in the88 # iteration run within the event loop.89 assert hasattr(content, "__iter__")90 return self.backend.iterate_in_threadpool(content)9192 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:93 if isinstance(data, bytes):94 return data9596 return self.backend.iterate(data)
deleted:http3/dispatch/wsgi.py-154 removed
1import io2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import Dispatcher6from ..models import Request, Response789class WSGIDispatch(Dispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = http3.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the WSGIDispatch class:2425 ```26 dispatch = http3.WSGIDispatch(27 app=app,28 script_name="/submount",29 remote_addr="1.2.3.4"30 )31 client = http3.Client(dispatch=dispatch)32 ```33 """3435 def __init__(36 self,37 app: typing.Callable,38 raise_app_exceptions: bool = True,39 script_name: str = "",40 remote_addr: str = "127.0.0.1",41 ) -> None:42 self.app = app43 self.raise_app_exceptions = raise_app_exceptions44 self.script_name = script_name45 self.remote_addr = remote_addr4647 def send(48 self,49 request: Request,50 verify: VerifyTypes = None,51 cert: CertTypes = None,52 timeout: TimeoutTypes = None,53 ) -> Response:54 environ = {55 "wsgi.version": (1, 0),56 "wsgi.url_scheme": request.url.scheme,57 "wsgi.input": BodyStream(request.stream()),58 "wsgi.errors": io.BytesIO(),59 "wsgi.multithread": True,60 "wsgi.multiprocess": False,61 "wsgi.run_once": False,62 "REQUEST_METHOD": request.method,63 "SCRIPT_NAME": self.script_name,64 "PATH_INFO": request.url.path,65 "QUERY_STRING": request.url.query,66 "SERVER_NAME": request.url.host,67 "SERVER_PORT": str(request.url.port),68 "REMOTE_ADDR": self.remote_addr,69 }70 for key, value in request.headers.items():71 key = key.upper().replace("-", "_")72 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):73 key = "HTTP_" + key74 environ[key] = value7576 seen_status = None77 seen_response_headers = None78 seen_exc_info = None7980 def start_response(81 status: str, response_headers: list, exc_info: typing.Any = None82 ) -> None:83 nonlocal seen_status, seen_response_headers, seen_exc_info84 seen_status = status85 seen_response_headers = response_headers86 seen_exc_info = exc_info8788 result = self.app(environ, start_response)8990 assert seen_status is not None91 assert seen_response_headers is not None92 if seen_exc_info and self.raise_app_exceptions:93 raise seen_exc_info[1]9495 return Response(96 status_code=int(seen_status.split()[0]),97 protocol="HTTP/1.1",98 headers=seen_response_headers,99 content=(chunk for chunk in result),100 on_close=getattr(result, "close", None),101 )102103104class BodyStream(io.RawIOBase):105 def __init__(self, iterator: typing.Iterator[bytes]) -> None:106 self._iterator = iterator107 self._buffer = b""108 self._closed = False109110 def read(self, size: int = -1) -> bytes:111 if self._closed:112 return b""113114 if size == -1:115 return self.readall()116117 try:118 while len(self._buffer) < size:119 self._buffer += next(self._iterator)120 except StopIteration:121 self._closed = True122 return self._buffer123124 output = self._buffer[:size]125 self._buffer = self._buffer[size:]126 return output127128 def readall(self) -> bytes:129 if self._closed:130 raise OSError("Stream closed") # pragma: nocover131132 for chunk in self._iterator:133 self._buffer += chunk134135 self._closed = True136 return self._buffer137138 def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover139 output = self.read(len(b))140 count = len(output)141 b[:count] = output142 return count143144 def write(self, b: bytes) -> int:145 raise OSError("Operation not supported") # pragma: nocover146147 def fileno(self) -> int:148 raise OSError("Operation not supported") # pragma: nocover149150 def seek(self, offset: int, whence: int = 0) -> int:151 raise OSError("Operation not supported") # pragma: nocover152153 def truncate(self, size: int = None) -> int:154 raise OSError("Operation not supported") # pragma: nocover
deleted:http3/__init__.py-131 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request3from .client import AsyncClient, Client4from .concurrency import AsyncioBackend5from .config import (6 USER_AGENT,7 CertTypes,8 PoolLimits,9 SSLConfig,10 TimeoutConfig,11 TimeoutTypes,12 VerifyTypes,13)14from .dispatch.connection import HTTPConnection15from .dispatch.connection_pool import ConnectionPool16from .exceptions import (17 ConnectTimeout,18 CookieConflict,19 DecodingError,20 InvalidURL,21 PoolTimeout,22 ProtocolError,23 ReadTimeout,24 RedirectBodyUnavailable,25 RedirectLoop,26 ResponseClosed,27 ResponseNotRead,28 StreamConsumed,29 Timeout,30 TooManyRedirects,31 WriteTimeout,32)33from .interfaces import (34 AsyncDispatcher,35 BaseReader,36 BaseWriter,37 ConcurrencyBackend,38 Dispatcher,39 Protocol,40)41from .models import (42 URL,43 AsyncRequest,44 AsyncRequestData,45 AsyncResponse,46 AsyncResponseContent,47 AuthTypes,48 Cookies,49 CookieTypes,50 Headers,51 HeaderTypes,52 Origin,53 QueryParams,54 QueryParamTypes,55 Request,56 RequestData,57 RequestFiles,58 Response,59 ResponseContent,60 URLTypes,61)62from .status_codes import StatusCode, codes6364__all__ = [65 "__description__",66 "__title__",67 "__version__",68 "delete",69 "get",70 "head",71 "options",72 "patch",73 "post",74 "patch",75 "put",76 "request",77 "AsyncClient",78 "Client",79 "AsyncioBackend",80 "USER_AGENT",81 "CertTypes",82 "PoolLimits",83 "SSLConfig",84 "TimeoutConfig",85 "VerifyTypes",86 "HTTPConnection",87 "ConnectionPool",88 "ConnectTimeout",89 "CookieConflict",90 "DecodingError",91 "InvalidURL",92 "PoolTimeout",93 "ProtocolError",94 "ReadTimeout",95 "RedirectBodyUnavailable",96 "RedirectLoop",97 "ResponseClosed",98 "ResponseNotRead",99 "StreamConsumed",100 "Timeout",101 "TooManyRedirects",102 "WriteTimeout",103 "AsyncDispatcher",104 "BaseReader",105 "BaseWriter",106 "ConcurrencyBackend",107 "Dispatcher",108 "Protocol",109 "URL",110 "URLTypes",111 "StatusCode",112 "codes",113 "TimeoutTypes",114 "AsyncRequest",115 "AsyncRequestData",116 "AsyncResponse",117 "AsyncResponseContent",118 "AuthTypes",119 "Cookies",120 "CookieTypes",121 "Headers",122 "HeaderTypes",123 "Origin",124 "QueryParams",125 "QueryParamTypes",126 "Request",127 "RequestData",128 "Response",129 "ResponseContent",130 "RequestFiles",131]
deleted:http3/__version__.py-3 removed
1__title__ = "http3"2__description__ = "A next generation HTTP client, for Python 3."3__version__ = "0.6.7"
deleted:http3/api.py-272 removed
1import typing23from .client import Client4from .config import CertTypes, TimeoutTypes, VerifyTypes5from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 RequestData,11 RequestFiles,12 Response,13 URLTypes,14)151617def request(18 method: str,19 url: URLTypes,20 *,21 params: QueryParamTypes = None,22 data: RequestData = None,23 files: RequestFiles = None,24 json: typing.Any = None,25 headers: HeaderTypes = None,26 cookies: CookieTypes = None,27 # files28 auth: AuthTypes = None,29 timeout: TimeoutTypes = None,30 allow_redirects: bool = True,31 # proxies32 cert: CertTypes = None,33 verify: VerifyTypes = True,34 stream: bool = False,35) -> Response:36 with Client() as client:37 return client.request(38 method=method,39 url=url,40 data=data,41 files=files,42 json=json,43 params=params,44 headers=headers,45 cookies=cookies,46 stream=stream,47 auth=auth,48 allow_redirects=allow_redirects,49 cert=cert,50 verify=verify,51 timeout=timeout,52 )535455def get(56 url: URLTypes,57 *,58 params: QueryParamTypes = None,59 headers: HeaderTypes = None,60 cookies: CookieTypes = None,61 stream: bool = False,62 auth: AuthTypes = None,63 allow_redirects: bool = True,64 cert: CertTypes = None,65 verify: VerifyTypes = True,66 timeout: TimeoutTypes = None,67) -> Response:68 return request(69 "GET",70 url,71 params=params,72 headers=headers,73 cookies=cookies,74 stream=stream,75 auth=auth,76 allow_redirects=allow_redirects,77 cert=cert,78 verify=verify,79 timeout=timeout,80 )818283def options(84 url: URLTypes,85 *,86 params: QueryParamTypes = None,87 headers: HeaderTypes = None,88 cookies: CookieTypes = None,89 stream: bool = False,90 auth: AuthTypes = None,91 allow_redirects: bool = True,92 cert: CertTypes = None,93 verify: VerifyTypes = True,94 timeout: TimeoutTypes = None,95) -> Response:96 return request(97 "OPTIONS",98 url,99 params=params,100 headers=headers,101 cookies=cookies,102 stream=stream,103 auth=auth,104 allow_redirects=allow_redirects,105 cert=cert,106 verify=verify,107 timeout=timeout,108 )109110111def head(112 url: URLTypes,113 *,114 params: QueryParamTypes = None,115 headers: HeaderTypes = None,116 cookies: CookieTypes = None,117 stream: bool = False,118 auth: AuthTypes = None,119 allow_redirects: bool = False, #  Note: Differs to usual default.120 cert: CertTypes = None,121 verify: VerifyTypes = True,122 timeout: TimeoutTypes = None,123) -> Response:124 return request(125 "HEAD",126 url,127 params=params,128 headers=headers,129 cookies=cookies,130 stream=stream,131 auth=auth,132 allow_redirects=allow_redirects,133 cert=cert,134 verify=verify,135 timeout=timeout,136 )137138139def post(140 url: URLTypes,141 *,142 data: RequestData = None,143 files: RequestFiles = None,144 json: typing.Any = None,145 params: QueryParamTypes = None,146 headers: HeaderTypes = None,147 cookies: CookieTypes = None,148 stream: bool = False,149 auth: AuthTypes = None,150 allow_redirects: bool = True,151 cert: CertTypes = None,152 verify: VerifyTypes = True,153 timeout: TimeoutTypes = None,154) -> Response:155 return request(156 "POST",157 url,158 data=data,159 files=files,160 json=json,161 params=params,162 headers=headers,163 cookies=cookies,164 stream=stream,165 auth=auth,166 allow_redirects=allow_redirects,167 cert=cert,168 verify=verify,169 timeout=timeout,170 )171172173def put(174 url: URLTypes,175 *,176 data: RequestData = None,177 files: RequestFiles = None,178 json: typing.Any = None,179 params: QueryParamTypes = None,180 headers: HeaderTypes = None,181 cookies: CookieTypes = None,182 stream: bool = False,183 auth: AuthTypes = None,184 allow_redirects: bool = True,185 cert: CertTypes = None,186 verify: VerifyTypes = True,187 timeout: TimeoutTypes = None,188) -> Response:189 return request(190 "PUT",191 url,192 data=data,193 files=files,194 json=json,195 params=params,196 headers=headers,197 cookies=cookies,198 stream=stream,199 auth=auth,200 allow_redirects=allow_redirects,201 cert=cert,202 verify=verify,203 timeout=timeout,204 )205206207def patch(208 url: URLTypes,209 *,210 data: RequestData = None,211 files: RequestFiles = None,212 json: typing.Any = None,213 params: QueryParamTypes = None,214 headers: HeaderTypes = None,215 cookies: CookieTypes = None,216 stream: bool = False,217 auth: AuthTypes = None,218 allow_redirects: bool = True,219 cert: CertTypes = None,220 verify: VerifyTypes = True,221 timeout: TimeoutTypes = None,222) -> Response:223 return request(224 "PATCH",225 url,226 data=data,227 files=files,228 json=json,229 params=params,230 headers=headers,231 cookies=cookies,232 stream=stream,233 auth=auth,234 allow_redirects=allow_redirects,235 cert=cert,236 verify=verify,237 timeout=timeout,238 )239240241def delete(242 url: URLTypes,243 *,244 data: RequestData = None,245 files: RequestFiles = None,246 json: typing.Any = None,247 params: QueryParamTypes = None,248 headers: HeaderTypes = None,249 cookies: CookieTypes = None,250 stream: bool = False,251 auth: AuthTypes = None,252 allow_redirects: bool = True,253 cert: CertTypes = None,254 verify: VerifyTypes = True,255 timeout: TimeoutTypes = None,256) -> Response:257 return request(258 "DELETE",259 url,260 data=data,261 files=files,262 json=json,263 params=params,264 headers=headers,265 cookies=cookies,266 stream=stream,267 auth=auth,268 allow_redirects=allow_redirects,269 cert=cert,270 verify=verify,271 timeout=timeout,272 )
deleted:http3/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:http3/client.py-895 removed
1import inspect2import typing3from types import TracebackType45from .auth import HTTPBasicAuth6from .concurrency import AsyncioBackend7from .config import (8 DEFAULT_MAX_REDIRECTS,9 DEFAULT_POOL_LIMITS,10 DEFAULT_TIMEOUT_CONFIG,11 CertTypes,12 PoolLimits,13 TimeoutTypes,14 VerifyTypes,15)16from .dispatch.asgi import ASGIDispatch17from .dispatch.connection_pool import ConnectionPool18from .dispatch.threaded import ThreadedDispatcher19from .dispatch.wsgi import WSGIDispatch20from .exceptions import (21 InvalidURL,22 RedirectBodyUnavailable,23 RedirectLoop,24 TooManyRedirects,25)26from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher27from .models import (28 URL,29 AsyncRequest,30 AsyncRequestData,31 AsyncResponse,32 AsyncResponseContent,33 AuthTypes,34 Cookies,35 CookieTypes,36 Headers,37 HeaderTypes,38 QueryParamTypes,39 RequestData,40 RequestFiles,41 Response,42 ResponseContent,43 URLTypes,44)45from .status_codes import codes464748class BaseClient:49 def __init__(50 self,51 auth: AuthTypes = None,52 cookies: CookieTypes = None,53 verify: VerifyTypes = True,54 cert: CertTypes = None,55 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,56 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,57 max_redirects: int = DEFAULT_MAX_REDIRECTS,58 base_url: URLTypes = None,59 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,60 app: typing.Callable = None,61 raise_app_exceptions: bool = True,62 backend: ConcurrencyBackend = None,63 ):64 if backend is None:65 backend = AsyncioBackend()6667 if app is not None:68 param_count = len(inspect.signature(app).parameters)69 assert param_count in (2, 3)70 if param_count == 2:71 dispatch = WSGIDispatch(72 app=app, raise_app_exceptions=raise_app_exceptions73 )74 else:75 dispatch = ASGIDispatch(76 app=app, raise_app_exceptions=raise_app_exceptions77 )7879 if dispatch is None:80 async_dispatch = ConnectionPool(81 verify=verify,82 cert=cert,83 timeout=timeout,84 pool_limits=pool_limits,85 backend=backend,86 ) # type: AsyncDispatcher87 elif isinstance(dispatch, Dispatcher):88 async_dispatch = ThreadedDispatcher(dispatch, backend)89 else:90 async_dispatch = dispatch9192 if base_url is None:93 self.base_url = URL("", allow_relative=True)94 else:95 self.base_url = URL(base_url)9697 self.auth = auth98 self.cookies = Cookies(cookies)99 self.max_redirects = max_redirects100 self.dispatch = async_dispatch101 self.concurrency_backend = backend102103 def merge_cookies(104 self, cookies: CookieTypes = None105 ) -> typing.Optional[CookieTypes]:106 if cookies or self.cookies:107 merged_cookies = Cookies(self.cookies)108 merged_cookies.update(cookies)109 return merged_cookies110 return cookies111112 async def send(113 self,114 request: AsyncRequest,115 *,116 stream: bool = False,117 auth: AuthTypes = None,118 allow_redirects: bool = True,119 verify: VerifyTypes = None,120 cert: CertTypes = None,121 timeout: TimeoutTypes = None,122 ) -> AsyncResponse:123 if auth is None:124 auth = self.auth125126 url = request.url127128 if url.scheme not in ("http", "https"):129 raise InvalidURL('URL scheme must be "http" or "https".')130131 if auth is None and (url.username or url.password):132 auth = HTTPBasicAuth(username=url.username, password=url.password)133134 if auth is not None:135 if isinstance(auth, tuple):136 auth = HTTPBasicAuth(username=auth[0], password=auth[1])137 request = auth(request)138139 response = await self.send_handling_redirects(140 request,141 verify=verify,142 cert=cert,143 timeout=timeout,144 allow_redirects=allow_redirects,145 )146147 if not stream:148 try:149 await response.read()150 finally:151 await response.close()152153 return response154155 async def send_handling_redirects(156 self,157 request: AsyncRequest,158 *,159 cert: CertTypes = None,160 verify: VerifyTypes = None,161 timeout: TimeoutTypes = None,162 allow_redirects: bool = True,163 history: typing.List[AsyncResponse] = None,164 ) -> AsyncResponse:165 if history is None:166 history = []167168 while True:169 # We perform these checks here, so that calls to `response.next()`170 # will raise redirect errors if appropriate.171 if len(history) > self.max_redirects:172 raise TooManyRedirects()173 if request.url in [response.url for response in history]:174 raise RedirectLoop()175176 response = await self.dispatch.send(177 request, verify=verify, cert=cert, timeout=timeout178 )179 should_close_response = True180 try:181 assert isinstance(response, AsyncResponse)182 response.history = list(history)183 self.cookies.extract_cookies(response)184 history = history + [response]185186 if allow_redirects and response.is_redirect:187 request = self.build_redirect_request(request, response)188 else:189 should_close_response = False190 break191 finally:192 if should_close_response:193 await response.close()194195 if response.is_redirect:196197 async def send_next() -> AsyncResponse:198 nonlocal request, response, verify, cert199 nonlocal allow_redirects, timeout, history200 request = self.build_redirect_request(request, response)201 response = await self.send_handling_redirects(202 request,203 allow_redirects=allow_redirects,204 verify=verify,205 cert=cert,206 timeout=timeout,207 history=history,208 )209 return response210211 response.next = send_next # type: ignore212213 return response214215 def build_redirect_request(216 self, request: AsyncRequest, response: AsyncResponse217 ) -> AsyncRequest:218 method = self.redirect_method(request, response)219 url = self.redirect_url(request, response)220 headers = self.redirect_headers(request, url)221 content = self.redirect_content(request, method)222 cookies = self.merge_cookies(request.cookies)223 return AsyncRequest(224 method=method, url=url, headers=headers, data=content, cookies=cookies225 )226227 def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:228 """229 When being redirected we may want to change the method of the request230 based on certain specs or browser behavior.231 """232 method = request.method233234 # https://tools.ietf.org/html/rfc7231#section-6.4.4235 if response.status_code == codes.SEE_OTHER and method != "HEAD":236 method = "GET"237238 # Do what the browsers do, despite standards...239 # Turn 302s into GETs.240 if response.status_code == codes.FOUND and method != "HEAD":241 method = "GET"242243 # If a POST is responded to with a 301, turn it into a GET.244 # This bizarre behaviour is explained in 'requests' issue 1704.245 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":246 method = "GET"247248 return method249250 def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:251 """252 Return the URL for the redirect to follow.253 """254 location = response.headers["Location"]255256 url = URL(location, allow_relative=True)257258 # Facilitate relative 'Location' headers, as allowed by RFC 7231.259 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')260 if url.is_relative_url:261 url = request.url.join(url)262263 # Attach previous fragment if needed (RFC 7231 7.1.2)264 if request.url.fragment and not url.fragment:265 url = url.copy_with(fragment=request.url.fragment)266267 return url268269 def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:270 """271 Strip Authorization headers when responses are redirected away from272 the origin.273 """274 headers = Headers(request.headers)275 if url.origin != request.url.origin:276 del headers["Authorization"]277 return headers278279 def redirect_content(self, request: AsyncRequest, method: str) -> bytes:280 """281 Return the body that should be used for the redirect request.282 """283 if method != request.method and method == "GET":284 return b""285 if request.is_streaming:286 raise RedirectBodyUnavailable()287 return request.content288289290class AsyncClient(BaseClient):291 async def get(292 self,293 url: URLTypes,294 *,295 params: QueryParamTypes = None,296 headers: HeaderTypes = None,297 cookies: CookieTypes = None,298 stream: bool = False,299 auth: AuthTypes = None,300 allow_redirects: bool = True,301 cert: CertTypes = None,302 verify: VerifyTypes = None,303 timeout: TimeoutTypes = None,304 ) -> AsyncResponse:305 return await self.request(306 "GET",307 url,308 params=params,309 headers=headers,310 cookies=cookies,311 stream=stream,312 auth=auth,313 allow_redirects=allow_redirects,314 verify=verify,315 cert=cert,316 timeout=timeout,317 )318319 async def options(320 self,321 url: URLTypes,322 *,323 params: QueryParamTypes = None,324 headers: HeaderTypes = None,325 cookies: CookieTypes = None,326 stream: bool = False,327 auth: AuthTypes = None,328 allow_redirects: bool = True,329 cert: CertTypes = None,330 verify: VerifyTypes = None,331 timeout: TimeoutTypes = None,332 ) -> AsyncResponse:333 return await self.request(334 "OPTIONS",335 url,336 params=params,337 headers=headers,338 cookies=cookies,339 stream=stream,340 auth=auth,341 allow_redirects=allow_redirects,342 verify=verify,343 cert=cert,344 timeout=timeout,345 )346347 async def head(348 self,349 url: URLTypes,350 *,351 params: QueryParamTypes = None,352 headers: HeaderTypes = None,353 cookies: CookieTypes = None,354 stream: bool = False,355 auth: AuthTypes = None,356 allow_redirects: bool = False, #  Note: Differs to usual default.357 cert: CertTypes = None,358 verify: VerifyTypes = None,359 timeout: TimeoutTypes = None,360 ) -> AsyncResponse:361 return await self.request(362 "HEAD",363 url,364 params=params,365 headers=headers,366 cookies=cookies,367 stream=stream,368 auth=auth,369 allow_redirects=allow_redirects,370 verify=verify,371 cert=cert,372 timeout=timeout,373 )374375 async def post(376 self,377 url: URLTypes,378 *,379 data: AsyncRequestData = None,380 files: RequestFiles = None,381 json: typing.Any = None,382 params: QueryParamTypes = None,383 headers: HeaderTypes = None,384 cookies: CookieTypes = None,385 stream: bool = False,386 auth: AuthTypes = None,387 allow_redirects: bool = True,388 cert: CertTypes = None,389 verify: VerifyTypes = None,390 timeout: TimeoutTypes = None,391 ) -> AsyncResponse:392 return await self.request(393 "POST",394 url,395 data=data,396 files=files,397 json=json,398 params=params,399 headers=headers,400 cookies=cookies,401 stream=stream,402 auth=auth,403 allow_redirects=allow_redirects,404 verify=verify,405 cert=cert,406 timeout=timeout,407 )408409 async def put(410 self,411 url: URLTypes,412 *,413 data: AsyncRequestData = None,414 files: RequestFiles = None,415 json: typing.Any = None,416 params: QueryParamTypes = None,417 headers: HeaderTypes = None,418 cookies: CookieTypes = None,419 stream: bool = False,420 auth: AuthTypes = None,421 allow_redirects: bool = True,422 cert: CertTypes = None,423 verify: VerifyTypes = None,424 timeout: TimeoutTypes = None,425 ) -> AsyncResponse:426 return await self.request(427 "PUT",428 url,429 data=data,430 files=files,431 json=json,432 params=params,433 headers=headers,434 cookies=cookies,435 stream=stream,436 auth=auth,437 allow_redirects=allow_redirects,438 verify=verify,439 cert=cert,440 timeout=timeout,441 )442443 async def patch(444 self,445 url: URLTypes,446 *,447 data: AsyncRequestData = None,448 files: RequestFiles = None,449 json: typing.Any = None,450 params: QueryParamTypes = None,451 headers: HeaderTypes = None,452 cookies: CookieTypes = None,453 stream: bool = False,454 auth: AuthTypes = None,455 allow_redirects: bool = True,456 cert: CertTypes = None,457 verify: VerifyTypes = None,458 timeout: TimeoutTypes = None,459 ) -> AsyncResponse:460 return await self.request(461 "PATCH",462 url,463 data=data,464 files=files,465 json=json,466 params=params,467 headers=headers,468 cookies=cookies,469 stream=stream,470 auth=auth,471 allow_redirects=allow_redirects,472 verify=verify,473 cert=cert,474 timeout=timeout,475 )476477 async def delete(478 self,479 url: URLTypes,480 *,481 data: AsyncRequestData = None,482 files: RequestFiles = None,483 json: typing.Any = None,484 params: QueryParamTypes = None,485 headers: HeaderTypes = None,486 cookies: CookieTypes = None,487 stream: bool = False,488 auth: AuthTypes = None,489 allow_redirects: bool = True,490 cert: CertTypes = None,491 verify: VerifyTypes = None,492 timeout: TimeoutTypes = None,493 ) -> AsyncResponse:494 return await self.request(495 "DELETE",496 url,497 data=data,498 files=files,499 json=json,500 params=params,501 headers=headers,502 cookies=cookies,503 stream=stream,504 auth=auth,505 allow_redirects=allow_redirects,506 verify=verify,507 cert=cert,508 timeout=timeout,509 )510511 async def request(512 self,513 method: str,514 url: URLTypes,515 *,516 data: AsyncRequestData = None,517 files: RequestFiles = None,518 json: typing.Any = None,519 params: QueryParamTypes = None,520 headers: HeaderTypes = None,521 cookies: CookieTypes = None,522 stream: bool = False,523 auth: AuthTypes = None,524 allow_redirects: bool = True,525 cert: CertTypes = None,526 verify: VerifyTypes = None,527 timeout: TimeoutTypes = None,528 ) -> AsyncResponse:529 url = self.base_url.join(url)530 cookies = self.merge_cookies(cookies)531 request = AsyncRequest(532 method,533 url,534 data=data,535 files=files,536 json=json,537 params=params,538 headers=headers,539 cookies=cookies,540 )541 response = await self.send(542 request,543 stream=stream,544 auth=auth,545 allow_redirects=allow_redirects,546 verify=verify,547 cert=cert,548 timeout=timeout,549 )550 return response551552 async def close(self) -> None:553 await self.dispatch.close()554555 async def __aenter__(self) -> "AsyncClient":556 return self557558 async def __aexit__(559 self,560 exc_type: typing.Type[BaseException] = None,561 exc_value: BaseException = None,562 traceback: TracebackType = None,563 ) -> None:564 await self.close()565566567class Client(BaseClient):568 def _async_request_data(569 self, data: RequestData = None570 ) -> typing.Optional[AsyncRequestData]:571 """572 If the request data is an bytes iterator then return an async bytes573 iterator onto the request data.574 """575 if data is None or isinstance(data, (str, bytes, dict)):576 return data577578 # Coerce an iterator into an async iterator, with each item in the579 # iteration running as a thread-pooled operation.580 assert hasattr(data, "__iter__")581 return self.concurrency_backend.iterate_in_threadpool(data)582583 def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:584 if isinstance(data, bytes):585 return data586587 # Coerce an async iterator into an iterator, with each item in the588 # iteration run within the event loop.589 assert hasattr(data, "__aiter__")590 return self.concurrency_backend.iterate(data)591592 def request(593 self,594 method: str,595 url: URLTypes,596 *,597 data: RequestData = None,598 files: RequestFiles = None,599 json: typing.Any = None,600 params: QueryParamTypes = None,601 headers: HeaderTypes = None,602 cookies: CookieTypes = None,603 stream: bool = False,604 auth: AuthTypes = None,605 allow_redirects: bool = True,606 cert: CertTypes = None,607 verify: VerifyTypes = None,608 timeout: TimeoutTypes = None,609 ) -> Response:610 url = self.base_url.join(url)611 cookies = self.merge_cookies(cookies)612 request = AsyncRequest(613 method,614 url,615 data=self._async_request_data(data),616 files=files,617 json=json,618 params=params,619 headers=headers,620 cookies=cookies,621 )622 concurrency_backend = self.concurrency_backend623624 coroutine = self.send625 args = [request]626 kwargs = dict(627 stream=True,628 auth=auth,629 allow_redirects=allow_redirects,630 verify=verify,631 cert=cert,632 timeout=timeout,633 )634 async_response = concurrency_backend.run(coroutine, *args, **kwargs)635636 content = getattr(637 async_response, "_raw_content", getattr(async_response, "_raw_stream", None)638 )639640 sync_content = self._sync_data(content)641642 def sync_on_close() -> None:643 nonlocal concurrency_backend, async_response644 concurrency_backend.run(async_response.on_close)645646 response = Response(647 status_code=async_response.status_code,648 protocol=async_response.protocol,649 headers=async_response.headers,650 content=sync_content,651 on_close=sync_on_close,652 request=async_response.request,653 history=async_response.history,654 )655 if not stream:656 try:657 response.read()658 finally:659 response.close()660 return response661662 def get(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 = True,672 cert: CertTypes = None,673 verify: VerifyTypes = None,674 timeout: TimeoutTypes = None,675 ) -> Response:676 return self.request(677 "GET",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 options(691 self,692 url: URLTypes,693 *,694 params: QueryParamTypes = None,695 headers: HeaderTypes = None,696 cookies: CookieTypes = None,697 stream: bool = False,698 auth: AuthTypes = None,699 allow_redirects: bool = True,700 cert: CertTypes = None,701 verify: VerifyTypes = None,702 timeout: TimeoutTypes = None,703 ) -> Response:704 return self.request(705 "OPTIONS",706 url,707 params=params,708 headers=headers,709 cookies=cookies,710 stream=stream,711 auth=auth,712 allow_redirects=allow_redirects,713 verify=verify,714 cert=cert,715 timeout=timeout,716 )717718 def head(719 self,720 url: URLTypes,721 *,722 params: QueryParamTypes = None,723 headers: HeaderTypes = None,724 cookies: CookieTypes = None,725 stream: bool = False,726 auth: AuthTypes = None,727 allow_redirects: bool = False, #  Note: Differs to usual default.728 cert: CertTypes = None,729 verify: VerifyTypes = None,730 timeout: TimeoutTypes = None,731 ) -> Response:732 return self.request(733 "HEAD",734 url,735 params=params,736 headers=headers,737 cookies=cookies,738 stream=stream,739 auth=auth,740 allow_redirects=allow_redirects,741 verify=verify,742 cert=cert,743 timeout=timeout,744 )745746 def post(747 self,748 url: URLTypes,749 *,750 data: RequestData = None,751 files: RequestFiles = None,752 json: typing.Any = None,753 params: QueryParamTypes = None,754 headers: HeaderTypes = None,755 cookies: CookieTypes = None,756 stream: bool = False,757 auth: AuthTypes = None,758 allow_redirects: bool = True,759 cert: CertTypes = None,760 verify: VerifyTypes = None,761 timeout: TimeoutTypes = None,762 ) -> Response:763 return self.request(764 "POST",765 url,766 data=data,767 files=files,768 json=json,769 params=params,770 headers=headers,771 cookies=cookies,772 stream=stream,773 auth=auth,774 allow_redirects=allow_redirects,775 verify=verify,776 cert=cert,777 timeout=timeout,778 )779780 def put(781 self,782 url: URLTypes,783 *,784 data: RequestData = None,785 files: RequestFiles = None,786 json: typing.Any = None,787 params: QueryParamTypes = None,788 headers: HeaderTypes = None,789 cookies: CookieTypes = None,790 stream: bool = False,791 auth: AuthTypes = None,792 allow_redirects: bool = True,793 cert: CertTypes = None,794 verify: VerifyTypes = None,795 timeout: TimeoutTypes = None,796 ) -> Response:797 return self.request(798 "PUT",799 url,800 data=data,801 files=files,802 json=json,803 params=params,804 headers=headers,805 cookies=cookies,806 stream=stream,807 auth=auth,808 allow_redirects=allow_redirects,809 verify=verify,810 cert=cert,811 timeout=timeout,812 )813814 def patch(815 self,816 url: URLTypes,817 *,818 data: RequestData = None,819 files: RequestFiles = None,820 json: typing.Any = None,821 params: QueryParamTypes = None,822 headers: HeaderTypes = None,823 cookies: CookieTypes = None,824 stream: bool = False,825 auth: AuthTypes = None,826 allow_redirects: bool = True,827 cert: CertTypes = None,828 verify: VerifyTypes = None,829 timeout: TimeoutTypes = None,830 ) -> Response:831 return self.request(832 "PATCH",833 url,834 data=data,835 files=files,836 json=json,837 params=params,838 headers=headers,839 cookies=cookies,840 stream=stream,841 auth=auth,842 allow_redirects=allow_redirects,843 verify=verify,844 cert=cert,845 timeout=timeout,846 )847848 def delete(849 self,850 url: URLTypes,851 *,852 data: RequestData = None,853 files: RequestFiles = None,854 json: typing.Any = None,855 params: QueryParamTypes = None,856 headers: HeaderTypes = None,857 cookies: CookieTypes = None,858 stream: bool = False,859 auth: AuthTypes = None,860 allow_redirects: bool = True,861 cert: CertTypes = None,862 verify: VerifyTypes = None,863 timeout: TimeoutTypes = None,864 ) -> Response:865 return self.request(866 "DELETE",867 url,868 data=data,869 files=files,870 json=json,871 params=params,872 headers=headers,873 cookies=cookies,874 stream=stream,875 auth=auth,876 allow_redirects=allow_redirects,877 verify=verify,878 cert=cert,879 timeout=timeout,880 )881882 def close(self) -> None:883 coroutine = self.dispatch.close884 self.concurrency_backend.run(coroutine)885886 def __enter__(self) -> "Client":887 return self888889 def __exit__(890 self,891 exc_type: typing.Type[BaseException] = None,892 exc_value: BaseException = None,893 traceback: TracebackType = None,894 ) -> None:895 self.close()
deleted:http3/concurrency.py-271 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 typing15from types import TracebackType1617from .config import PoolLimits, TimeoutConfig18from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19from .interfaces import (20 BaseBackgroundManager,21 BasePoolSemaphore,22 BaseReader,23 BaseWriter,24 ConcurrencyBackend,25 Protocol,26)2728SSL_MONKEY_PATCH_APPLIED = False293031def ssl_monkey_patch() -> None:32 """33 Monky-patch for https://bugs.python.org/issue367093435 This prevents console errors when outstanding HTTPS connections36 still exist at the point of exiting.3738 Clients which have been opened using a `with` block, or which have39 had `close()` closed, will not exhibit this issue in the first place.40 """41 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore4243 _write = MonkeyPatch.write4445 def _fixed_write(self, data: bytes) -> None: # type: ignore46 if self._loop and not self._loop.is_closed():47 _write(self, data)4849 MonkeyPatch.write = _fixed_write505152class TimeoutFlag:53 """54 A timeout flag holds a state of either read-timeout or write-timeout mode.5556 We use this so that we can attempt both reads and writes concurrently, while57 only enforcing timeouts in one direction.5859 During a request/response cycle we start in write-timeout mode.6061 Once we've sent a request fully, or once we start seeing a response,62 then we switch to read-timeout mode instead.63 """6465 def __init__(self) -> None:66 self.raise_on_read_timeout = False67 self.raise_on_write_timeout = True6869 def set_read_timeouts(self) -> None:70 """71 Set the flag to read-timeout mode.72 """73 self.raise_on_read_timeout = True74 self.raise_on_write_timeout = False7576 def set_write_timeouts(self) -> None:77 """78 Set the flag to write-timeout mode.79 """80 self.raise_on_read_timeout = False81 self.raise_on_write_timeout = True828384class Reader(BaseReader):85 def __init__(86 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87 ) -> None:88 self.stream_reader = stream_reader89 self.timeout = timeout9091 async def read(92 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93 ) -> bytes:94 if timeout is None:95 timeout = self.timeout9697 while True:98 # Check our flag at the first possible moment, and use a fine99 # grained retry loop if we're not yet in read-timeout mode.100 should_raise = flag is None or flag.raise_on_read_timeout101 read_timeout = timeout.read_timeout if should_raise else 0.01102 try:103 data = await asyncio.wait_for(self.stream_reader.read(n), read_timeout)104 break105 except asyncio.TimeoutError:106 if should_raise:107 raise ReadTimeout() from None108109 return data110111112class Writer(BaseWriter):113 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):114 self.stream_writer = stream_writer115 self.timeout = timeout116117 def write_no_block(self, data: bytes) -> None:118 self.stream_writer.write(data) # pragma: nocover119120 async def write(121 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None122 ) -> None:123 if not data:124 return125126 if timeout is None:127 timeout = self.timeout128129 self.stream_writer.write(data)130 while True:131 try:132 await asyncio.wait_for( # type: ignore133 self.stream_writer.drain(), timeout.write_timeout134 )135 break136 except asyncio.TimeoutError:137 # We check our flag at the possible moment, in order to138 # allow us to suppress write timeouts, if we've since139 # switched over to read-timeout mode.140 should_raise = flag is None or flag.raise_on_write_timeout141 if should_raise:142 raise WriteTimeout() from None143144 async def close(self) -> None:145 self.stream_writer.close()146147148class PoolSemaphore(BasePoolSemaphore):149 def __init__(self, pool_limits: PoolLimits):150 self.pool_limits = pool_limits151152 @property153 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:154 if not hasattr(self, "_semaphore"):155 max_connections = self.pool_limits.hard_limit156 if max_connections is None:157 self._semaphore = None158 else:159 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)160 return self._semaphore161162 async def acquire(self) -> None:163 if self.semaphore is None:164 return165166 timeout = self.pool_limits.pool_timeout167 try:168 await asyncio.wait_for(self.semaphore.acquire(), timeout)169 except asyncio.TimeoutError:170 raise PoolTimeout()171172 def release(self) -> None:173 if self.semaphore is None:174 return175176 self.semaphore.release()177178179class AsyncioBackend(ConcurrencyBackend):180 def __init__(self) -> None:181 global SSL_MONKEY_PATCH_APPLIED182183 if not SSL_MONKEY_PATCH_APPLIED:184 ssl_monkey_patch()185 SSL_MONKEY_PATCH_APPLIED = True186187 @property188 def loop(self) -> asyncio.AbstractEventLoop:189 if not hasattr(self, "_loop"):190 try:191 self._loop = asyncio.get_event_loop()192 except RuntimeError:193 self._loop = asyncio.new_event_loop()194 return self._loop195196 async def connect(197 self,198 hostname: str,199 port: int,200 ssl_context: typing.Optional[ssl.SSLContext],201 timeout: TimeoutConfig,202 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:203 try:204 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore205 asyncio.open_connection(hostname, port, ssl=ssl_context),206 timeout.connect_timeout,207 )208 except asyncio.TimeoutError:209 raise ConnectTimeout()210211 ssl_object = stream_writer.get_extra_info("ssl_object")212 if ssl_object is None:213 ident = "http/1.1"214 else:215 ident = ssl_object.selected_alpn_protocol()216 if ident is None:217 ident = ssl_object.selected_npn_protocol()218219 reader = Reader(stream_reader=stream_reader, timeout=timeout)220 writer = Writer(stream_writer=stream_writer, timeout=timeout)221 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11222223 return (reader, writer, protocol)224225 async def run_in_threadpool(226 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any227 ) -> typing.Any:228 if kwargs:229 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here230 func = functools.partial(func, **kwargs)231 return await self.loop.run_in_executor(None, func, *args)232233 def run(234 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any235 ) -> typing.Any:236 loop = self.loop237 if loop.is_running():238 self._loop = asyncio.new_event_loop()239 try:240 return self.loop.run_until_complete(coroutine(*args, **kwargs))241 finally:242 self._loop = loop243244 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:245 return PoolSemaphore(limits)246247 def background_manager(248 self, coroutine: typing.Callable, args: typing.Any249 ) -> "BackgroundManager":250 return BackgroundManager(coroutine, args)251252253class BackgroundManager(BaseBackgroundManager):254 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:255 self.coroutine = coroutine256 self.args = args257258 async def __aenter__(self) -> "BackgroundManager":259 loop = asyncio.get_event_loop()260 self.task = loop.create_task(self.coroutine(*self.args))261 return self262263 async def __aexit__(264 self,265 exc_type: typing.Type[BaseException] = None,266 exc_value: BaseException = None,267 traceback: TracebackType = None,268 ) -> None:269 await self.task270 if exc_type is None:271 self.task.result()
deleted:http3/config.py-250 removed
1import asyncio2import os3import ssl4import typing56import certifi78from .__version__ import __version__910CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11VerifyTypes = typing.Union[str, bool]12TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]131415USER_AGENT = f"python-http3/{__version__}"1617DEFAULT_CIPHERS = ":".join(18 [19 "ECDHE+AESGCM",20 "ECDHE+CHACHA20",21 "DHE+AESGCM",22 "DHE+CHACHA20",23 "ECDH+AESGCM",24 "DH+AESGCM",25 "ECDH+AES",26 "DH+AES",27 "RSA+AESGCM",28 "RSA+AES",29 "!aNULL",30 "!eNULL",31 "!MD5",32 "!DSS",33 ]34)353637class SSLConfig:38 """39 SSL Configuration.40 """4142 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43 self.cert = cert44 self.verify = verify4546 self.ssl_context: typing.Optional[ssl.SSLContext] = None4748 def __eq__(self, other: typing.Any) -> bool:49 return (50 isinstance(other, self.__class__)51 and self.cert == other.cert52 and self.verify == other.verify53 )5455 def __repr__(self) -> str:56 class_name = self.__class__.__name__57 return f"{class_name}(cert={self.cert}, verify={self.verify})"5859 def with_overrides(60 self, cert: CertTypes = None, verify: VerifyTypes = None61 ) -> "SSLConfig":62 cert = self.cert if cert is None else cert63 verify = self.verify if verify is None else verify64 if (cert == self.cert) and (verify == self.verify):65 return self66 return SSLConfig(cert=cert, verify=verify)6768 async def load_ssl_context(self) -> ssl.SSLContext:69 if self.ssl_context is None:70 if not self.verify:71 self.ssl_context = self.load_ssl_context_no_verify()72 else:73 # Run the SSL loading in a threadpool, since it makes disk accesses.74 loop = asyncio.get_event_loop()75 self.ssl_context = await loop.run_in_executor(76 None, self.load_ssl_context_verify77 )7879 assert self.ssl_context is not None80 return self.ssl_context8182 def load_ssl_context_no_verify(self) -> ssl.SSLContext:83 """84 Return an SSL context for unverified connections.85 """86 context = self._create_default_ssl_context()87 context.verify_mode = ssl.CERT_NONE88 context.check_hostname = False89 return context9091 def load_ssl_context_verify(self) -> ssl.SSLContext:92 """93 Return an SSL context for verified connections.94 """95 if isinstance(self.verify, bool):96 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH97 elif os.path.exists(self.verify):98 ca_bundle_path = self.verify99 else:100 raise IOError(101 "Could not find a suitable TLS CA certificate bundle, "102 "invalid path: {}".format(self.verify)103 )104105 context = self._create_default_ssl_context()106 context.verify_mode = ssl.CERT_REQUIRED107 context.check_hostname = True108109 # Signal to server support for PHA in TLS 1.3. Raises an110 # AttributeError if only read-only access is implemented.111 try:112 context.post_handshake_auth = True # type: ignore113 except AttributeError: # pragma: nocover114 pass115116 # Disable using 'commonName' for SSLContext.check_hostname117 # when the 'subjectAltName' extension isn't available.118 try:119 context.hostname_checks_common_name = False # type: ignore120 except AttributeError: # pragma: nocover121 pass122123 if os.path.isfile(ca_bundle_path):124 context.load_verify_locations(cafile=ca_bundle_path)125 elif os.path.isdir(ca_bundle_path):126 context.load_verify_locations(capath=ca_bundle_path)127128 if self.cert is not None:129 if isinstance(self.cert, str):130 context.load_cert_chain(certfile=self.cert)131 elif isinstance(self.cert, tuple) and len(self.cert) == 2:132 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])133 elif isinstance(self.cert, tuple) and len(self.cert) == 3:134 context.load_cert_chain(135 certfile=self.cert[0],136 keyfile=self.cert[1],137 password=self.cert[2], # type: ignore138 )139140 return context141142 def _create_default_ssl_context(self) -> ssl.SSLContext:143 """144 Creates the default SSLContext object that's used for both verified145 and unverified connections.146 """147 context = ssl.SSLContext(ssl.PROTOCOL_TLS)148 context.options |= ssl.OP_NO_SSLv2149 context.options |= ssl.OP_NO_SSLv3150 context.options |= ssl.OP_NO_COMPRESSION151 context.set_ciphers(DEFAULT_CIPHERS)152153 if ssl.HAS_ALPN:154 context.set_alpn_protocols(["h2", "http/1.1"])155 if ssl.HAS_NPN:156 context.set_npn_protocols(["h2", "http/1.1"])157158 return context159160161class TimeoutConfig:162 """163 Timeout values.164 """165166 def __init__(167 self,168 timeout: TimeoutTypes = None,169 *,170 connect_timeout: float = None,171 read_timeout: float = None,172 write_timeout: float = None,173 ):174 if timeout is None:175 self.connect_timeout = connect_timeout176 self.read_timeout = read_timeout177 self.write_timeout = write_timeout178 else:179 # Specified as a single timeout value180 assert connect_timeout is None181 assert read_timeout is None182 assert write_timeout is None183 if isinstance(timeout, TimeoutConfig):184 self.connect_timeout = timeout.connect_timeout185 self.read_timeout = timeout.read_timeout186 self.write_timeout = timeout.write_timeout187 elif isinstance(timeout, tuple):188 self.connect_timeout = timeout[0]189 self.read_timeout = timeout[1]190 self.write_timeout = timeout[2]191 else:192 self.connect_timeout = timeout193 self.read_timeout = timeout194 self.write_timeout = timeout195196 def __eq__(self, other: typing.Any) -> bool:197 return (198 isinstance(other, self.__class__)199 and self.connect_timeout == other.connect_timeout200 and self.read_timeout == other.read_timeout201 and self.write_timeout == other.write_timeout202 )203204 def __repr__(self) -> str:205 class_name = self.__class__.__name__206 if len({self.connect_timeout, self.read_timeout, self.write_timeout}) == 1:207 return f"{class_name}(timeout={self.connect_timeout})"208 return (209 f"{class_name}(connect_timeout={self.connect_timeout}, "210 f"read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"211 )212213214class PoolLimits:215 """216 Limits on the number of connections in a connection pool.217 """218219 def __init__(220 self,221 *,222 soft_limit: int = None,223 hard_limit: int = None,224 pool_timeout: float = None,225 ):226 self.soft_limit = soft_limit227 self.hard_limit = hard_limit228 self.pool_timeout = pool_timeout229230 def __eq__(self, other: typing.Any) -> bool:231 return (232 isinstance(other, self.__class__)233 and self.soft_limit == other.soft_limit234 and self.hard_limit == other.hard_limit235 and self.pool_timeout == other.pool_timeout236 )237238 def __repr__(self) -> str:239 class_name = self.__class__.__name__240 return (241 f"{class_name}(soft_limit={self.soft_limit}, "242 f"hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"243 )244245246DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)247DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)248DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)249DEFAULT_CA_BUNDLE_PATH = certifi.where()250DEFAULT_MAX_REDIRECTS = 20
deleted:http3/decoders.py-149 removed
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 "gzip": GZipDecoder,138 "deflate": DeflateDecoder,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:http3/exceptions.py-135 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 NotConnected(Exception):38 """39 A connection was lost at the point of starting a request,40 prior to any writes succeeding.41 """424344class HttpError(Exception):45 """46 An HTTP error occurred.47 """484950class ProtocolError(Exception):51 """52 Malformed HTTP.53 """545556class DecodingError(Exception):57 """58 Decoding of the response failed.59 """606162# Redirect exceptions...636465class RedirectError(Exception):66 """67 Base class for HTTP redirect errors.68 """697071class TooManyRedirects(RedirectError):72 """73 Too many redirects.74 """757677class RedirectBodyUnavailable(RedirectError):78 """79 Got a redirect response, but the request body was streaming, and is80 no longer available.81 """828384class RedirectLoop(RedirectError):85 """86 Infinite redirect loop.87 """888990# Stream exceptions...919293class StreamException(Exception):94 """95 The base class for stream exceptions.9697 The developer made an error in accessing the request stream in98 an invalid way.99 """100101102class StreamConsumed(StreamException):103 """104 Attempted to read or stream response content, but the content has already105 been streamed.106 """107108109class ResponseNotRead(StreamException):110 """111 Attempted to access response content, without having called `read()`112 after a streaming response.113 """114115116class ResponseClosed(StreamException):117 """118 Attempted to read or stream response content, but the request has been119 closed.120 """121122123# Other cases...124125126class InvalidURL(Exception):127 """128 URL was missing a hostname, or was not one of HTTP/HTTPS.129 """130131132class CookieConflict(Exception):133 """134 Attempted to lookup a cookie by name, but multiple cookies existed.135 """
deleted:http3/interfaces.py-227 removed
1import enum2import ssl3import typing4from types import TracebackType56from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7from .models import (8 AsyncRequest,9 AsyncRequestData,10 AsyncResponse,11 HeaderTypes,12 QueryParamTypes,13 Request,14 RequestData,15 Response,16 URLTypes,17)181920class Protocol(str, enum.Enum):21 HTTP_11 = "HTTP/1.1"22 HTTP_2 = "HTTP/2"232425class AsyncDispatcher:26 """27 Base class for async dispatcher classes, that handle sending the request.2829 Stubs out the interface, as well as providing a `.request()` convienence30 implementation, to make it easy to use or test stand-alone dispatchers,31 without requiring a complete `Client` instance.32 """3334 async def request(35 self,36 method: str,37 url: URLTypes,38 *,39 data: AsyncRequestData = b"",40 params: QueryParamTypes = None,41 headers: HeaderTypes = None,42 verify: VerifyTypes = None,43 cert: CertTypes = None,44 timeout: TimeoutTypes = None45 ) -> AsyncResponse:46 request = AsyncRequest(method, url, data=data, params=params, headers=headers)47 return await self.send(request, verify=verify, cert=cert, timeout=timeout)4849 async def send(50 self,51 request: AsyncRequest,52 verify: VerifyTypes = None,53 cert: CertTypes = None,54 timeout: TimeoutTypes = None,55 ) -> AsyncResponse:56 raise NotImplementedError() # pragma: nocover5758 async def close(self) -> None:59 pass # pragma: nocover6061 async def __aenter__(self) -> "AsyncDispatcher":62 return self6364 async def __aexit__(65 self,66 exc_type: typing.Type[BaseException] = None,67 exc_value: BaseException = None,68 traceback: TracebackType = None,69 ) -> None:70 await self.close()717273class Dispatcher:74 """75 Base class for syncronous dispatcher classes, that handle sending the request.7677 Stubs out the interface, as well as providing a `.request()` convienence78 implementation, to make it easy to use or test stand-alone dispatchers,79 without requiring a complete `Client` instance.80 """8182 def request(83 self,84 method: str,85 url: URLTypes,86 *,87 data: RequestData = b"",88 params: QueryParamTypes = None,89 headers: HeaderTypes = None,90 verify: VerifyTypes = None,91 cert: CertTypes = None,92 timeout: TimeoutTypes = None93 ) -> Response:94 request = Request(method, url, data=data, params=params, headers=headers)95 return self.send(request, verify=verify, cert=cert, timeout=timeout)9697 def send(98 self,99 request: Request,100 verify: VerifyTypes = None,101 cert: CertTypes = None,102 timeout: TimeoutTypes = None,103 ) -> Response:104 raise NotImplementedError() # pragma: nocover105106 def close(self) -> None:107 pass # pragma: nocover108109 def __enter__(self) -> "Dispatcher":110 return self111112 def __exit__(113 self,114 exc_type: typing.Type[BaseException] = None,115 exc_value: BaseException = None,116 traceback: TracebackType = None,117 ) -> None:118 self.close()119120121class BaseReader:122 """123 A stream reader. Abstracts away any asyncio-specfic interfaces124 into a more generic base class, that we can use with alternate125 backend, or for stand-alone test cases.126 """127128 async def read(129 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None130 ) -> 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 break210211 def background_manager(212 self, coroutine: typing.Callable, args: typing.Any213 ) -> "BaseBackgroundManager":214 raise NotImplementedError() # pragma: no cover215216217class BaseBackgroundManager:218 async def __aenter__(self) -> "BaseBackgroundManager":219 raise NotImplementedError() # pragma: no cover220221 async def __aexit__(222 self,223 exc_type: typing.Type[BaseException] = None,224 exc_value: BaseException = None,225 traceback: TracebackType = None,226 ) -> None:227 raise NotImplementedError() # pragma: no cover
deleted:http3/models.py-1168 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 .config import USER_AGENT14from .decoders import (15 ACCEPT_ENCODING,16 SUPPORTED_DECODERS,17 Decoder,18 IdentityDecoder,19 MultiDecoder,20)21from .exceptions import (22 CookieConflict,23 HttpError,24 InvalidURL,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,28)29from .multipart import multipart_encode30from .status_codes import StatusCode31from .utils import (32 guess_json_utf,33 is_known_encoding,34 normalize_header_key,35 normalize_header_value,36)3738URLTypes = typing.Union["URL", str]3940QueryParamTypes = typing.Union[41 "QueryParams",42 typing.Mapping[str, str],43 typing.List[typing.Tuple[typing.Any, typing.Any]],44 str,45]4647HeaderTypes = typing.Union[48 "Headers",49 typing.Dict[typing.AnyStr, typing.AnyStr],50 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],51]5253CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]5455AuthTypes = typing.Union[56 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],57 typing.Callable[["AsyncRequest"], "AsyncRequest"],58]5960AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]6162RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]6364RequestFiles = typing.Dict[65 str,66 typing.Union[67 typing.IO[typing.AnyStr], # file68 typing.Tuple[str, typing.IO[typing.AnyStr]], # (filename, file)69 typing.Tuple[70 str, typing.IO[typing.AnyStr], str71 ], # (filename, file, content_type)72 ],73]7475AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]7677ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]787980class URL:81 def __init__(82 self,83 url: URLTypes,84 allow_relative: bool = False,85 params: QueryParamTypes = None,86 ) -> None:87 if isinstance(url, rfc3986.uri.URIReference):88 self.components = url89 elif isinstance(url, str):90 self.components = rfc3986.api.uri_reference(url)91 else:92 self.components = url.components9394 # Handle IDNA domain names.95 if self.components.authority:96 idna_authority = self.components.authority.encode("idna").decode("ascii")97 if idna_authority != self.components.authority:98 self.components = self.components.copy_with(authority=idna_authority)99100 # Normalize scheme and domain name.101 self.components = self.components.normalize()102103 # Add any query parameters.104 if params:105 query_string = str(QueryParams(params))106 self.components = self.components.copy_with(query=query_string)107108 # Enforce absolute URLs by default.109 if not allow_relative:110 if not self.scheme:111 raise InvalidURL("No scheme included in URL.")112 if not self.host:113 raise InvalidURL("No host included in URL.")114115 @property116 def scheme(self) -> str:117 return self.components.scheme or ""118119 @property120 def authority(self) -> str:121 return self.components.authority or ""122123 @property124 def username(self) -> str:125 userinfo = self.components.userinfo or ""126 return userinfo.partition(":")[0]127128 @property129 def password(self) -> str:130 userinfo = self.components.userinfo or ""131 return userinfo.partition(":")[2]132133 @property134 def host(self) -> str:135 return self.components.host or ""136137 @property138 def port(self) -> int:139 port = self.components.port140 if port is None:141 return {"https": 443, "http": 80}[self.scheme]142 return int(port)143144 @property145 def path(self) -> str:146 return self.components.path or "/"147148 @property149 def query(self) -> str:150 return self.components.query or ""151152 @property153 def full_path(self) -> str:154 path = self.path155 if self.query:156 path += "?" + self.query157 return path158159 @property160 def fragment(self) -> str:161 return self.components.fragment or ""162163 @property164 def is_ssl(self) -> bool:165 return self.components.scheme == "https"166167 @property168 def is_absolute_url(self) -> bool:169 """170 Return `True` for absolute URLs such as 'http://example.com/path',171 and `False` for relative URLs such as '/path'.172 """173 # We don't use rfc3986's `is_absolute` because it treats174 # URLs with a fragment portion as not absolute.175 # What we actually care about is if the URL provides176 # a scheme and hostname to which connections should be made.177 return self.components.scheme and self.components.host178179 @property180 def is_relative_url(self) -> bool:181 return not self.is_absolute_url182183 @property184 def origin(self) -> "Origin":185 return Origin(self)186187 def copy_with(self, **kwargs: typing.Any) -> "URL":188 return URL(self.components.copy_with(**kwargs))189190 def join(self, relative_url: URLTypes) -> "URL":191 """192 Return an absolute URL, using given this URL as the base.193 """194 if self.is_relative_url:195 return URL(relative_url)196197 # We drop any fragment portion, because RFC 3986 strictly198 # treats URLs with a fragment portion as not being absolute URLs.199 base_components = self.components.copy_with(fragment=None)200 relative_url = URL(relative_url, allow_relative=True)201 return URL(relative_url.components.resolve_with(base_components))202203 def __hash__(self) -> int:204 return hash(str(self))205206 def __eq__(self, other: typing.Any) -> bool:207 return isinstance(other, URL) and str(self) == str(other)208209 def __str__(self) -> str:210 return self.components.unsplit()211212 def __repr__(self) -> str:213 class_name = self.__class__.__name__214 url_str = str(self)215 return f"{class_name}({url_str!r})"216217218class Origin:219 """220 The URL scheme and authority information, as a comparable, hashable object.221 """222223 def __init__(self, url: URLTypes) -> None:224 if not isinstance(url, URL):225 url = URL(url)226 self.is_ssl = url.is_ssl227 self.host = url.host228 self.port = url.port229230 def __eq__(self, other: typing.Any) -> bool:231 return (232 isinstance(other, self.__class__)233 and self.is_ssl == other.is_ssl234 and self.host == other.host235 and self.port == other.port236 )237238 def __hash__(self) -> int:239 return hash((self.is_ssl, self.host, self.port))240241242class QueryParams(typing.Mapping[str, str]):243 """244 URL query parameters, as a multi-dict.245 """246247 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:248 assert len(args) < 2, "Too many arguments."249 assert not (args and kwargs), "Cannot mix named and unnamed arguments."250251 value = args[0] if args else kwargs252253 if isinstance(value, str):254 items = parse_qsl(value)255 elif isinstance(value, QueryParams):256 items = value.multi_items()257 elif isinstance(value, list):258 items = value259 else:260 items = value.items() # type: ignore261262 self._list = [(str(k), str(v)) for k, v in items]263 self._dict = {str(k): str(v) for k, v in items}264265 def getlist(self, key: typing.Any) -> typing.List[str]:266 return [item_value for item_key, item_value in self._list if item_key == key]267268 def keys(self) -> typing.KeysView:269 return self._dict.keys()270271 def values(self) -> typing.ValuesView:272 return self._dict.values()273274 def items(self) -> typing.ItemsView:275 return self._dict.items()276277 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:278 return list(self._list)279280 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:281 if key in self._dict:282 return self._dict[key]283 return default284285 def __getitem__(self, key: typing.Any) -> str:286 return self._dict[key]287288 def __contains__(self, key: typing.Any) -> bool:289 return key in self._dict290291 def __iter__(self) -> typing.Iterator[typing.Any]:292 return iter(self.keys())293294 def __len__(self) -> int:295 return len(self._dict)296297 def __eq__(self, other: typing.Any) -> bool:298 if not isinstance(other, self.__class__):299 return False300 return sorted(self._list) == sorted(other._list)301302 def __str__(self) -> str:303 return urlencode(self._list)304305 def __repr__(self) -> str:306 class_name = self.__class__.__name__307 query_string = str(self)308 return f"{class_name}({query_string!r})"309310311class Headers(typing.MutableMapping[str, str]):312 """313 HTTP headers, as a case-insensitive multi-dict.314 """315316 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:317 if headers is None:318 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]319 elif isinstance(headers, Headers):320 self._list = list(headers.raw)321 elif isinstance(headers, dict):322 self._list = [323 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))324 for k, v in headers.items()325 ]326 else:327 self._list = [328 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))329 for k, v in headers330 ]331 self._encoding = encoding332333 @property334 def encoding(self) -> str:335 """336 Header encoding is mandated as ascii, but we allow fallbacks to utf-8337 or iso-8859-1.338 """339 if self._encoding is None:340 for encoding in ["ascii", "utf-8"]:341 for key, value in self.raw:342 try:343 key.decode(encoding)344 value.decode(encoding)345 except UnicodeDecodeError:346 break347 else:348 # The else block runs if 'break' did not occur, meaning349 # all values fitted the encoding.350 self._encoding = encoding351 break352 else:353 # The ISO-8859-1 encoding covers all 256 code points in a byte,354 # so will never raise decode errors.355 self._encoding = "iso-8859-1"356 return self._encoding357358 @encoding.setter359 def encoding(self, value: str) -> None:360 self._encoding = value361362 @property363 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:364 """365 Returns a list of the raw header items, as byte pairs.366 May be mutated in-place.367 """368 return self._list369370 def keys(self) -> typing.List[str]: # type: ignore371 return [key.decode(self.encoding) for key, value in self._list]372373 def values(self) -> typing.List[str]: # type: ignore374 return [value.decode(self.encoding) for key, value in self._list]375376 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore377 return [378 (key.decode(self.encoding), value.decode(self.encoding))379 for key, value in self._list380 ]381382 def get(self, key: str, default: typing.Any = None) -> typing.Any:383 try:384 return self[key]385 except KeyError:386 return default387388 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:389 """390 Return multiple header values.391 """392 get_header_key = key.lower().encode(self.encoding)393394 values = [395 item_value.decode(self.encoding)396 for item_key, item_value in self._list397 if item_key == get_header_key398 ]399400 if not split_commas:401 return values402403 split_values = []404 for value in values:405 split_values.extend([item.strip() for item in value.split(",")])406 return split_values407408 def __getitem__(self, key: str) -> str:409 """410 Return a single header value.411412 If there are multiple headers with the same key, then we concatenate413 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2414 """415 normalized_key = key.lower().encode(self.encoding)416417 items = []418 for header_key, header_value in self._list:419 if header_key == normalized_key:420 items.append(header_value.decode(self.encoding))421422 if items:423 return ", ".join(items)424425 raise KeyError(key)426427 def __setitem__(self, key: str, value: str) -> None:428 """429 Set the header `key` to `value`, removing any duplicate entries.430 Retains insertion order.431 """432 set_key = key.lower().encode(self.encoding)433 set_value = value.encode(self.encoding)434435 found_indexes = []436 for idx, (item_key, item_value) in enumerate(self._list):437 if item_key == set_key:438 found_indexes.append(idx)439440 for idx in reversed(found_indexes[1:]):441 del self._list[idx]442443 if found_indexes:444 idx = found_indexes[0]445 self._list[idx] = (set_key, set_value)446 else:447 self._list.append((set_key, set_value))448449 def __delitem__(self, key: str) -> None:450 """451 Remove the header `key`.452 """453 del_key = key.lower().encode(self.encoding)454455 pop_indexes = []456 for idx, (item_key, item_value) in enumerate(self._list):457 if item_key == del_key:458 pop_indexes.append(idx)459460 for idx in reversed(pop_indexes):461 del self._list[idx]462463 def __contains__(self, key: typing.Any) -> bool:464 get_header_key = key.lower().encode(self.encoding)465 for header_key, header_value in self._list:466 if header_key == get_header_key:467 return True468 return False469470 def __iter__(self) -> typing.Iterator[typing.Any]:471 return iter(self.keys())472473 def __len__(self) -> int:474 return len(self._list)475476 def __eq__(self, other: typing.Any) -> bool:477 if not isinstance(other, Headers):478 return False479 return sorted(self._list) == sorted(other._list)480481 def __repr__(self) -> str:482 class_name = self.__class__.__name__483484 encoding_str = ""485 if self.encoding != "ascii":486 encoding_str = f", encoding={self.encoding!r}"487488 as_dict = dict(self.items())489 if len(as_dict) == len(self):490 return f"{class_name}({as_dict!r}{encoding_str})"491 as_list = self.items()492 return f"{class_name}({as_list!r}{encoding_str})"493494495class BaseRequest:496 def __init__(497 self,498 method: str,499 url: typing.Union[str, URL],500 *,501 params: QueryParamTypes = None,502 headers: HeaderTypes = None,503 cookies: CookieTypes = None,504 ):505 self.method = method.upper()506 self.url = URL(url, params=params)507 self.headers = Headers(headers)508 if cookies:509 self._cookies = Cookies(cookies)510 self._cookies.set_cookie_header(self)511512 def encode_data(513 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None514 ) -> typing.Tuple[bytes, str]:515 if json is not None:516 content = jsonlib.dumps(json).encode("utf-8")517 content_type = "application/json"518 elif files is not None:519 content, content_type = multipart_encode(data or {}, files)520 elif data is not None:521 content = urlencode(data, doseq=True).encode("utf-8")522 content_type = "application/x-www-form-urlencoded"523 else:524 content = b""525 content_type = ""526 return content, content_type527528 def prepare(self) -> None:529 content = getattr(self, "content", None) # type: bytes530 is_streaming = getattr(self, "is_streaming", False)531532 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]533534 has_host = "host" in self.headers535 has_user_agent = "user-agent" in self.headers536 has_accept = "accept" in self.headers537 has_content_length = (538 "content-length" in self.headers or "transfer-encoding" in self.headers539 )540 has_accept_encoding = "accept-encoding" in self.headers541 has_connection = "connection" in self.headers542543 if not has_host:544 auto_headers.append((b"host", self.url.authority.encode("ascii")))545 if not has_user_agent:546 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))547 if not has_accept:548 auto_headers.append((b"accept", b"*/*"))549 if not has_content_length:550 if is_streaming:551 auto_headers.append((b"transfer-encoding", b"chunked"))552 elif content:553 content_length = str(len(content)).encode()554 auto_headers.append((b"content-length", content_length))555 if not has_accept_encoding:556 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))557 if not has_connection:558 auto_headers.append((b"connection", b"keep-alive"))559560 for item in reversed(auto_headers):561 self.headers.raw.insert(0, item)562563 @property564 def cookies(self) -> "Cookies":565 if not hasattr(self, "_cookies"):566 self._cookies = Cookies()567 return self._cookies568569 def __repr__(self) -> str:570 class_name = self.__class__.__name__571 url = str(self.url)572 return f"<{class_name}({self.method!r}, {url!r})>"573574575class AsyncRequest(BaseRequest):576 def __init__(577 self,578 method: str,579 url: typing.Union[str, URL],580 *,581 params: QueryParamTypes = None,582 headers: HeaderTypes = None,583 cookies: CookieTypes = None,584 data: AsyncRequestData = None,585 files: RequestFiles = None,586 json: typing.Any = None,587 ):588 super().__init__(589 method=method, url=url, params=params, headers=headers, cookies=cookies590 )591592 if data is None or isinstance(data, dict):593 content, content_type = self.encode_data(data, files, json)594 self.is_streaming = False595 self.content = content596 if content_type:597 self.headers["Content-Type"] = content_type598 elif isinstance(data, (str, bytes)):599 data = data.encode("utf-8") if isinstance(data, str) else data600 self.is_streaming = False601 self.content = data602 else:603 assert hasattr(data, "__aiter__")604 self.is_streaming = True605 self.content_aiter = data606607 self.prepare()608609 async def read(self) -> bytes:610 """611 Read and return the response content.612 """613 if not hasattr(self, "content"):614 self.content = b"".join([part async for part in self.stream()])615 return self.content616617 async def stream(self) -> typing.AsyncIterator[bytes]:618 if self.is_streaming:619 async for part in self.content_aiter:620 yield part621 elif self.content:622 yield self.content623624625class Request(BaseRequest):626 def __init__(627 self,628 method: str,629 url: typing.Union[str, URL],630 *,631 params: QueryParamTypes = None,632 headers: HeaderTypes = None,633 cookies: CookieTypes = None,634 data: RequestData = None,635 files: RequestFiles = None,636 json: typing.Any = None,637 ):638 super().__init__(639 method=method, url=url, params=params, headers=headers, cookies=cookies640 )641642 if data is None or isinstance(data, dict):643 content, content_type = self.encode_data(data, files, json)644 self.is_streaming = False645 self.content = content646 if content_type:647 self.headers["Content-Type"] = content_type648 elif isinstance(data, (str, bytes)):649 data = data.encode("utf-8") if isinstance(data, str) else data650 self.is_streaming = False651 self.content = data652 else:653 assert hasattr(data, "__iter__")654 self.is_streaming = True655 self.content_iter = data656657 self.prepare()658659 def read(self) -> bytes:660 if not hasattr(self, "content"):661 self.content = b"".join([part for part in self.stream()])662 return self.content663664 def stream(self) -> typing.Iterator[bytes]:665 if self.is_streaming:666 for part in self.content_iter:667 yield part668 elif self.content:669 yield self.content670671672class BaseResponse:673 def __init__(674 self,675 status_code: int,676 *,677 protocol: str = None,678 headers: HeaderTypes = None,679 request: BaseRequest = None,680 on_close: typing.Callable = None,681 ):682 self.status_code = status_code683 self.protocol = protocol684 self.headers = Headers(headers)685686 self.request = request687 self.on_close = on_close688 self.next = None # typing.Optional[typing.Callable]689690 @property691 def reason_phrase(self) -> str:692 return StatusCode.get_reason_phrase(self.status_code)693694 @property695 def url(self) -> typing.Optional[URL]:696 """697 Returns the URL for which the request was made.698699 Requires that `request` was provided when instantiating the response.700 """701 return None if self.request is None else self.request.url702703 @property704 def content(self) -> bytes:705 if not hasattr(self, "_content"):706 if hasattr(self, "_raw_content"):707 raw_content = getattr(self, "_raw_content") # type: bytes708 content = self.decoder.decode(raw_content)709 content += self.decoder.flush()710 self._content = content711 else:712 raise ResponseNotRead()713 return self._content714715 @property716 def text(self) -> str:717 if not hasattr(self, "_text"):718 content = self.content719 if not content:720 self._text = ""721 else:722 encoding = self.encoding723 self._text = content.decode(encoding, errors="replace")724 return self._text725726 @property727 def encoding(self) -> str:728 if not hasattr(self, "_encoding"):729 encoding = self.charset_encoding730 if encoding is None or not is_known_encoding(encoding):731 encoding = self.apparent_encoding732 if encoding is None or not is_known_encoding(encoding):733 encoding = "utf-8"734 self._encoding = encoding735 return self._encoding736737 @encoding.setter738 def encoding(self, value: str) -> None:739 self._encoding = value740741 @property742 def charset_encoding(self) -> typing.Optional[str]:743 """744 Return the encoding, as specified by the Content-Type header.745 """746 content_type = self.headers.get("Content-Type")747 if content_type is None:748 return None749750 parsed = cgi.parse_header(content_type)751 media_type, params = parsed[0], parsed[-1]752 if "charset" in params:753 return params["charset"].strip("'\"")754755 # RFC 2616 specifies that 'iso-8859-1' should be used as the default756 # for 'text/*' media types, if no charset is provided.757 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1758 if media_type.startswith("text/"):759 return "iso-8859-1"760761 return None762763 @property764 def apparent_encoding(self) -> typing.Optional[str]:765 """766 Return the encoding, as it appears to autodetection.767 """768 return chardet.detect(self.content)["encoding"]769770 @property771 def decoder(self) -> Decoder:772 """773 Returns a decoder instance which can be used to decode the raw byte774 content, depending on the Content-Encoding used in the response.775 """776 if not hasattr(self, "_decoder"):777 decoders = [] # type: typing.List[Decoder]778 values = self.headers.getlist("content-encoding", split_commas=True)779 for value in values:780 value = value.strip().lower()781 decoder_cls = SUPPORTED_DECODERS[value]782 decoders.append(decoder_cls())783784 if len(decoders) == 1:785 self._decoder = decoders[0]786 elif len(decoders) > 1:787 self._decoder = MultiDecoder(decoders)788 else:789 self._decoder = IdentityDecoder()790791 return self._decoder792793 @property794 def is_redirect(self) -> bool:795 return StatusCode.is_redirect(self.status_code) and "location" in self.headers796797 def raise_for_status(self) -> None:798 """799 Raise the `HttpError` if one occurred.800 """801 message = (802 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"803 "For more information check: https://httpstatuses.com/{0.status_code}"804 )805806 if StatusCode.is_client_error(self.status_code):807 message = message.format(self, error_type="Client Error")808 elif StatusCode.is_server_error(self.status_code):809 message = message.format(self, error_type="Server Error")810 else:811 message = ""812813 if message:814 raise HttpError(message)815816 def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:817 if self.charset_encoding is None and self.content and len(self.content) > 3:818 encoding = guess_json_utf(self.content)819 if encoding is not None:820 try:821 return jsonlib.loads(self.content.decode(encoding), **kwargs)822 except UnicodeDecodeError:823 pass824 return jsonlib.loads(self.text, **kwargs)825826 @property827 def cookies(self) -> "Cookies":828 if not hasattr(self, "_cookies"):829 assert self.request is not None830 self._cookies = Cookies()831 self._cookies.extract_cookies(self)832 return self._cookies833834 def __repr__(self) -> str:835 return f"<Response [{self.status_code} {self.reason_phrase}]>"836837838class AsyncResponse(BaseResponse):839 def __init__(840 self,841 status_code: int,842 *,843 protocol: str = None,844 headers: HeaderTypes = None,845 content: AsyncResponseContent = None,846 on_close: typing.Callable = None,847 request: AsyncRequest = None,848 history: typing.List["BaseResponse"] = None,849 ):850 super().__init__(851 status_code=status_code,852 protocol=protocol,853 headers=headers,854 request=request,855 on_close=on_close,856 )857858 self.history = [] if history is None else list(history)859860 if content is None or isinstance(content, bytes):861 self.is_closed = True862 self.is_stream_consumed = True863 self._raw_content = content or b""864 else:865 self.is_closed = False866 self.is_stream_consumed = False867 self._raw_stream = content868869 async def read(self) -> bytes:870 """871 Read and return the response content.872 """873 if not hasattr(self, "_content"):874 self._content = b"".join([part async for part in self.stream()])875 return self._content876877 async def stream(self) -> typing.AsyncIterator[bytes]:878 """879 A byte-iterator over the decoded response content.880 This allows us to handle gzip, deflate, and brotli encoded responses.881 """882 if hasattr(self, "_content"):883 yield self._content884 else:885 async for chunk in self.raw():886 yield self.decoder.decode(chunk)887 yield self.decoder.flush()888889 async def raw(self) -> typing.AsyncIterator[bytes]:890 """891 A byte-iterator over the raw response content.892 """893 if hasattr(self, "_raw_content"):894 yield self._raw_content895 else:896 if self.is_stream_consumed:897 raise StreamConsumed()898 if self.is_closed:899 raise ResponseClosed()900901 self.is_stream_consumed = True902 async for part in self._raw_stream:903 yield part904 await self.close()905906 async def close(self) -> None:907 """908 Close the response and release the connection.909 Automatically called if the response body is read to completion.910 """911 if not self.is_closed:912 self.is_closed = True913 if self.on_close is not None:914 await self.on_close()915916917class Response(BaseResponse):918 def __init__(919 self,920 status_code: int,921 *,922 protocol: str = None,923 headers: HeaderTypes = None,924 content: ResponseContent = None,925 on_close: typing.Callable = None,926 request: Request = None,927 history: typing.List["BaseResponse"] = None,928 ):929 super().__init__(930 status_code=status_code,931 protocol=protocol,932 headers=headers,933 request=request,934 on_close=on_close,935 )936937 self.history = [] if history is None else list(history)938939 if content is None or isinstance(content, bytes):940 self.is_closed = True941 self.is_stream_consumed = True942 self._raw_content = content or b""943 else:944 self.is_closed = False945 self.is_stream_consumed = False946 self._raw_stream = content947948 def read(self) -> bytes:949 """950 Read and return the response content.951 """952 if not hasattr(self, "_content"):953 self._content = b"".join([part for part in self.stream()])954 return self._content955956 def stream(self) -> typing.Iterator[bytes]:957 """958 A byte-iterator over the decoded response content.959 This allows us to handle gzip, deflate, and brotli encoded responses.960 """961 if hasattr(self, "_content"):962 yield self._content963 else:964 for chunk in self.raw():965 yield self.decoder.decode(chunk)966 yield self.decoder.flush()967968 def raw(self) -> typing.Iterator[bytes]:969 """970 A byte-iterator over the raw response content.971 """972 if hasattr(self, "_raw_content"):973 yield self._raw_content974 else:975 if self.is_stream_consumed:976 raise StreamConsumed()977 if self.is_closed:978 raise ResponseClosed()979980 self.is_stream_consumed = True981 for part in self._raw_stream:982 yield part983 self.close()984985 def close(self) -> None:986 """987 Close the response and release the connection.988 Automatically called if the response body is read to completion.989 """990 if not self.is_closed:991 self.is_closed = True992 if self.on_close is not None:993 self.on_close()994995996class Cookies(MutableMapping):997 """998 HTTP Cookies, as a mutable mapping.999 """10001001 def __init__(self, cookies: CookieTypes = None) -> None:1002 if cookies is None or isinstance(cookies, dict):1003 self.jar = CookieJar()1004 if isinstance(cookies, dict):1005 for key, value in cookies.items():1006 self.set(key, value)1007 elif isinstance(cookies, Cookies):1008 self.jar = CookieJar()1009 for cookie in cookies.jar:1010 self.jar.set_cookie(cookie)1011 else:1012 self.jar = cookies10131014 def extract_cookies(self, response: BaseResponse) -> None:1015 """1016 Loads any cookies based on the response `Set-Cookie` headers.1017 """1018 assert response.request is not None1019 urlib_response = self._CookieCompatResponse(response)1020 urllib_request = self._CookieCompatRequest(response.request)10211022 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore10231024 def set_cookie_header(self, request: BaseRequest) -> None:1025 """1026 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1027 """1028 urllib_request = self._CookieCompatRequest(request)1029 self.jar.add_cookie_header(urllib_request)10301031 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1032 """1033 Set a cookie value by name. May optionally include domain and path.1034 """1035 kwargs = dict(1036 version=0,1037 name=name,1038 value=value,1039 port=None,1040 port_specified=False,1041 domain=domain,1042 domain_specified=bool(domain),1043 domain_initial_dot=domain.startswith("."),1044 path=path,1045 path_specified=bool(path),1046 secure=False,1047 expires=None,1048 discard=True,1049 comment=None,1050 comment_url=None,1051 rest={"HttpOnly": None},1052 rfc2109=False,1053 )1054 cookie = Cookie(**kwargs) # type: ignore1055 self.jar.set_cookie(cookie)10561057 def get( # type: ignore1058 self, name: str, default: str = None, domain: str = None, path: str = None1059 ) -> typing.Optional[str]:1060 """1061 Get a cookie by name. May optionally include domain and path1062 in order to specify exactly which cookie to retrieve.1063 """1064 value = None1065 for cookie in self.jar:1066 if cookie.name == name:1067 if domain is None or cookie.domain == domain: # type: ignore1068 if path is None or cookie.path == path:1069 if value is not None:1070 message = f"Multiple cookies exist with name={name}"1071 raise CookieConflict(message)1072 value = cookie.value10731074 if value is None:1075 return default1076 return value10771078 def delete(self, name: str, domain: str = None, path: str = None) -> None:1079 """1080 Delete a cookie by name. May optionally include domain and path1081 in order to specify exactly which cookie to delete.1082 """1083 if domain is not None and path is not None:1084 return self.jar.clear(domain, path, name)10851086 remove = []1087 for cookie in self.jar:1088 if cookie.name == name:1089 if domain is None or cookie.domain == domain: # type: ignore1090 if path is None or cookie.path == path:1091 remove.append(cookie)10921093 for cookie in remove:1094 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10951096 def clear(self, domain: str = None, path: str = None) -> None:1097 """1098 Delete all cookies. Optionally include a domain and path in1099 order to only delete a subset of all the cookies.1100 """1101 args = []1102 if domain is not None:1103 args.append(domain)1104 if path is not None:1105 assert domain is not None1106 args.append(path)1107 self.jar.clear(*args)11081109 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1110 cookies = Cookies(cookies)1111 for cookie in cookies.jar:1112 self.jar.set_cookie(cookie)11131114 def __setitem__(self, name: str, value: str) -> None:1115 return self.set(name, value)11161117 def __getitem__(self, name: str) -> str:1118 value = self.get(name)1119 if value is None:1120 raise KeyError(name)1121 return value11221123 def __delitem__(self, name: str) -> None:1124 return self.delete(name)11251126 def __len__(self) -> int:1127 return len(self.jar)11281129 def __iter__(self) -> typing.Iterator[str]:1130 return (cookie.name for cookie in self.jar)11311132 def __bool__(self) -> bool:1133 for cookie in self.jar:1134 return True1135 return False11361137 class _CookieCompatRequest(urllib.request.Request):1138 """1139 Wraps a `Request` instance up in a compatability interface suitable1140 for use with `CookieJar` operations.1141 """11421143 def __init__(self, request: BaseRequest) -> None:1144 super().__init__(1145 url=str(request.url),1146 headers=dict(request.headers),1147 method=request.method,1148 )1149 self.request = request11501151 def add_unredirected_header(self, key: str, value: str) -> None:1152 super().add_unredirected_header(key, value)1153 self.request.headers[key] = value11541155 class _CookieCompatResponse:1156 """1157 Wraps a `Request` instance up in a compatability interface suitable1158 for use with `CookieJar` operations.1159 """11601161 def __init__(self, response: BaseResponse):1162 self.response = response11631164 def info(self) -> email.message.Message:1165 info = email.message.Message()1166 for key, value in self.response.headers.items():1167 info[key] = value1168 return info
deleted:http3/multipart.py-106 removed
1import binascii2import mimetypes3import os4import typing5from io import BytesIO6from urllib.parse import quote789class Field:10 def render_headers(self) -> bytes:11 raise NotImplementedError() # pragma: nocover1213 def render_data(self) -> bytes:14 raise NotImplementedError() # pragma: nocover151617class DataField(Field):18 def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:19 if not isinstance(name, str):20 raise TypeError("Invalid type for name. Expected str.")21 if not isinstance(value, (str, bytes)):22 raise TypeError("Invalid type for value. Expected str or bytes.")23 self.name = name24 self.value = value2526 def render_headers(self) -> bytes:27 name = quote(self.name, encoding="utf-8").encode("ascii")28 return b"".join(29 [b'Content-Disposition: form-data; name="', name, b'"\r\n' b"\r\n"]30 )3132 def render_data(self) -> bytes:33 return (34 self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")35 )363738class FileField(Field):39 def __init__(40 self, name: str, value: typing.Union[typing.IO[typing.AnyStr], tuple]41 ) -> None:42 self.name = name43 if not isinstance(value, tuple):44 self.filename = os.path.basename(getattr(value, "name", "upload"))45 self.file = value # type: typing.Union[typing.IO[str], typing.IO[bytes]]46 self.content_type = self.guess_content_type()47 else:48 self.filename = value[0]49 self.file = value[1]50 self.content_type = (51 value[2] if len(value) > 2 else self.guess_content_type()52 )5354 def guess_content_type(self) -> str:55 return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"5657 def render_headers(self) -> bytes:58 name = quote(self.name, encoding="utf-8").encode("ascii")59 filename = quote(self.filename, encoding="utf-8").encode("ascii")60 content_type = self.content_type.encode("ascii")61 return b"".join(62 [63 b'Content-Disposition: form-data; name="',64 name,65 b'"; filename="',66 filename,67 b'"\r\n',68 b"Content-Type: ",69 content_type,70 b"\r\n",71 b"\r\n",72 ]73 )7475 def render_data(self) -> bytes:76 content = self.file.read()77 return content.encode("utf-8") if isinstance(content, str) else content787980def iter_fields(data: dict, files: dict) -> typing.Iterator[Field]:81 for name, value in data.items():82 if isinstance(value, (list, dict)):83 for item in value:84 yield DataField(name=name, value=item)85 else:86 yield DataField(name=name, value=value)8788 for name, value in files.items():89 yield FileField(name=name, value=value)909192def multipart_encode(data: dict, files: dict) -> typing.Tuple[bytes, str]:93 body = BytesIO()94 boundary = binascii.hexlify(os.urandom(16))9596 for field in iter_fields(data, files):97 body.write(b"--%s\r\n" % boundary)98 body.write(field.render_headers())99 body.write(field.render_data())100 body.write(b"\r\n")101102 body.write(b"--%s--\r\n" % boundary)103104 content_type = "multipart/form-data; boundary=%s" % boundary.decode("ascii")105106 return body.getvalue(), content_type
deleted:http3/status_codes.py-131 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 get_reason_phrase(cls, value: int) -> str:30 try:31 return StatusCode(value).phrase # type: ignore32 except ValueError:33 return ""3435 @classmethod36 def is_redirect(cls, value: int) -> bool:37 return value in (38 # 301 (Cacheable redirect. Method may change to GET.)39 StatusCode.MOVED_PERMANENTLY,40 # 302 (Uncacheable redirect. Method may change to GET.)41 StatusCode.FOUND,42 # 303 (Client should make a GET or HEAD request.)43 StatusCode.SEE_OTHER,44 # 307 (Equiv. 302, but retain method)45 StatusCode.TEMPORARY_REDIRECT,46 # 308 (Equiv. 301, but retain method)47 StatusCode.PERMANENT_REDIRECT,48 )4950 @classmethod51 def is_client_error(cls, value: int) -> bool:52 return value >= 400 and value <= 4995354 @classmethod55 def is_server_error(cls, value: int) -> bool:56 return value >= 500 and value <= 5995758 # informational59 CONTINUE = 100, "Continue"60 SWITCHING_PROTOCOLS = 101, "Switching Protocols"61 PROCESSING = 102, "Processing"6263 # success64 OK = 200, "OK"65 CREATED = 201, "Created"66 ACCEPTED = 202, "Accepted"67 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"68 NO_CONTENT = 204, "No Content"69 RESET_CONTENT = 205, "Reset Content"70 PARTIAL_CONTENT = 206, "Partial Content"71 MULTI_STATUS = 207, "Multi-Status"72 ALREADY_REPORTED = 208, "Already Reported"73 IM_USED = 226, "IM Used"7475 # redirection76 MULTIPLE_CHOICES = 300, "Multiple Choices"77 MOVED_PERMANENTLY = 301, "Moved Permanently"78 FOUND = 302, "Found"79 SEE_OTHER = 303, "See Other"80 NOT_MODIFIED = 304, "Not Modified"81 USE_PROXY = 305, "Use Proxy"82 TEMPORARY_REDIRECT = 307, "Temporary Redirect"83 PERMANENT_REDIRECT = 308, "Permanent Redirect"8485 # client error86 BAD_REQUEST = 400, "Bad Request"87 UNAUTHORIZED = 401, "Unauthorized"88 PAYMENT_REQUIRED = 402, "Payment Required"89 FORBIDDEN = 403, "Forbidden"90 NOT_FOUND = 404, "Not Found"91 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"92 NOT_ACCEPTABLE = 406, "Not Acceptable"93 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"94 REQUEST_TIMEOUT = 408, "Request Timeout"95 CONFLICT = 409, "Conflict"96 GONE = 410, "Gone"97 LENGTH_REQUIRED = 411, "Length Required"98 PRECONDITION_FAILED = 412, "Precondition Failed"99 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"100 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"101 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"102 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"103 EXPECTATION_FAILED = 417, "Expectation Failed"104 MISDIRECTED_REQUEST = 421, "Misdirected Request"105 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"106 LOCKED = 423, "Locked"107 FAILED_DEPENDENCY = 424, "Failed Dependency"108 UPGRADE_REQUIRED = 426, "Upgrade Required"109 PRECONDITION_REQUIRED = 428, "Precondition Required"110 TOO_MANY_REQUESTS = 429, "Too Many Requests"111 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"112113 # server errors114 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"115 NOT_IMPLEMENTED = 501, "Not Implemented"116 BAD_GATEWAY = 502, "Bad Gateway"117 SERVICE_UNAVAILABLE = 503, "Service Unavailable"118 GATEWAY_TIMEOUT = 504, "Gateway Timeout"119 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"120 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"121 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"122 LOOP_DETECTED = 508, "Loop Detected"123 NOT_EXTENDED = 510, "Not Extended"124 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"125126127codes = StatusCode128129#  Include lower-case styles for `requests` compatability.130for code in codes:131 setattr(codes, code._name_.lower(), int(code))
deleted:http3/utils.py-66 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 True323334# Null bytes; no need to recreate these on each call to guess_json_utf35_null = "\x00".encode("ascii") # encoding to ASCII for Python 336_null2 = _null * 237_null3 = _null * 3383940def guess_json_utf(data: bytes) -> typing.Optional[str]:41 # JSON always starts with two ASCII characters, so detection is as42 # easy as counting the nulls and from their location and count43 # determine the encoding. Also detect a BOM, if present.44 sample = data[:4]45 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):46 return "utf-32" # BOM included47 if sample[:3] == codecs.BOM_UTF8:48 return "utf-8-sig" # BOM included, MS style (discouraged)49 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):50 return "utf-16" # BOM included51 nullcount = sample.count(_null)52 if nullcount == 0:53 return "utf-8"54 if nullcount == 2:55 if sample[::2] == _null2: # 1st and 3rd are null56 return "utf-16-be"57 if sample[1::2] == _null2: # 2nd and 4th are null58 return "utf-16-le"59 # Did not detect 2 valid UTF-16 ascii-range characters60 if nullcount == 3:61 if sample[:3] == _null3:62 return "utf-32-be"63 if sample[1:] == _null3:64 return "utf-32-le"65 # Did not detect a valid UTF-32 ascii-range character66 return None
added:httpx/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:httpx/dispatch/asgi.py+187 added
1import asyncio2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import AsyncDispatcher6from ..models import AsyncRequest, AsyncResponse789class ASGIDispatch(AsyncDispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = httpx.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the ASGIDispatch class:2425 ```26 dispatch = httpx.ASGIDispatch(27 app=app,28 root_path="/submount",29 client=("1.2.3.4", 123)30 )31 client = httpx.Client(dispatch=dispatch)32 ```33 """3435 def __init__(36 self,37 app: typing.Callable,38 raise_app_exceptions: bool = True,39 root_path: str = "",40 client: typing.Tuple[str, int] = ("127.0.0.1", 123),41 ) -> None:42 self.app = app43 self.raise_app_exceptions = raise_app_exceptions44 self.root_path = root_path45 self.client = client4647 async def send(48 self,49 request: AsyncRequest,50 verify: VerifyTypes = None,51 cert: CertTypes = None,52 timeout: TimeoutTypes = None,53 ) -> AsyncResponse:5455 scope = {56 "type": "http",57 "asgi": {"version": "3.0"},58 "http_version": "1.1",59 "method": request.method,60 "headers": request.headers.raw,61 "scheme": request.url.scheme,62 "path": request.url.path,63 "query_string": request.url.query.encode("ascii"),64 "server": request.url.host,65 "client": self.client,66 "root_path": self.root_path,67 }68 app = self.app69 app_exc = None70 status_code = None71 headers = None72 response_started = asyncio.Event()73 response_body = BodyIterator()74 request_stream = request.stream()7576 async def receive() -> dict:77 nonlocal request_stream7879 try:80 body = await request_stream.__anext__()81 except StopAsyncIteration:82 return {"type": "http.request", "body": b"", "more_body": False}83 return {"type": "http.request", "body": body, "more_body": True}8485 async def send(message: dict) -> None:86 nonlocal status_code, headers, response_started, response_body, request8788 if message["type"] == "http.response.start":89 status_code = message["status"]90 headers = message.get("headers", [])91 response_started.set()92 elif message["type"] == "http.response.body":93 body = message.get("body", b"")94 more_body = message.get("more_body", False)95 if body and request.method != "HEAD":96 await response_body.put(body)97 if not more_body:98 await response_body.done()99100 async def run_app() -> None:101 nonlocal app, scope, receive, send, app_exc, response_body102 try:103 await app(scope, receive, send)104 except Exception as exc:105 app_exc = exc106 finally:107 await response_body.done()108109 # Really we'd like to push all `asyncio` logic into concurrency.py,110 # with a standardized interface, so that we can support other event111 # loop implementations, such as Trio and Curio.112 # That's a bit fiddly here, so we're not yet supporting using a custom113 # `ConcurrencyBackend` with the `Client(app=asgi_app)` case.114 loop = asyncio.get_event_loop()115 app_task = loop.create_task(run_app())116 response_task = loop.create_task(response_started.wait())117118 tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]119120 await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)121122 if app_exc is not None and self.raise_app_exceptions:123 raise app_exc124125 assert response_started.is_set(), "application did not return a response."126 assert status_code is not None127 assert headers is not None128129 async def on_close() -> None:130 nonlocal app_task, response_body131 await response_body.drain()132 await app_task133 if app_exc is not None and self.raise_app_exceptions:134 raise app_exc135136 return AsyncResponse(137 status_code=status_code,138 protocol="HTTP/1.1",139 headers=headers,140 content=response_body.iterate(),141 on_close=on_close,142 request=request,143 )144145146class BodyIterator:147 """148 Provides a byte-iterator interface that the client can use to149 ingest the response content from.150 """151152 def __init__(self) -> None:153 self._queue = asyncio.Queue(154 maxsize=1155 ) # type: asyncio.Queue[typing.Union[bytes, object]]156 self._done = object()157158 async def iterate(self) -> typing.AsyncIterator[bytes]:159 """160 A byte-iterator, used by the client to consume the response body.161 """162 while True:163 data = await self._queue.get()164 if data is self._done:165 break166 assert isinstance(data, bytes)167 yield data168169 async def drain(self) -> None:170 """171 Drain any remaining body, in order to allow any blocked `put()` calls172 to complete.173 """174 async for chunk in self.iterate():175 pass # pragma: no cover176177 async def put(self, data: bytes) -> None:178 """179 Used by the server to add data to the response body.180 """181 await self._queue.put(data)182183 async def done(self) -> None:184 """185 Used by the server to signal the end of the response body.186 """187 await self._queue.put(self._done)
added:httpx/dispatch/connection_pool.py+176 added
1import typing23from ..concurrency import AsyncioBackend4from ..config import (5 DEFAULT_POOL_LIMITS,6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,8 PoolLimits,9 TimeoutTypes,10 VerifyTypes,11)12from ..exceptions import NotConnected13from ..interfaces import AsyncDispatcher, ConcurrencyBackend14from ..models import AsyncRequest, AsyncResponse, Origin15from .connection import HTTPConnection1617CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]181920class ConnectionStore:21 """22 We need to maintain collections of connections in a way that allows us to:2324 * Lookup connections by origin.25 * Iterate over connections by insertion time.26 * Return the total number of connections.27 """2829 def __init__(self) -> None:30 self.all = {} # type: typing.Dict[HTTPConnection, float]31 self.by_origin = (32 {}33 ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3435 def pop_by_origin(36 self, origin: Origin, http2_only: bool = False37 ) -> typing.Optional[HTTPConnection]:38 try:39 connections = self.by_origin[origin]40 except KeyError:41 return None4243 connection = next(reversed(list(connections.keys())))44 if http2_only and not connection.is_http2:45 return None4647 del connections[connection]48 if not connections:49 del self.by_origin[origin]50 del self.all[connection]5152 return connection5354 def add(self, connection: HTTPConnection) -> None:55 self.all[connection] = 0.056 try:57 self.by_origin[connection.origin][connection] = 0.058 except KeyError:59 self.by_origin[connection.origin] = {connection: 0.0}6061 def remove(self, connection: HTTPConnection) -> None:62 del self.all[connection]63 del self.by_origin[connection.origin][connection]64 if not self.by_origin[connection.origin]:65 del self.by_origin[connection.origin]6667 def clear(self) -> None:68 self.all.clear()69 self.by_origin.clear()7071 def __iter__(self) -> typing.Iterator[HTTPConnection]:72 return iter(self.all.keys())7374 def __len__(self) -> int:75 return len(self.all)767778class ConnectionPool(AsyncDispatcher):79 def __init__(80 self,81 *,82 verify: VerifyTypes = True,83 cert: CertTypes = None,84 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,85 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,86 backend: ConcurrencyBackend = None,87 ):88 self.verify = verify89 self.cert = cert90 self.timeout = timeout91 self.pool_limits = pool_limits92 self.is_closed = False9394 self.keepalive_connections = ConnectionStore()95 self.active_connections = ConnectionStore()9697 self.backend = AsyncioBackend() if backend is None else backend98 self.max_connections = self.backend.get_semaphore(pool_limits)99100 @property101 def num_connections(self) -> int:102 return len(self.keepalive_connections) + len(self.active_connections)103104 async def send(105 self,106 request: AsyncRequest,107 verify: VerifyTypes = None,108 cert: CertTypes = None,109 timeout: TimeoutTypes = None,110 ) -> AsyncResponse:111 allow_connection_reuse = True112 connection = None113 while connection is None:114 connection = await self.acquire_connection(115 origin=request.url.origin, allow_connection_reuse=allow_connection_reuse116 )117 try:118 response = await connection.send(119 request, verify=verify, cert=cert, timeout=timeout120 )121 except BaseException as exc:122 self.active_connections.remove(connection)123 self.max_connections.release()124 if isinstance(exc, NotConnected) and allow_connection_reuse:125 connection = None126 allow_connection_reuse = False127 else:128 raise exc129130 return response131132 async def acquire_connection(133 self, origin: Origin, allow_connection_reuse: bool = True134 ) -> HTTPConnection:135 connection = None136 if allow_connection_reuse:137 connection = self.active_connections.pop_by_origin(origin, http2_only=True)138 if connection is None:139 connection = self.keepalive_connections.pop_by_origin(origin)140141 if connection is None:142 await self.max_connections.acquire()143 connection = HTTPConnection(144 origin,145 verify=self.verify,146 cert=self.cert,147 timeout=self.timeout,148 backend=self.backend,149 release_func=self.release_connection,150 )151152 self.active_connections.add(connection)153154 return connection155156 async def release_connection(self, connection: HTTPConnection) -> None:157 if connection.is_closed:158 self.active_connections.remove(connection)159 self.max_connections.release()160 elif (161 self.pool_limits.soft_limit is not None162 and self.num_connections > self.pool_limits.soft_limit163 ):164 self.active_connections.remove(connection)165 self.max_connections.release()166 await connection.close()167 else:168 self.active_connections.remove(connection)169 self.keepalive_connections.add(connection)170171 async def close(self) -> None:172 self.is_closed = True173 connections = list(self.keepalive_connections)174 self.keepalive_connections.clear()175 for connection in connections:176 await connection.close()
added:httpx/dispatch/connection.py+104 added
1import functools2import typing34from ..concurrency import AsyncioBackend5from ..config import (6 DEFAULT_TIMEOUT_CONFIG,7 CertTypes,8 SSLConfig,9 TimeoutConfig,10 TimeoutTypes,11 VerifyTypes,12)13from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol14from ..models import AsyncRequest, AsyncResponse, Origin15from .http2 import HTTP2Connection16from .http11 import HTTP11Connection1718# Callback signature: async def callback(conn: HTTPConnection) -> None19ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]202122class HTTPConnection(AsyncDispatcher):23 def __init__(24 self,25 origin: typing.Union[str, Origin],26 verify: VerifyTypes = True,27 cert: CertTypes = None,28 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,29 backend: ConcurrencyBackend = None,30 release_func: typing.Optional[ReleaseCallback] = None,31 ):32 self.origin = Origin(origin) if isinstance(origin, str) else origin33 self.ssl = SSLConfig(cert=cert, verify=verify)34 self.timeout = TimeoutConfig(timeout)35 self.backend = AsyncioBackend() if backend is None else backend36 self.release_func = release_func37 self.h11_connection = None # type: typing.Optional[HTTP11Connection]38 self.h2_connection = None # type: typing.Optional[HTTP2Connection]3940 async def send(41 self,42 request: AsyncRequest,43 verify: VerifyTypes = None,44 cert: CertTypes = None,45 timeout: TimeoutTypes = None,46 ) -> AsyncResponse:47 if self.h11_connection is None and self.h2_connection is None:48 await self.connect(verify=verify, cert=cert, timeout=timeout)4950 if self.h2_connection is not None:51 response = await self.h2_connection.send(request, timeout=timeout)52 else:53 assert self.h11_connection is not None54 response = await self.h11_connection.send(request, timeout=timeout)5556 return response5758 async def connect(59 self,60 verify: VerifyTypes = None,61 cert: CertTypes = None,62 timeout: TimeoutTypes = None,63 ) -> None:64 ssl = self.ssl.with_overrides(verify=verify, cert=cert)65 timeout = self.timeout if timeout is None else TimeoutConfig(timeout)6667 host = self.origin.host68 port = self.origin.port69 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None7071 if self.release_func is None:72 on_release = None73 else:74 on_release = functools.partial(self.release_func, self)7576 reader, writer, protocol = await self.backend.connect(77 host, port, ssl_context, timeout78 )79 if protocol == Protocol.HTTP_2:80 self.h2_connection = HTTP2Connection(81 reader, writer, self.backend, on_release=on_release82 )83 else:84 self.h11_connection = HTTP11Connection(85 reader, writer, self.backend, on_release=on_release86 )8788 async def close(self) -> None:89 if self.h2_connection is not None:90 await self.h2_connection.close()91 elif self.h11_connection is not None:92 await self.h11_connection.close()9394 @property95 def is_http2(self) -> bool:96 return self.h2_connection is not None9798 @property99 def is_closed(self) -> bool:100 if self.h2_connection is not None:101 return self.h2_connection.is_closed102 else:103 assert self.h11_connection is not None104 return self.h11_connection.is_closed
added:httpx/dispatch/http11.py+190 added
1import typing23import h1145from ..concurrency import TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..exceptions import NotConnected8from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9from ..models import AsyncRequest, AsyncResponse1011H11Event = typing.Union[12 h11.Request,13 h11.Response,14 h11.InformationalResponse,15 h11.Data,16 h11.EndOfMessage,17 h11.ConnectionClosed,18]192021# Callback signature: async def callback() -> None22# In practice the callback will be a functools partial, which binds23# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.24OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]252627class HTTP11Connection:28 READ_NUM_BYTES = 40962930 def __init__(31 self,32 reader: BaseReader,33 writer: BaseWriter,34 backend: ConcurrencyBackend,35 on_release: typing.Optional[OnReleaseCallback] = None,36 ):37 self.reader = reader38 self.writer = writer39 self.backend = backend40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)42 self.timeout_flag = TimeoutFlag()4344 async def send(45 self, request: AsyncRequest, timeout: TimeoutTypes = None46 ) -> AsyncResponse:47 timeout = None if timeout is None else TimeoutConfig(timeout)4849 try:50 await self._send_request(request, timeout)51 except ConnectionResetError: # pragma: nocover52 # We're currently testing this case in HTTP/2.53 # Really we should test it here too, but this'll do in the meantime.54 raise NotConnected() from None5556 task, args = self._send_request_data, [request.stream(), timeout]57 async with self.backend.background_manager(task, args=args):58 http_version, status_code, headers = await self._receive_response(timeout)59 content = self._receive_response_data(timeout)6061 return AsyncResponse(62 status_code=status_code,63 protocol=http_version,64 headers=headers,65 content=content,66 on_close=self.response_closed,67 request=request,68 )6970 async def close(self) -> None:71 event = h11.ConnectionClosed()72 try:73 self.h11_state.send(event)74 except h11.LocalProtocolError: # pragma: no cover75 # Premature client disconnect76 pass77 await self.writer.close()7879 async def _send_request(80 self, request: AsyncRequest, timeout: TimeoutConfig = None81 ) -> None:82 """83 Send the request method, URL, and headers to the network.84 """85 method = request.method.encode("ascii")86 target = request.url.full_path.encode("ascii")87 headers = request.headers.raw88 event = h11.Request(method=method, target=target, headers=headers)89 await self._send_event(event, timeout)9091 async def _send_request_data(92 self, data: typing.AsyncIterator[bytes], timeout: TimeoutConfig = None93 ) -> None:94 """95 Send the request body to the network.96 """97 try:98 # Send the request body.99 async for chunk in data:100 event = h11.Data(data=chunk)101 await self._send_event(event, timeout)102103 # Finalize sending the request.104 event = h11.EndOfMessage()105 await self._send_event(event, timeout)106 except OSError: # pragma: nocover107 # Once we've sent the initial part of the request we don't actually108 # care about connection errors that occur when sending the body.109 # Ignore these, and defer to any exceptions on reading the response.110 self.h11_state.send_failed()111 finally:112 # Once we've sent the request, we enable read timeouts.113 self.timeout_flag.set_read_timeouts()114115 async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:116 """117 Send a single `h11` event to the network, waiting for the data to118 drain before returning.119 """120 bytes_to_send = self.h11_state.send(event)121 await self.writer.write(bytes_to_send, timeout)122123 async def _receive_response(124 self, timeout: TimeoutConfig = None125 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:126 """127 Read the response status and headers from the network.128 """129 while True:130 event = await self._receive_event(timeout)131 # As soon as we start seeing response events, we should enable132 # read timeouts, if we haven't already.133 self.timeout_flag.set_read_timeouts()134 if isinstance(event, h11.InformationalResponse):135 continue136 else:137 assert isinstance(event, h11.Response)138 break139 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")140 return (http_version, event.status_code, event.headers)141142 async def _receive_response_data(143 self, timeout: TimeoutConfig = None144 ) -> typing.AsyncIterator[bytes]:145 """146 Read the response data from the network.147 """148 while True:149 event = await self._receive_event(timeout)150 if isinstance(event, h11.Data):151 yield event.data152 else:153 assert isinstance(event, h11.EndOfMessage)154 break155156 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:157 """158 Read a single `h11` event, reading more data from the network if needed.159 """160 while True:161 event = self.h11_state.next_event()162 if event is h11.NEED_DATA:163 try:164 data = await self.reader.read(165 self.READ_NUM_BYTES, timeout, flag=self.timeout_flag166 )167 except OSError: # pragma: nocover168 data = b""169 self.h11_state.receive_data(data)170 else:171 break172 return event173174 async def response_closed(self) -> None:175 if (176 self.h11_state.our_state is h11.DONE177 and self.h11_state.their_state is h11.DONE178 ):179 # Get ready for another request/response cycle.180 self.h11_state.start_next_cycle()181 self.timeout_flag.set_write_timeouts()182 else:183 await self.close()184185 if self.on_release is not None:186 await self.on_release()187188 @property189 def is_closed(self) -> bool:190 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)
added:httpx/dispatch/http2.py+178 added
1import functools2import typing34import h2.connection5import h2.events67from ..concurrency import TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..exceptions import NotConnected10from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11from ..models import AsyncRequest, AsyncResponse121314class HTTP2Connection:15 READ_NUM_BYTES = 40961617 def __init__(18 self,19 reader: BaseReader,20 writer: BaseWriter,21 backend: ConcurrencyBackend,22 on_release: typing.Callable = None,23 ):24 self.reader = reader25 self.writer = writer26 self.backend = backend27 self.on_release = on_release28 self.h2_state = h2.connection.H2Connection()29 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]30 self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]31 self.initialized = False3233 async def send(34 self, request: AsyncRequest, timeout: TimeoutTypes = None35 ) -> AsyncResponse:36 timeout = None if timeout is None else TimeoutConfig(timeout)3738 #  Start sending the request.39 if not self.initialized:40 self.initiate_connection()4142 try:43 stream_id = await self.send_headers(request, timeout)44 except ConnectionResetError:45 raise NotConnected() from None4647 self.events[stream_id] = []48 self.timeout_flags[stream_id] = TimeoutFlag()4950 task, args = self.send_request_data, [stream_id, request.stream(), timeout]51 async with self.backend.background_manager(task, args=args):52 status_code, headers = await self.receive_response(stream_id, timeout)53 content = self.body_iter(stream_id, timeout)54 on_close = functools.partial(self.response_closed, stream_id=stream_id)5556 return AsyncResponse(57 status_code=status_code,58 protocol="HTTP/2",59 headers=headers,60 content=content,61 on_close=on_close,62 request=request,63 )6465 async def close(self) -> None:66 await self.writer.close()6768 def initiate_connection(self) -> None:69 self.h2_state.initiate_connection()70 data_to_send = self.h2_state.data_to_send()71 self.writer.write_no_block(data_to_send)72 self.initialized = True7374 async def send_headers(75 self, request: AsyncRequest, timeout: TimeoutConfig = None76 ) -> int:77 stream_id = self.h2_state.get_next_available_stream_id()78 headers = [79 (b":method", request.method.encode("ascii")),80 (b":authority", request.url.authority.encode("ascii")),81 (b":scheme", request.url.scheme.encode("ascii")),82 (b":path", request.url.full_path.encode("ascii")),83 ] + [(k, v) for k, v in request.headers.raw if k != b"host"]84 self.h2_state.send_headers(stream_id, headers)85 data_to_send = self.h2_state.data_to_send()86 await self.writer.write(data_to_send, timeout)87 return stream_id8889 async def send_request_data(90 self,91 stream_id: int,92 stream: typing.AsyncIterator[bytes],93 timeout: TimeoutConfig = None,94 ) -> None:95 try:96 async for data in stream:97 await self.send_data(stream_id, data, timeout)98 await self.end_stream(stream_id, timeout)99 finally:100 # Once we've sent the request we should enable read timeouts.101 self.timeout_flags[stream_id].set_read_timeouts()102103 async def send_data(104 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None105 ) -> None:106 flow_control = self.h2_state.local_flow_control_window(stream_id)107 chunk_size = min(len(data), flow_control)108 for idx in range(0, len(data), chunk_size):109 chunk = data[idx : idx + chunk_size]110 self.h2_state.send_data(stream_id, chunk)111 data_to_send = self.h2_state.data_to_send()112 await self.writer.write(data_to_send, timeout)113114 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:115 self.h2_state.end_stream(stream_id)116 data_to_send = self.h2_state.data_to_send()117 await self.writer.write(data_to_send, timeout)118119 async def receive_response(120 self, stream_id: int, timeout: TimeoutConfig = None121 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:122 """123 Read the response status and headers from the network.124 """125 while True:126 event = await self.receive_event(stream_id, timeout)127 # As soon as we start seeing response events, we should enable128 # read timeouts, if we haven't already.129 self.timeout_flags[stream_id].set_read_timeouts()130 if isinstance(event, h2.events.ResponseReceived):131 break132133 status_code = 200134 headers = []135 for k, v in event.headers:136 if k == b":status":137 status_code = int(v.decode("ascii", errors="ignore"))138 elif not k.startswith(b":"):139 headers.append((k, v))140 return (status_code, headers)141142 async def body_iter(143 self, stream_id: int, timeout: TimeoutConfig = None144 ) -> typing.AsyncIterator[bytes]:145 while True:146 event = await self.receive_event(stream_id, timeout)147 if isinstance(event, h2.events.DataReceived):148 self.h2_state.acknowledge_received_data(len(event.data), stream_id)149 yield event.data150 elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):151 break152153 async def receive_event(154 self, stream_id: int, timeout: TimeoutConfig = None155 ) -> h2.events.Event:156 while not self.events[stream_id]:157 flag = self.timeout_flags[stream_id]158 data = await self.reader.read(self.READ_NUM_BYTES, timeout, flag=flag)159 events = self.h2_state.receive_data(data)160 for event in events:161 if getattr(event, "stream_id", 0):162 self.events[event.stream_id].append(event)163164 data_to_send = self.h2_state.data_to_send()165 await self.writer.write(data_to_send, timeout)166167 return self.events[stream_id].pop(0)168169 async def response_closed(self, stream_id: int) -> None:170 del self.events[stream_id]171 del self.timeout_flags[stream_id]172173 if not self.events and self.on_release is not None:174 await self.on_release()175176 @property177 def is_closed(self) -> bool:178 return False
added:httpx/dispatch/threaded.py+96 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 protocol=sync_response.protocol,68 headers=sync_response.headers,69 content=async_content,70 on_close=async_on_close,71 request=request,72 history=sync_response.history,73 )7475 async def close(self) -> None:76 """77 The `.close()` method runs the `Dispatcher.close()` within a threadpool,78 so as not to block the async event loop.79 """80 func = self.sync_dispatcher.close81 await self.backend.run_in_threadpool(func)8283 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:84 if isinstance(content, bytes):85 return content8687 # Coerce an async iterator into an iterator, with each item in the88 # iteration run within the event loop.89 assert hasattr(content, "__iter__")90 return self.backend.iterate_in_threadpool(content)9192 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:93 if isinstance(data, bytes):94 return data9596 return self.backend.iterate(data)
added:httpx/dispatch/wsgi.py+154 added
1import io2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import Dispatcher6from ..models import Request, Response789class WSGIDispatch(Dispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = httpx.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the WSGIDispatch class:2425 ```26 dispatch = httpx.WSGIDispatch(27 app=app,28 script_name="/submount",29 remote_addr="1.2.3.4"30 )31 client = httpx.Client(dispatch=dispatch)32 ```33 """3435 def __init__(36 self,37 app: typing.Callable,38 raise_app_exceptions: bool = True,39 script_name: str = "",40 remote_addr: str = "127.0.0.1",41 ) -> None:42 self.app = app43 self.raise_app_exceptions = raise_app_exceptions44 self.script_name = script_name45 self.remote_addr = remote_addr4647 def send(48 self,49 request: Request,50 verify: VerifyTypes = None,51 cert: CertTypes = None,52 timeout: TimeoutTypes = None,53 ) -> Response:54 environ = {55 "wsgi.version": (1, 0),56 "wsgi.url_scheme": request.url.scheme,57 "wsgi.input": BodyStream(request.stream()),58 "wsgi.errors": io.BytesIO(),59 "wsgi.multithread": True,60 "wsgi.multiprocess": False,61 "wsgi.run_once": False,62 "REQUEST_METHOD": request.method,63 "SCRIPT_NAME": self.script_name,64 "PATH_INFO": request.url.path,65 "QUERY_STRING": request.url.query,66 "SERVER_NAME": request.url.host,67 "SERVER_PORT": str(request.url.port),68 "REMOTE_ADDR": self.remote_addr,69 }70 for key, value in request.headers.items():71 key = key.upper().replace("-", "_")72 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):73 key = "HTTP_" + key74 environ[key] = value7576 seen_status = None77 seen_response_headers = None78 seen_exc_info = None7980 def start_response(81 status: str, response_headers: list, exc_info: typing.Any = None82 ) -> None:83 nonlocal seen_status, seen_response_headers, seen_exc_info84 seen_status = status85 seen_response_headers = response_headers86 seen_exc_info = exc_info8788 result = self.app(environ, start_response)8990 assert seen_status is not None91 assert seen_response_headers is not None92 if seen_exc_info and self.raise_app_exceptions:93 raise seen_exc_info[1]9495 return Response(96 status_code=int(seen_status.split()[0]),97 protocol="HTTP/1.1",98 headers=seen_response_headers,99 content=(chunk for chunk in result),100 on_close=getattr(result, "close", None),101 )102103104class BodyStream(io.RawIOBase):105 def __init__(self, iterator: typing.Iterator[bytes]) -> None:106 self._iterator = iterator107 self._buffer = b""108 self._closed = False109110 def read(self, size: int = -1) -> bytes:111 if self._closed:112 return b""113114 if size == -1:115 return self.readall()116117 try:118 while len(self._buffer) < size:119 self._buffer += next(self._iterator)120 except StopIteration:121 self._closed = True122 return self._buffer123124 output = self._buffer[:size]125 self._buffer = self._buffer[size:]126 return output127128 def readall(self) -> bytes:129 if self._closed:130 raise OSError("Stream closed") # pragma: nocover131132 for chunk in self._iterator:133 self._buffer += chunk134135 self._closed = True136 return self._buffer137138 def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover139 output = self.read(len(b))140 count = len(output)141 b[:count] = output142 return count143144 def write(self, b: bytes) -> int:145 raise OSError("Operation not supported") # pragma: nocover146147 def fileno(self) -> int:148 raise OSError("Operation not supported") # pragma: nocover149150 def seek(self, offset: int, whence: int = 0) -> int:151 raise OSError("Operation not supported") # pragma: nocover152153 def truncate(self, size: int = None) -> int:154 raise OSError("Operation not supported") # pragma: nocover
added:httpx/__init__.py+131 added
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request3from .client import AsyncClient, Client4from .concurrency import AsyncioBackend5from .config import (6 USER_AGENT,7 CertTypes,8 PoolLimits,9 SSLConfig,10 TimeoutConfig,11 TimeoutTypes,12 VerifyTypes,13)14from .dispatch.connection import HTTPConnection15from .dispatch.connection_pool import ConnectionPool16from .exceptions import (17 ConnectTimeout,18 CookieConflict,19 DecodingError,20 InvalidURL,21 PoolTimeout,22 ProtocolError,23 ReadTimeout,24 RedirectBodyUnavailable,25 RedirectLoop,26 ResponseClosed,27 ResponseNotRead,28 StreamConsumed,29 Timeout,30 TooManyRedirects,31 WriteTimeout,32)33from .interfaces import (34 AsyncDispatcher,35 BaseReader,36 BaseWriter,37 ConcurrencyBackend,38 Dispatcher,39 Protocol,40)41from .models import (42 URL,43 AsyncRequest,44 AsyncRequestData,45 AsyncResponse,46 AsyncResponseContent,47 AuthTypes,48 Cookies,49 CookieTypes,50 Headers,51 HeaderTypes,52 Origin,53 QueryParams,54 QueryParamTypes,55 Request,56 RequestData,57 RequestFiles,58 Response,59 ResponseContent,60 URLTypes,61)62from .status_codes import StatusCode, codes6364__all__ = [65 "__description__",66 "__title__",67 "__version__",68 "delete",69 "get",70 "head",71 "options",72 "patch",73 "post",74 "patch",75 "put",76 "request",77 "AsyncClient",78 "Client",79 "AsyncioBackend",80 "USER_AGENT",81 "CertTypes",82 "PoolLimits",83 "SSLConfig",84 "TimeoutConfig",85 "VerifyTypes",86 "HTTPConnection",87 "ConnectionPool",88 "ConnectTimeout",89 "CookieConflict",90 "DecodingError",91 "InvalidURL",92 "PoolTimeout",93 "ProtocolError",94 "ReadTimeout",95 "RedirectBodyUnavailable",96 "RedirectLoop",97 "ResponseClosed",98 "ResponseNotRead",99 "StreamConsumed",100 "Timeout",101 "TooManyRedirects",102 "WriteTimeout",103 "AsyncDispatcher",104 "BaseReader",105 "BaseWriter",106 "ConcurrencyBackend",107 "Dispatcher",108 "Protocol",109 "URL",110 "URLTypes",111 "StatusCode",112 "codes",113 "TimeoutTypes",114 "AsyncRequest",115 "AsyncRequestData",116 "AsyncResponse",117 "AsyncResponseContent",118 "AuthTypes",119 "Cookies",120 "CookieTypes",121 "Headers",122 "HeaderTypes",123 "Origin",124 "QueryParams",125 "QueryParamTypes",126 "Request",127 "RequestData",128 "Response",129 "ResponseContent",130 "RequestFiles",131]
added:httpx/__version__.py+3 added
1__title__ = "httpx"2__description__ = "A next generation HTTP client, for Python 3."3__version__ = "0.6.7"
added:httpx/api.py+272 added
1import typing23from .client import Client4from .config import CertTypes, TimeoutTypes, VerifyTypes5from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,9 QueryParamTypes,10 RequestData,11 RequestFiles,12 Response,13 URLTypes,14)151617def request(18 method: str,19 url: URLTypes,20 *,21 params: QueryParamTypes = None,22 data: RequestData = None,23 files: RequestFiles = None,24 json: typing.Any = None,25 headers: HeaderTypes = None,26 cookies: CookieTypes = None,27 # files28 auth: AuthTypes = None,29 timeout: TimeoutTypes = None,30 allow_redirects: bool = True,31 # proxies32 cert: CertTypes = None,33 verify: VerifyTypes = True,34 stream: bool = False,35) -> Response:36 with Client() as client:37 return client.request(38 method=method,39 url=url,40 data=data,41 files=files,42 json=json,43 params=params,44 headers=headers,45 cookies=cookies,46 stream=stream,47 auth=auth,48 allow_redirects=allow_redirects,49 cert=cert,50 verify=verify,51 timeout=timeout,52 )535455def get(56 url: URLTypes,57 *,58 params: QueryParamTypes = None,59 headers: HeaderTypes = None,60 cookies: CookieTypes = None,61 stream: bool = False,62 auth: AuthTypes = None,63 allow_redirects: bool = True,64 cert: CertTypes = None,65 verify: VerifyTypes = True,66 timeout: TimeoutTypes = None,67) -> Response:68 return request(69 "GET",70 url,71 params=params,72 headers=headers,73 cookies=cookies,74 stream=stream,75 auth=auth,76 allow_redirects=allow_redirects,77 cert=cert,78 verify=verify,79 timeout=timeout,80 )818283def options(84 url: URLTypes,85 *,86 params: QueryParamTypes = None,87 headers: HeaderTypes = None,88 cookies: CookieTypes = None,89 stream: bool = False,90 auth: AuthTypes = None,91 allow_redirects: bool = True,92 cert: CertTypes = None,93 verify: VerifyTypes = True,94 timeout: TimeoutTypes = None,95) -> Response:96 return request(97 "OPTIONS",98 url,99 params=params,100 headers=headers,101 cookies=cookies,102 stream=stream,103 auth=auth,104 allow_redirects=allow_redirects,105 cert=cert,106 verify=verify,107 timeout=timeout,108 )109110111def head(112 url: URLTypes,113 *,114 params: QueryParamTypes = None,115 headers: HeaderTypes = None,116 cookies: CookieTypes = None,117 stream: bool = False,118 auth: AuthTypes = None,119 allow_redirects: bool = False, #  Note: Differs to usual default.120 cert: CertTypes = None,121 verify: VerifyTypes = True,122 timeout: TimeoutTypes = None,123) -> Response:124 return request(125 "HEAD",126 url,127 params=params,128 headers=headers,129 cookies=cookies,130 stream=stream,131 auth=auth,132 allow_redirects=allow_redirects,133 cert=cert,134 verify=verify,135 timeout=timeout,136 )137138139def post(140 url: URLTypes,141 *,142 data: RequestData = None,143 files: RequestFiles = None,144 json: typing.Any = None,145 params: QueryParamTypes = None,146 headers: HeaderTypes = None,147 cookies: CookieTypes = None,148 stream: bool = False,149 auth: AuthTypes = None,150 allow_redirects: bool = True,151 cert: CertTypes = None,152 verify: VerifyTypes = True,153 timeout: TimeoutTypes = None,154) -> Response:155 return request(156 "POST",157 url,158 data=data,159 files=files,160 json=json,161 params=params,162 headers=headers,163 cookies=cookies,164 stream=stream,165 auth=auth,166 allow_redirects=allow_redirects,167 cert=cert,168 verify=verify,169 timeout=timeout,170 )171172173def put(174 url: URLTypes,175 *,176 data: RequestData = None,177 files: RequestFiles = None,178 json: typing.Any = None,179 params: QueryParamTypes = None,180 headers: HeaderTypes = None,181 cookies: CookieTypes = None,182 stream: bool = False,183 auth: AuthTypes = None,184 allow_redirects: bool = True,185 cert: CertTypes = None,186 verify: VerifyTypes = True,187 timeout: TimeoutTypes = None,188) -> Response:189 return request(190 "PUT",191 url,192 data=data,193 files=files,194 json=json,195 params=params,196 headers=headers,197 cookies=cookies,198 stream=stream,199 auth=auth,200 allow_redirects=allow_redirects,201 cert=cert,202 verify=verify,203 timeout=timeout,204 )205206207def patch(208 url: URLTypes,209 *,210 data: RequestData = None,211 files: RequestFiles = None,212 json: typing.Any = None,213 params: QueryParamTypes = None,214 headers: HeaderTypes = None,215 cookies: CookieTypes = None,216 stream: bool = False,217 auth: AuthTypes = None,218 allow_redirects: bool = True,219 cert: CertTypes = None,220 verify: VerifyTypes = True,221 timeout: TimeoutTypes = None,222) -> Response:223 return request(224 "PATCH",225 url,226 data=data,227 files=files,228 json=json,229 params=params,230 headers=headers,231 cookies=cookies,232 stream=stream,233 auth=auth,234 allow_redirects=allow_redirects,235 cert=cert,236 verify=verify,237 timeout=timeout,238 )239240241def delete(242 url: URLTypes,243 *,244 data: RequestData = None,245 files: RequestFiles = None,246 json: typing.Any = None,247 params: QueryParamTypes = None,248 headers: HeaderTypes = None,249 cookies: CookieTypes = None,250 stream: bool = False,251 auth: AuthTypes = None,252 allow_redirects: bool = True,253 cert: CertTypes = None,254 verify: VerifyTypes = True,255 timeout: TimeoutTypes = None,256) -> Response:257 return request(258 "DELETE",259 url,260 data=data,261 files=files,262 json=json,263 params=params,264 headers=headers,265 cookies=cookies,266 stream=stream,267 auth=auth,268 allow_redirects=allow_redirects,269 cert=cert,270 verify=verify,271 timeout=timeout,272 )
added:httpx/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:httpx/client.py+895 added
1import inspect2import typing3from types import TracebackType45from .auth import HTTPBasicAuth6from .concurrency import AsyncioBackend7from .config import (8 DEFAULT_MAX_REDIRECTS,9 DEFAULT_POOL_LIMITS,10 DEFAULT_TIMEOUT_CONFIG,11 CertTypes,12 PoolLimits,13 TimeoutTypes,14 VerifyTypes,15)16from .dispatch.asgi import ASGIDispatch17from .dispatch.connection_pool import ConnectionPool18from .dispatch.threaded import ThreadedDispatcher19from .dispatch.wsgi import WSGIDispatch20from .exceptions import (21 InvalidURL,22 RedirectBodyUnavailable,23 RedirectLoop,24 TooManyRedirects,25)26from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher27from .models import (28 URL,29 AsyncRequest,30 AsyncRequestData,31 AsyncResponse,32 AsyncResponseContent,33 AuthTypes,34 Cookies,35 CookieTypes,36 Headers,37 HeaderTypes,38 QueryParamTypes,39 RequestData,40 RequestFiles,41 Response,42 ResponseContent,43 URLTypes,44)45from .status_codes import codes464748class BaseClient:49 def __init__(50 self,51 auth: AuthTypes = None,52 cookies: CookieTypes = None,53 verify: VerifyTypes = True,54 cert: CertTypes = None,55 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,56 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,57 max_redirects: int = DEFAULT_MAX_REDIRECTS,58 base_url: URLTypes = None,59 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,60 app: typing.Callable = None,61 raise_app_exceptions: bool = True,62 backend: ConcurrencyBackend = None,63 ):64 if backend is None:65 backend = AsyncioBackend()6667 if app is not None:68 param_count = len(inspect.signature(app).parameters)69 assert param_count in (2, 3)70 if param_count == 2:71 dispatch = WSGIDispatch(72 app=app, raise_app_exceptions=raise_app_exceptions73 )74 else:75 dispatch = ASGIDispatch(76 app=app, raise_app_exceptions=raise_app_exceptions77 )7879 if dispatch is None:80 async_dispatch = ConnectionPool(81 verify=verify,82 cert=cert,83 timeout=timeout,84 pool_limits=pool_limits,85 backend=backend,86 ) # type: AsyncDispatcher87 elif isinstance(dispatch, Dispatcher):88 async_dispatch = ThreadedDispatcher(dispatch, backend)89 else:90 async_dispatch = dispatch9192 if base_url is None:93 self.base_url = URL("", allow_relative=True)94 else:95 self.base_url = URL(base_url)9697 self.auth = auth98 self.cookies = Cookies(cookies)99 self.max_redirects = max_redirects100 self.dispatch = async_dispatch101 self.concurrency_backend = backend102103 def merge_cookies(104 self, cookies: CookieTypes = None105 ) -> typing.Optional[CookieTypes]:106 if cookies or self.cookies:107 merged_cookies = Cookies(self.cookies)108 merged_cookies.update(cookies)109 return merged_cookies110 return cookies111112 async def send(113 self,114 request: AsyncRequest,115 *,116 stream: bool = False,117 auth: AuthTypes = None,118 allow_redirects: bool = True,119 verify: VerifyTypes = None,120 cert: CertTypes = None,121 timeout: TimeoutTypes = None,122 ) -> AsyncResponse:123 if auth is None:124 auth = self.auth125126 url = request.url127128 if url.scheme not in ("http", "https"):129 raise InvalidURL('URL scheme must be "http" or "https".')130131 if auth is None and (url.username or url.password):132 auth = HTTPBasicAuth(username=url.username, password=url.password)133134 if auth is not None:135 if isinstance(auth, tuple):136 auth = HTTPBasicAuth(username=auth[0], password=auth[1])137 request = auth(request)138139 response = await self.send_handling_redirects(140 request,141 verify=verify,142 cert=cert,143 timeout=timeout,144 allow_redirects=allow_redirects,145 )146147 if not stream:148 try:149 await response.read()150 finally:151 await response.close()152153 return response154155 async def send_handling_redirects(156 self,157 request: AsyncRequest,158 *,159 cert: CertTypes = None,160 verify: VerifyTypes = None,161 timeout: TimeoutTypes = None,162 allow_redirects: bool = True,163 history: typing.List[AsyncResponse] = None,164 ) -> AsyncResponse:165 if history is None:166 history = []167168 while True:169 # We perform these checks here, so that calls to `response.next()`170 # will raise redirect errors if appropriate.171 if len(history) > self.max_redirects:172 raise TooManyRedirects()173 if request.url in [response.url for response in history]:174 raise RedirectLoop()175176 response = await self.dispatch.send(177 request, verify=verify, cert=cert, timeout=timeout178 )179 should_close_response = True180 try:181 assert isinstance(response, AsyncResponse)182 response.history = list(history)183 self.cookies.extract_cookies(response)184 history = history + [response]185186 if allow_redirects and response.is_redirect:187 request = self.build_redirect_request(request, response)188 else:189 should_close_response = False190 break191 finally:192 if should_close_response:193 await response.close()194195 if response.is_redirect:196197 async def send_next() -> AsyncResponse:198 nonlocal request, response, verify, cert199 nonlocal allow_redirects, timeout, history200 request = self.build_redirect_request(request, response)201 response = await self.send_handling_redirects(202 request,203 allow_redirects=allow_redirects,204 verify=verify,205 cert=cert,206 timeout=timeout,207 history=history,208 )209 return response210211 response.next = send_next # type: ignore212213 return response214215 def build_redirect_request(216 self, request: AsyncRequest, response: AsyncResponse217 ) -> AsyncRequest:218 method = self.redirect_method(request, response)219 url = self.redirect_url(request, response)220 headers = self.redirect_headers(request, url)221 content = self.redirect_content(request, method)222 cookies = self.merge_cookies(request.cookies)223 return AsyncRequest(224 method=method, url=url, headers=headers, data=content, cookies=cookies225 )226227 def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:228 """229 When being redirected we may want to change the method of the request230 based on certain specs or browser behavior.231 """232 method = request.method233234 # https://tools.ietf.org/html/rfc7231#section-6.4.4235 if response.status_code == codes.SEE_OTHER and method != "HEAD":236 method = "GET"237238 # Do what the browsers do, despite standards...239 # Turn 302s into GETs.240 if response.status_code == codes.FOUND and method != "HEAD":241 method = "GET"242243 # If a POST is responded to with a 301, turn it into a GET.244 # This bizarre behaviour is explained in 'requests' issue 1704.245 if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":246 method = "GET"247248 return method249250 def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:251 """252 Return the URL for the redirect to follow.253 """254 location = response.headers["Location"]255256 url = URL(location, allow_relative=True)257258 # Facilitate relative 'Location' headers, as allowed by RFC 7231.259 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')260 if url.is_relative_url:261 url = request.url.join(url)262263 # Attach previous fragment if needed (RFC 7231 7.1.2)264 if request.url.fragment and not url.fragment:265 url = url.copy_with(fragment=request.url.fragment)266267 return url268269 def redirect_headers(self, request: AsyncRequest, url: URL) -> Headers:270 """271 Strip Authorization headers when responses are redirected away from272 the origin.273 """274 headers = Headers(request.headers)275 if url.origin != request.url.origin:276 del headers["Authorization"]277 return headers278279 def redirect_content(self, request: AsyncRequest, method: str) -> bytes:280 """281 Return the body that should be used for the redirect request.282 """283 if method != request.method and method == "GET":284 return b""285 if request.is_streaming:286 raise RedirectBodyUnavailable()287 return request.content288289290class AsyncClient(BaseClient):291 async def get(292 self,293 url: URLTypes,294 *,295 params: QueryParamTypes = None,296 headers: HeaderTypes = None,297 cookies: CookieTypes = None,298 stream: bool = False,299 auth: AuthTypes = None,300 allow_redirects: bool = True,301 cert: CertTypes = None,302 verify: VerifyTypes = None,303 timeout: TimeoutTypes = None,304 ) -> AsyncResponse:305 return await self.request(306 "GET",307 url,308 params=params,309 headers=headers,310 cookies=cookies,311 stream=stream,312 auth=auth,313 allow_redirects=allow_redirects,314 verify=verify,315 cert=cert,316 timeout=timeout,317 )318319 async def options(320 self,321 url: URLTypes,322 *,323 params: QueryParamTypes = None,324 headers: HeaderTypes = None,325 cookies: CookieTypes = None,326 stream: bool = False,327 auth: AuthTypes = None,328 allow_redirects: bool = True,329 cert: CertTypes = None,330 verify: VerifyTypes = None,331 timeout: TimeoutTypes = None,332 ) -> AsyncResponse:333 return await self.request(334 "OPTIONS",335 url,336 params=params,337 headers=headers,338 cookies=cookies,339 stream=stream,340 auth=auth,341 allow_redirects=allow_redirects,342 verify=verify,343 cert=cert,344 timeout=timeout,345 )346347 async def head(348 self,349 url: URLTypes,350 *,351 params: QueryParamTypes = None,352 headers: HeaderTypes = None,353 cookies: CookieTypes = None,354 stream: bool = False,355 auth: AuthTypes = None,356 allow_redirects: bool = False, #  Note: Differs to usual default.357 cert: CertTypes = None,358 verify: VerifyTypes = None,359 timeout: TimeoutTypes = None,360 ) -> AsyncResponse:361 return await self.request(362 "HEAD",363 url,364 params=params,365 headers=headers,366 cookies=cookies,367 stream=stream,368 auth=auth,369 allow_redirects=allow_redirects,370 verify=verify,371 cert=cert,372 timeout=timeout,373 )374375 async def post(376 self,377 url: URLTypes,378 *,379 data: AsyncRequestData = None,380 files: RequestFiles = None,381 json: typing.Any = None,382 params: QueryParamTypes = None,383 headers: HeaderTypes = None,384 cookies: CookieTypes = None,385 stream: bool = False,386 auth: AuthTypes = None,387 allow_redirects: bool = True,388 cert: CertTypes = None,389 verify: VerifyTypes = None,390 timeout: TimeoutTypes = None,391 ) -> AsyncResponse:392 return await self.request(393 "POST",394 url,395 data=data,396 files=files,397 json=json,398 params=params,399 headers=headers,400 cookies=cookies,401 stream=stream,402 auth=auth,403 allow_redirects=allow_redirects,404 verify=verify,405 cert=cert,406 timeout=timeout,407 )408409 async def put(410 self,411 url: URLTypes,412 *,413 data: AsyncRequestData = None,414 files: RequestFiles = None,415 json: typing.Any = None,416 params: QueryParamTypes = None,417 headers: HeaderTypes = None,418 cookies: CookieTypes = None,419 stream: bool = False,420 auth: AuthTypes = None,421 allow_redirects: bool = True,422 cert: CertTypes = None,423 verify: VerifyTypes = None,424 timeout: TimeoutTypes = None,425 ) -> AsyncResponse:426 return await self.request(427 "PUT",428 url,429 data=data,430 files=files,431 json=json,432 params=params,433 headers=headers,434 cookies=cookies,435 stream=stream,436 auth=auth,437 allow_redirects=allow_redirects,438 verify=verify,439 cert=cert,440 timeout=timeout,441 )442443 async def patch(444 self,445 url: URLTypes,446 *,447 data: AsyncRequestData = None,448 files: RequestFiles = None,449 json: typing.Any = None,450 params: QueryParamTypes = None,451 headers: HeaderTypes = None,452 cookies: CookieTypes = None,453 stream: bool = False,454 auth: AuthTypes = None,455 allow_redirects: bool = True,456 cert: CertTypes = None,457 verify: VerifyTypes = None,458 timeout: TimeoutTypes = None,459 ) -> AsyncResponse:460 return await self.request(461 "PATCH",462 url,463 data=data,464 files=files,465 json=json,466 params=params,467 headers=headers,468 cookies=cookies,469 stream=stream,470 auth=auth,471 allow_redirects=allow_redirects,472 verify=verify,473 cert=cert,474 timeout=timeout,475 )476477 async def delete(478 self,479 url: URLTypes,480 *,481 data: AsyncRequestData = None,482 files: RequestFiles = None,483 json: typing.Any = None,484 params: QueryParamTypes = None,485 headers: HeaderTypes = None,486 cookies: CookieTypes = None,487 stream: bool = False,488 auth: AuthTypes = None,489 allow_redirects: bool = True,490 cert: CertTypes = None,491 verify: VerifyTypes = None,492 timeout: TimeoutTypes = None,493 ) -> AsyncResponse:494 return await self.request(495 "DELETE",496 url,497 data=data,498 files=files,499 json=json,500 params=params,501 headers=headers,502 cookies=cookies,503 stream=stream,504 auth=auth,505 allow_redirects=allow_redirects,506 verify=verify,507 cert=cert,508 timeout=timeout,509 )510511 async def request(512 self,513 method: str,514 url: URLTypes,515 *,516 data: AsyncRequestData = None,517 files: RequestFiles = None,518 json: typing.Any = None,519 params: QueryParamTypes = None,520 headers: HeaderTypes = None,521 cookies: CookieTypes = None,522 stream: bool = False,523 auth: AuthTypes = None,524 allow_redirects: bool = True,525 cert: CertTypes = None,526 verify: VerifyTypes = None,527 timeout: TimeoutTypes = None,528 ) -> AsyncResponse:529 url = self.base_url.join(url)530 cookies = self.merge_cookies(cookies)531 request = AsyncRequest(532 method,533 url,534 data=data,535 files=files,536 json=json,537 params=params,538 headers=headers,539 cookies=cookies,540 )541 response = await self.send(542 request,543 stream=stream,544 auth=auth,545 allow_redirects=allow_redirects,546 verify=verify,547 cert=cert,548 timeout=timeout,549 )550 return response551552 async def close(self) -> None:553 await self.dispatch.close()554555 async def __aenter__(self) -> "AsyncClient":556 return self557558 async def __aexit__(559 self,560 exc_type: typing.Type[BaseException] = None,561 exc_value: BaseException = None,562 traceback: TracebackType = None,563 ) -> None:564 await self.close()565566567class Client(BaseClient):568 def _async_request_data(569 self, data: RequestData = None570 ) -> typing.Optional[AsyncRequestData]:571 """572 If the request data is an bytes iterator then return an async bytes573 iterator onto the request data.574 """575 if data is None or isinstance(data, (str, bytes, dict)):576 return data577578 # Coerce an iterator into an async iterator, with each item in the579 # iteration running as a thread-pooled operation.580 assert hasattr(data, "__iter__")581 return self.concurrency_backend.iterate_in_threadpool(data)582583 def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:584 if isinstance(data, bytes):585 return data586587 # Coerce an async iterator into an iterator, with each item in the588 # iteration run within the event loop.589 assert hasattr(data, "__aiter__")590 return self.concurrency_backend.iterate(data)591592 def request(593 self,594 method: str,595 url: URLTypes,596 *,597 data: RequestData = None,598 files: RequestFiles = None,599 json: typing.Any = None,600 params: QueryParamTypes = None,601 headers: HeaderTypes = None,602 cookies: CookieTypes = None,603 stream: bool = False,604 auth: AuthTypes = None,605 allow_redirects: bool = True,606 cert: CertTypes = None,607 verify: VerifyTypes = None,608 timeout: TimeoutTypes = None,609 ) -> Response:610 url = self.base_url.join(url)611 cookies = self.merge_cookies(cookies)612 request = AsyncRequest(613 method,614 url,615 data=self._async_request_data(data),616 files=files,617 json=json,618 params=params,619 headers=headers,620 cookies=cookies,621 )622 concurrency_backend = self.concurrency_backend623624 coroutine = self.send625 args = [request]626 kwargs = dict(627 stream=True,628 auth=auth,629 allow_redirects=allow_redirects,630 verify=verify,631 cert=cert,632 timeout=timeout,633 )634 async_response = concurrency_backend.run(coroutine, *args, **kwargs)635636 content = getattr(637 async_response, "_raw_content", getattr(async_response, "_raw_stream", None)638 )639640 sync_content = self._sync_data(content)641642 def sync_on_close() -> None:643 nonlocal concurrency_backend, async_response644 concurrency_backend.run(async_response.on_close)645646 response = Response(647 status_code=async_response.status_code,648 protocol=async_response.protocol,649 headers=async_response.headers,650 content=sync_content,651 on_close=sync_on_close,652 request=async_response.request,653 history=async_response.history,654 )655 if not stream:656 try:657 response.read()658 finally:659 response.close()660 return response661662 def get(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 = True,672 cert: CertTypes = None,673 verify: VerifyTypes = None,674 timeout: TimeoutTypes = None,675 ) -> Response:676 return self.request(677 "GET",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 options(691 self,692 url: URLTypes,693 *,694 params: QueryParamTypes = None,695 headers: HeaderTypes = None,696 cookies: CookieTypes = None,697 stream: bool = False,698 auth: AuthTypes = None,699 allow_redirects: bool = True,700 cert: CertTypes = None,701 verify: VerifyTypes = None,702 timeout: TimeoutTypes = None,703 ) -> Response:704 return self.request(705 "OPTIONS",706 url,707 params=params,708 headers=headers,709 cookies=cookies,710 stream=stream,711 auth=auth,712 allow_redirects=allow_redirects,713 verify=verify,714 cert=cert,715 timeout=timeout,716 )717718 def head(719 self,720 url: URLTypes,721 *,722 params: QueryParamTypes = None,723 headers: HeaderTypes = None,724 cookies: CookieTypes = None,725 stream: bool = False,726 auth: AuthTypes = None,727 allow_redirects: bool = False, #  Note: Differs to usual default.728 cert: CertTypes = None,729 verify: VerifyTypes = None,730 timeout: TimeoutTypes = None,731 ) -> Response:732 return self.request(733 "HEAD",734 url,735 params=params,736 headers=headers,737 cookies=cookies,738 stream=stream,739 auth=auth,740 allow_redirects=allow_redirects,741 verify=verify,742 cert=cert,743 timeout=timeout,744 )745746 def post(747 self,748 url: URLTypes,749 *,750 data: RequestData = None,751 files: RequestFiles = None,752 json: typing.Any = None,753 params: QueryParamTypes = None,754 headers: HeaderTypes = None,755 cookies: CookieTypes = None,756 stream: bool = False,757 auth: AuthTypes = None,758 allow_redirects: bool = True,759 cert: CertTypes = None,760 verify: VerifyTypes = None,761 timeout: TimeoutTypes = None,762 ) -> Response:763 return self.request(764 "POST",765 url,766 data=data,767 files=files,768 json=json,769 params=params,770 headers=headers,771 cookies=cookies,772 stream=stream,773 auth=auth,774 allow_redirects=allow_redirects,775 verify=verify,776 cert=cert,777 timeout=timeout,778 )779780 def put(781 self,782 url: URLTypes,783 *,784 data: RequestData = None,785 files: RequestFiles = None,786 json: typing.Any = None,787 params: QueryParamTypes = None,788 headers: HeaderTypes = None,789 cookies: CookieTypes = None,790 stream: bool = False,791 auth: AuthTypes = None,792 allow_redirects: bool = True,793 cert: CertTypes = None,794 verify: VerifyTypes = None,795 timeout: TimeoutTypes = None,796 ) -> Response:797 return self.request(798 "PUT",799 url,800 data=data,801 files=files,802 json=json,803 params=params,804 headers=headers,805 cookies=cookies,806 stream=stream,807 auth=auth,808 allow_redirects=allow_redirects,809 verify=verify,810 cert=cert,811 timeout=timeout,812 )813814 def patch(815 self,816 url: URLTypes,817 *,818 data: RequestData = None,819 files: RequestFiles = None,820 json: typing.Any = None,821 params: QueryParamTypes = None,822 headers: HeaderTypes = None,823 cookies: CookieTypes = None,824 stream: bool = False,825 auth: AuthTypes = None,826 allow_redirects: bool = True,827 cert: CertTypes = None,828 verify: VerifyTypes = None,829 timeout: TimeoutTypes = None,830 ) -> Response:831 return self.request(832 "PATCH",833 url,834 data=data,835 files=files,836 json=json,837 params=params,838 headers=headers,839 cookies=cookies,840 stream=stream,841 auth=auth,842 allow_redirects=allow_redirects,843 verify=verify,844 cert=cert,845 timeout=timeout,846 )847848 def delete(849 self,850 url: URLTypes,851 *,852 data: RequestData = None,853 files: RequestFiles = None,854 json: typing.Any = None,855 params: QueryParamTypes = None,856 headers: HeaderTypes = None,857 cookies: CookieTypes = None,858 stream: bool = False,859 auth: AuthTypes = None,860 allow_redirects: bool = True,861 cert: CertTypes = None,862 verify: VerifyTypes = None,863 timeout: TimeoutTypes = None,864 ) -> Response:865 return self.request(866 "DELETE",867 url,868 data=data,869 files=files,870 json=json,871 params=params,872 headers=headers,873 cookies=cookies,874 stream=stream,875 auth=auth,876 allow_redirects=allow_redirects,877 verify=verify,878 cert=cert,879 timeout=timeout,880 )881882 def close(self) -> None:883 coroutine = self.dispatch.close884 self.concurrency_backend.run(coroutine)885886 def __enter__(self) -> "Client":887 return self888889 def __exit__(890 self,891 exc_type: typing.Type[BaseException] = None,892 exc_value: BaseException = None,893 traceback: TracebackType = None,894 ) -> None:895 self.close()
added:httpx/concurrency.py+271 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 typing15from types import TracebackType1617from .config import PoolLimits, TimeoutConfig18from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19from .interfaces import (20 BaseBackgroundManager,21 BasePoolSemaphore,22 BaseReader,23 BaseWriter,24 ConcurrencyBackend,25 Protocol,26)2728SSL_MONKEY_PATCH_APPLIED = False293031def ssl_monkey_patch() -> None:32 """33 Monky-patch for https://bugs.python.org/issue367093435 This prevents console errors when outstanding HTTPS connections36 still exist at the point of exiting.3738 Clients which have been opened using a `with` block, or which have39 had `close()` closed, will not exhibit this issue in the first place.40 """41 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignore4243 _write = MonkeyPatch.write4445 def _fixed_write(self, data: bytes) -> None: # type: ignore46 if self._loop and not self._loop.is_closed():47 _write(self, data)4849 MonkeyPatch.write = _fixed_write505152class TimeoutFlag:53 """54 A timeout flag holds a state of either read-timeout or write-timeout mode.5556 We use this so that we can attempt both reads and writes concurrently, while57 only enforcing timeouts in one direction.5859 During a request/response cycle we start in write-timeout mode.6061 Once we've sent a request fully, or once we start seeing a response,62 then we switch to read-timeout mode instead.63 """6465 def __init__(self) -> None:66 self.raise_on_read_timeout = False67 self.raise_on_write_timeout = True6869 def set_read_timeouts(self) -> None:70 """71 Set the flag to read-timeout mode.72 """73 self.raise_on_read_timeout = True74 self.raise_on_write_timeout = False7576 def set_write_timeouts(self) -> None:77 """78 Set the flag to write-timeout mode.79 """80 self.raise_on_read_timeout = False81 self.raise_on_write_timeout = True828384class Reader(BaseReader):85 def __init__(86 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87 ) -> None:88 self.stream_reader = stream_reader89 self.timeout = timeout9091 async def read(92 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93 ) -> bytes:94 if timeout is None:95 timeout = self.timeout9697 while True:98 # Check our flag at the first possible moment, and use a fine99 # grained retry loop if we're not yet in read-timeout mode.100 should_raise = flag is None or flag.raise_on_read_timeout101 read_timeout = timeout.read_timeout if should_raise else 0.01102 try:103 data = await asyncio.wait_for(self.stream_reader.read(n), read_timeout)104 break105 except asyncio.TimeoutError:106 if should_raise:107 raise ReadTimeout() from None108109 return data110111112class Writer(BaseWriter):113 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):114 self.stream_writer = stream_writer115 self.timeout = timeout116117 def write_no_block(self, data: bytes) -> None:118 self.stream_writer.write(data) # pragma: nocover119120 async def write(121 self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None122 ) -> None:123 if not data:124 return125126 if timeout is None:127 timeout = self.timeout128129 self.stream_writer.write(data)130 while True:131 try:132 await asyncio.wait_for( # type: ignore133 self.stream_writer.drain(), timeout.write_timeout134 )135 break136 except asyncio.TimeoutError:137 # We check our flag at the possible moment, in order to138 # allow us to suppress write timeouts, if we've since139 # switched over to read-timeout mode.140 should_raise = flag is None or flag.raise_on_write_timeout141 if should_raise:142 raise WriteTimeout() from None143144 async def close(self) -> None:145 self.stream_writer.close()146147148class PoolSemaphore(BasePoolSemaphore):149 def __init__(self, pool_limits: PoolLimits):150 self.pool_limits = pool_limits151152 @property153 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:154 if not hasattr(self, "_semaphore"):155 max_connections = self.pool_limits.hard_limit156 if max_connections is None:157 self._semaphore = None158 else:159 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)160 return self._semaphore161162 async def acquire(self) -> None:163 if self.semaphore is None:164 return165166 timeout = self.pool_limits.pool_timeout167 try:168 await asyncio.wait_for(self.semaphore.acquire(), timeout)169 except asyncio.TimeoutError:170 raise PoolTimeout()171172 def release(self) -> None:173 if self.semaphore is None:174 return175176 self.semaphore.release()177178179class AsyncioBackend(ConcurrencyBackend):180 def __init__(self) -> None:181 global SSL_MONKEY_PATCH_APPLIED182183 if not SSL_MONKEY_PATCH_APPLIED:184 ssl_monkey_patch()185 SSL_MONKEY_PATCH_APPLIED = True186187 @property188 def loop(self) -> asyncio.AbstractEventLoop:189 if not hasattr(self, "_loop"):190 try:191 self._loop = asyncio.get_event_loop()192 except RuntimeError:193 self._loop = asyncio.new_event_loop()194 return self._loop195196 async def connect(197 self,198 hostname: str,199 port: int,200 ssl_context: typing.Optional[ssl.SSLContext],201 timeout: TimeoutConfig,202 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:203 try:204 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore205 asyncio.open_connection(hostname, port, ssl=ssl_context),206 timeout.connect_timeout,207 )208 except asyncio.TimeoutError:209 raise ConnectTimeout()210211 ssl_object = stream_writer.get_extra_info("ssl_object")212 if ssl_object is None:213 ident = "http/1.1"214 else:215 ident = ssl_object.selected_alpn_protocol()216 if ident is None:217 ident = ssl_object.selected_npn_protocol()218219 reader = Reader(stream_reader=stream_reader, timeout=timeout)220 writer = Writer(stream_writer=stream_writer, timeout=timeout)221 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11222223 return (reader, writer, protocol)224225 async def run_in_threadpool(226 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any227 ) -> typing.Any:228 if kwargs:229 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here230 func = functools.partial(func, **kwargs)231 return await self.loop.run_in_executor(None, func, *args)232233 def run(234 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any235 ) -> typing.Any:236 loop = self.loop237 if loop.is_running():238 self._loop = asyncio.new_event_loop()239 try:240 return self.loop.run_until_complete(coroutine(*args, **kwargs))241 finally:242 self._loop = loop243244 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:245 return PoolSemaphore(limits)246247 def background_manager(248 self, coroutine: typing.Callable, args: typing.Any249 ) -> "BackgroundManager":250 return BackgroundManager(coroutine, args)251252253class BackgroundManager(BaseBackgroundManager):254 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:255 self.coroutine = coroutine256 self.args = args257258 async def __aenter__(self) -> "BackgroundManager":259 loop = asyncio.get_event_loop()260 self.task = loop.create_task(self.coroutine(*self.args))261 return self262263 async def __aexit__(264 self,265 exc_type: typing.Type[BaseException] = None,266 exc_value: BaseException = None,267 traceback: TracebackType = None,268 ) -> None:269 await self.task270 if exc_type is None:271 self.task.result()
added:httpx/config.py+250 added
1import asyncio2import os3import ssl4import typing56import certifi78from .__version__ import __version__910CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11VerifyTypes = typing.Union[str, bool]12TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]131415USER_AGENT = f"python-httpx/{__version__}"1617DEFAULT_CIPHERS = ":".join(18 [19 "ECDHE+AESGCM",20 "ECDHE+CHACHA20",21 "DHE+AESGCM",22 "DHE+CHACHA20",23 "ECDH+AESGCM",24 "DH+AESGCM",25 "ECDH+AES",26 "DH+AES",27 "RSA+AESGCM",28 "RSA+AES",29 "!aNULL",30 "!eNULL",31 "!MD5",32 "!DSS",33 ]34)353637class SSLConfig:38 """39 SSL Configuration.40 """4142 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43 self.cert = cert44 self.verify = verify4546 self.ssl_context: typing.Optional[ssl.SSLContext] = None4748 def __eq__(self, other: typing.Any) -> bool:49 return (50 isinstance(other, self.__class__)51 and self.cert == other.cert52 and self.verify == other.verify53 )5455 def __repr__(self) -> str:56 class_name = self.__class__.__name__57 return f"{class_name}(cert={self.cert}, verify={self.verify})"5859 def with_overrides(60 self, cert: CertTypes = None, verify: VerifyTypes = None61 ) -> "SSLConfig":62 cert = self.cert if cert is None else cert63 verify = self.verify if verify is None else verify64 if (cert == self.cert) and (verify == self.verify):65 return self66 return SSLConfig(cert=cert, verify=verify)6768 async def load_ssl_context(self) -> ssl.SSLContext:69 if self.ssl_context is None:70 if not self.verify:71 self.ssl_context = self.load_ssl_context_no_verify()72 else:73 # Run the SSL loading in a threadpool, since it makes disk accesses.74 loop = asyncio.get_event_loop()75 self.ssl_context = await loop.run_in_executor(76 None, self.load_ssl_context_verify77 )7879 assert self.ssl_context is not None80 return self.ssl_context8182 def load_ssl_context_no_verify(self) -> ssl.SSLContext:83 """84 Return an SSL context for unverified connections.85 """86 context = self._create_default_ssl_context()87 context.verify_mode = ssl.CERT_NONE88 context.check_hostname = False89 return context9091 def load_ssl_context_verify(self) -> ssl.SSLContext:92 """93 Return an SSL context for verified connections.94 """95 if isinstance(self.verify, bool):96 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH97 elif os.path.exists(self.verify):98 ca_bundle_path = self.verify99 else:100 raise IOError(101 "Could not find a suitable TLS CA certificate bundle, "102 "invalid path: {}".format(self.verify)103 )104105 context = self._create_default_ssl_context()106 context.verify_mode = ssl.CERT_REQUIRED107 context.check_hostname = True108109 # Signal to server support for PHA in TLS 1.3. Raises an110 # AttributeError if only read-only access is implemented.111 try:112 context.post_handshake_auth = True # type: ignore113 except AttributeError: # pragma: nocover114 pass115116 # Disable using 'commonName' for SSLContext.check_hostname117 # when the 'subjectAltName' extension isn't available.118 try:119 context.hostname_checks_common_name = False # type: ignore120 except AttributeError: # pragma: nocover121 pass122123 if os.path.isfile(ca_bundle_path):124 context.load_verify_locations(cafile=ca_bundle_path)125 elif os.path.isdir(ca_bundle_path):126 context.load_verify_locations(capath=ca_bundle_path)127128 if self.cert is not None:129 if isinstance(self.cert, str):130 context.load_cert_chain(certfile=self.cert)131 elif isinstance(self.cert, tuple) and len(self.cert) == 2:132 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])133 elif isinstance(self.cert, tuple) and len(self.cert) == 3:134 context.load_cert_chain(135 certfile=self.cert[0],136 keyfile=self.cert[1],137 password=self.cert[2], # type: ignore138 )139140 return context141142 def _create_default_ssl_context(self) -> ssl.SSLContext:143 """144 Creates the default SSLContext object that's used for both verified145 and unverified connections.146 """147 context = ssl.SSLContext(ssl.PROTOCOL_TLS)148 context.options |= ssl.OP_NO_SSLv2149 context.options |= ssl.OP_NO_SSLv3150 context.options |= ssl.OP_NO_COMPRESSION151 context.set_ciphers(DEFAULT_CIPHERS)152153 if ssl.HAS_ALPN:154 context.set_alpn_protocols(["h2", "http/1.1"])155 if ssl.HAS_NPN:156 context.set_npn_protocols(["h2", "http/1.1"])157158 return context159160161class TimeoutConfig:162 """163 Timeout values.164 """165166 def __init__(167 self,168 timeout: TimeoutTypes = None,169 *,170 connect_timeout: float = None,171 read_timeout: float = None,172 write_timeout: float = None,173 ):174 if timeout is None:175 self.connect_timeout = connect_timeout176 self.read_timeout = read_timeout177 self.write_timeout = write_timeout178 else:179 # Specified as a single timeout value180 assert connect_timeout is None181 assert read_timeout is None182 assert write_timeout is None183 if isinstance(timeout, TimeoutConfig):184 self.connect_timeout = timeout.connect_timeout185 self.read_timeout = timeout.read_timeout186 self.write_timeout = timeout.write_timeout187 elif isinstance(timeout, tuple):188 self.connect_timeout = timeout[0]189 self.read_timeout = timeout[1]190 self.write_timeout = timeout[2]191 else:192 self.connect_timeout = timeout193 self.read_timeout = timeout194 self.write_timeout = timeout195196 def __eq__(self, other: typing.Any) -> bool:197 return (198 isinstance(other, self.__class__)199 and self.connect_timeout == other.connect_timeout200 and self.read_timeout == other.read_timeout201 and self.write_timeout == other.write_timeout202 )203204 def __repr__(self) -> str:205 class_name = self.__class__.__name__206 if len({self.connect_timeout, self.read_timeout, self.write_timeout}) == 1:207 return f"{class_name}(timeout={self.connect_timeout})"208 return (209 f"{class_name}(connect_timeout={self.connect_timeout}, "210 f"read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"211 )212213214class PoolLimits:215 """216 Limits on the number of connections in a connection pool.217 """218219 def __init__(220 self,221 *,222 soft_limit: int = None,223 hard_limit: int = None,224 pool_timeout: float = None,225 ):226 self.soft_limit = soft_limit227 self.hard_limit = hard_limit228 self.pool_timeout = pool_timeout229230 def __eq__(self, other: typing.Any) -> bool:231 return (232 isinstance(other, self.__class__)233 and self.soft_limit == other.soft_limit234 and self.hard_limit == other.hard_limit235 and self.pool_timeout == other.pool_timeout236 )237238 def __repr__(self) -> str:239 class_name = self.__class__.__name__240 return (241 f"{class_name}(soft_limit={self.soft_limit}, "242 f"hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"243 )244245246DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)247DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)248DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)249DEFAULT_CA_BUNDLE_PATH = certifi.where()250DEFAULT_MAX_REDIRECTS = 20
added:httpx/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 "gzip": GZipDecoder,138 "deflate": DeflateDecoder,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:httpx/exceptions.py+135 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 NotConnected(Exception):38 """39 A connection was lost at the point of starting a request,40 prior to any writes succeeding.41 """424344class HttpError(Exception):45 """46 An HTTP error occurred.47 """484950class ProtocolError(Exception):51 """52 Malformed HTTP.53 """545556class DecodingError(Exception):57 """58 Decoding of the response failed.59 """606162# Redirect exceptions...636465class RedirectError(Exception):66 """67 Base class for HTTP redirect errors.68 """697071class TooManyRedirects(RedirectError):72 """73 Too many redirects.74 """757677class RedirectBodyUnavailable(RedirectError):78 """79 Got a redirect response, but the request body was streaming, and is80 no longer available.81 """828384class RedirectLoop(RedirectError):85 """86 Infinite redirect loop.87 """888990# Stream exceptions...919293class StreamException(Exception):94 """95 The base class for stream exceptions.9697 The developer made an error in accessing the request stream in98 an invalid way.99 """100101102class StreamConsumed(StreamException):103 """104 Attempted to read or stream response content, but the content has already105 been streamed.106 """107108109class ResponseNotRead(StreamException):110 """111 Attempted to access response content, without having called `read()`112 after a streaming response.113 """114115116class ResponseClosed(StreamException):117 """118 Attempted to read or stream response content, but the request has been119 closed.120 """121122123# Other cases...124125126class InvalidURL(Exception):127 """128 URL was missing a hostname, or was not one of HTTP/HTTPS.129 """130131132class CookieConflict(Exception):133 """134 Attempted to lookup a cookie by name, but multiple cookies existed.135 """
added:httpx/interfaces.py+227 added
1import enum2import ssl3import typing4from types import TracebackType56from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7from .models import (8 AsyncRequest,9 AsyncRequestData,10 AsyncResponse,11 HeaderTypes,12 QueryParamTypes,13 Request,14 RequestData,15 Response,16 URLTypes,17)181920class Protocol(str, enum.Enum):21 HTTP_11 = "HTTP/1.1"22 HTTP_2 = "HTTP/2"232425class AsyncDispatcher:26 """27 Base class for async dispatcher classes, that handle sending the request.2829 Stubs out the interface, as well as providing a `.request()` convienence30 implementation, to make it easy to use or test stand-alone dispatchers,31 without requiring a complete `Client` instance.32 """3334 async def request(35 self,36 method: str,37 url: URLTypes,38 *,39 data: AsyncRequestData = b"",40 params: QueryParamTypes = None,41 headers: HeaderTypes = None,42 verify: VerifyTypes = None,43 cert: CertTypes = None,44 timeout: TimeoutTypes = None45 ) -> AsyncResponse:46 request = AsyncRequest(method, url, data=data, params=params, headers=headers)47 return await self.send(request, verify=verify, cert=cert, timeout=timeout)4849 async def send(50 self,51 request: AsyncRequest,52 verify: VerifyTypes = None,53 cert: CertTypes = None,54 timeout: TimeoutTypes = None,55 ) -> AsyncResponse:56 raise NotImplementedError() # pragma: nocover5758 async def close(self) -> None:59 pass # pragma: nocover6061 async def __aenter__(self) -> "AsyncDispatcher":62 return self6364 async def __aexit__(65 self,66 exc_type: typing.Type[BaseException] = None,67 exc_value: BaseException = None,68 traceback: TracebackType = None,69 ) -> None:70 await self.close()717273class Dispatcher:74 """75 Base class for syncronous dispatcher classes, that handle sending the request.7677 Stubs out the interface, as well as providing a `.request()` convienence78 implementation, to make it easy to use or test stand-alone dispatchers,79 without requiring a complete `Client` instance.80 """8182 def request(83 self,84 method: str,85 url: URLTypes,86 *,87 data: RequestData = b"",88 params: QueryParamTypes = None,89 headers: HeaderTypes = None,90 verify: VerifyTypes = None,91 cert: CertTypes = None,92 timeout: TimeoutTypes = None93 ) -> Response:94 request = Request(method, url, data=data, params=params, headers=headers)95 return self.send(request, verify=verify, cert=cert, timeout=timeout)9697 def send(98 self,99 request: Request,100 verify: VerifyTypes = None,101 cert: CertTypes = None,102 timeout: TimeoutTypes = None,103 ) -> Response:104 raise NotImplementedError() # pragma: nocover105106 def close(self) -> None:107 pass # pragma: nocover108109 def __enter__(self) -> "Dispatcher":110 return self111112 def __exit__(113 self,114 exc_type: typing.Type[BaseException] = None,115 exc_value: BaseException = None,116 traceback: TracebackType = None,117 ) -> None:118 self.close()119120121class BaseReader:122 """123 A stream reader. Abstracts away any asyncio-specfic interfaces124 into a more generic base class, that we can use with alternate125 backend, or for stand-alone test cases.126 """127128 async def read(129 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None130 ) -> 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 break210211 def background_manager(212 self, coroutine: typing.Callable, args: typing.Any213 ) -> "BaseBackgroundManager":214 raise NotImplementedError() # pragma: no cover215216217class BaseBackgroundManager:218 async def __aenter__(self) -> "BaseBackgroundManager":219 raise NotImplementedError() # pragma: no cover220221 async def __aexit__(222 self,223 exc_type: typing.Type[BaseException] = None,224 exc_value: BaseException = None,225 traceback: TracebackType = None,226 ) -> None:227 raise NotImplementedError() # pragma: no cover
added:httpx/models.py+1168 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 .config import USER_AGENT14from .decoders import (15 ACCEPT_ENCODING,16 SUPPORTED_DECODERS,17 Decoder,18 IdentityDecoder,19 MultiDecoder,20)21from .exceptions import (22 CookieConflict,23 HttpError,24 InvalidURL,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,28)29from .multipart import multipart_encode30from .status_codes import StatusCode31from .utils import (32 guess_json_utf,33 is_known_encoding,34 normalize_header_key,35 normalize_header_value,36)3738URLTypes = typing.Union["URL", str]3940QueryParamTypes = typing.Union[41 "QueryParams",42 typing.Mapping[str, str],43 typing.List[typing.Tuple[typing.Any, typing.Any]],44 str,45]4647HeaderTypes = typing.Union[48 "Headers",49 typing.Dict[typing.AnyStr, typing.AnyStr],50 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],51]5253CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]5455AuthTypes = typing.Union[56 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],57 typing.Callable[["AsyncRequest"], "AsyncRequest"],58]5960AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]6162RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]6364RequestFiles = typing.Dict[65 str,66 typing.Union[67 typing.IO[typing.AnyStr], # file68 typing.Tuple[str, typing.IO[typing.AnyStr]], # (filename, file)69 typing.Tuple[70 str, typing.IO[typing.AnyStr], str71 ], # (filename, file, content_type)72 ],73]7475AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]7677ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]787980class URL:81 def __init__(82 self,83 url: URLTypes,84 allow_relative: bool = False,85 params: QueryParamTypes = None,86 ) -> None:87 if isinstance(url, rfc3986.uri.URIReference):88 self.components = url89 elif isinstance(url, str):90 self.components = rfc3986.api.uri_reference(url)91 else:92 self.components = url.components9394 # Handle IDNA domain names.95 if self.components.authority:96 idna_authority = self.components.authority.encode("idna").decode("ascii")97 if idna_authority != self.components.authority:98 self.components = self.components.copy_with(authority=idna_authority)99100 # Normalize scheme and domain name.101 self.components = self.components.normalize()102103 # Add any query parameters.104 if params:105 query_string = str(QueryParams(params))106 self.components = self.components.copy_with(query=query_string)107108 # Enforce absolute URLs by default.109 if not allow_relative:110 if not self.scheme:111 raise InvalidURL("No scheme included in URL.")112 if not self.host:113 raise InvalidURL("No host included in URL.")114115 @property116 def scheme(self) -> str:117 return self.components.scheme or ""118119 @property120 def authority(self) -> str:121 return self.components.authority or ""122123 @property124 def username(self) -> str:125 userinfo = self.components.userinfo or ""126 return userinfo.partition(":")[0]127128 @property129 def password(self) -> str:130 userinfo = self.components.userinfo or ""131 return userinfo.partition(":")[2]132133 @property134 def host(self) -> str:135 return self.components.host or ""136137 @property138 def port(self) -> int:139 port = self.components.port140 if port is None:141 return {"https": 443, "http": 80}[self.scheme]142 return int(port)143144 @property145 def path(self) -> str:146 return self.components.path or "/"147148 @property149 def query(self) -> str:150 return self.components.query or ""151152 @property153 def full_path(self) -> str:154 path = self.path155 if self.query:156 path += "?" + self.query157 return path158159 @property160 def fragment(self) -> str:161 return self.components.fragment or ""162163 @property164 def is_ssl(self) -> bool:165 return self.components.scheme == "https"166167 @property168 def is_absolute_url(self) -> bool:169 """170 Return `True` for absolute URLs such as 'http://example.com/path',171 and `False` for relative URLs such as '/path'.172 """173 # We don't use rfc3986's `is_absolute` because it treats174 # URLs with a fragment portion as not absolute.175 # What we actually care about is if the URL provides176 # a scheme and hostname to which connections should be made.177 return self.components.scheme and self.components.host178179 @property180 def is_relative_url(self) -> bool:181 return not self.is_absolute_url182183 @property184 def origin(self) -> "Origin":185 return Origin(self)186187 def copy_with(self, **kwargs: typing.Any) -> "URL":188 return URL(self.components.copy_with(**kwargs))189190 def join(self, relative_url: URLTypes) -> "URL":191 """192 Return an absolute URL, using given this URL as the base.193 """194 if self.is_relative_url:195 return URL(relative_url)196197 # We drop any fragment portion, because RFC 3986 strictly198 # treats URLs with a fragment portion as not being absolute URLs.199 base_components = self.components.copy_with(fragment=None)200 relative_url = URL(relative_url, allow_relative=True)201 return URL(relative_url.components.resolve_with(base_components))202203 def __hash__(self) -> int:204 return hash(str(self))205206 def __eq__(self, other: typing.Any) -> bool:207 return isinstance(other, URL) and str(self) == str(other)208209 def __str__(self) -> str:210 return self.components.unsplit()211212 def __repr__(self) -> str:213 class_name = self.__class__.__name__214 url_str = str(self)215 return f"{class_name}({url_str!r})"216217218class Origin:219 """220 The URL scheme and authority information, as a comparable, hashable object.221 """222223 def __init__(self, url: URLTypes) -> None:224 if not isinstance(url, URL):225 url = URL(url)226 self.is_ssl = url.is_ssl227 self.host = url.host228 self.port = url.port229230 def __eq__(self, other: typing.Any) -> bool:231 return (232 isinstance(other, self.__class__)233 and self.is_ssl == other.is_ssl234 and self.host == other.host235 and self.port == other.port236 )237238 def __hash__(self) -> int:239 return hash((self.is_ssl, self.host, self.port))240241242class QueryParams(typing.Mapping[str, str]):243 """244 URL query parameters, as a multi-dict.245 """246247 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:248 assert len(args) < 2, "Too many arguments."249 assert not (args and kwargs), "Cannot mix named and unnamed arguments."250251 value = args[0] if args else kwargs252253 if isinstance(value, str):254 items = parse_qsl(value)255 elif isinstance(value, QueryParams):256 items = value.multi_items()257 elif isinstance(value, list):258 items = value259 else:260 items = value.items() # type: ignore261262 self._list = [(str(k), str(v)) for k, v in items]263 self._dict = {str(k): str(v) for k, v in items}264265 def getlist(self, key: typing.Any) -> typing.List[str]:266 return [item_value for item_key, item_value in self._list if item_key == key]267268 def keys(self) -> typing.KeysView:269 return self._dict.keys()270271 def values(self) -> typing.ValuesView:272 return self._dict.values()273274 def items(self) -> typing.ItemsView:275 return self._dict.items()276277 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:278 return list(self._list)279280 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:281 if key in self._dict:282 return self._dict[key]283 return default284285 def __getitem__(self, key: typing.Any) -> str:286 return self._dict[key]287288 def __contains__(self, key: typing.Any) -> bool:289 return key in self._dict290291 def __iter__(self) -> typing.Iterator[typing.Any]:292 return iter(self.keys())293294 def __len__(self) -> int:295 return len(self._dict)296297 def __eq__(self, other: typing.Any) -> bool:298 if not isinstance(other, self.__class__):299 return False300 return sorted(self._list) == sorted(other._list)301302 def __str__(self) -> str:303 return urlencode(self._list)304305 def __repr__(self) -> str:306 class_name = self.__class__.__name__307 query_string = str(self)308 return f"{class_name}({query_string!r})"309310311class Headers(typing.MutableMapping[str, str]):312 """313 HTTP headers, as a case-insensitive multi-dict.314 """315316 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:317 if headers is None:318 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]319 elif isinstance(headers, Headers):320 self._list = list(headers.raw)321 elif isinstance(headers, dict):322 self._list = [323 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))324 for k, v in headers.items()325 ]326 else:327 self._list = [328 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))329 for k, v in headers330 ]331 self._encoding = encoding332333 @property334 def encoding(self) -> str:335 """336 Header encoding is mandated as ascii, but we allow fallbacks to utf-8337 or iso-8859-1.338 """339 if self._encoding is None:340 for encoding in ["ascii", "utf-8"]:341 for key, value in self.raw:342 try:343 key.decode(encoding)344 value.decode(encoding)345 except UnicodeDecodeError:346 break347 else:348 # The else block runs if 'break' did not occur, meaning349 # all values fitted the encoding.350 self._encoding = encoding351 break352 else:353 # The ISO-8859-1 encoding covers all 256 code points in a byte,354 # so will never raise decode errors.355 self._encoding = "iso-8859-1"356 return self._encoding357358 @encoding.setter359 def encoding(self, value: str) -> None:360 self._encoding = value361362 @property363 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:364 """365 Returns a list of the raw header items, as byte pairs.366 May be mutated in-place.367 """368 return self._list369370 def keys(self) -> typing.List[str]: # type: ignore371 return [key.decode(self.encoding) for key, value in self._list]372373 def values(self) -> typing.List[str]: # type: ignore374 return [value.decode(self.encoding) for key, value in self._list]375376 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore377 return [378 (key.decode(self.encoding), value.decode(self.encoding))379 for key, value in self._list380 ]381382 def get(self, key: str, default: typing.Any = None) -> typing.Any:383 try:384 return self[key]385 except KeyError:386 return default387388 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:389 """390 Return multiple header values.391 """392 get_header_key = key.lower().encode(self.encoding)393394 values = [395 item_value.decode(self.encoding)396 for item_key, item_value in self._list397 if item_key == get_header_key398 ]399400 if not split_commas:401 return values402403 split_values = []404 for value in values:405 split_values.extend([item.strip() for item in value.split(",")])406 return split_values407408 def __getitem__(self, key: str) -> str:409 """410 Return a single header value.411412 If there are multiple headers with the same key, then we concatenate413 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2414 """415 normalized_key = key.lower().encode(self.encoding)416417 items = []418 for header_key, header_value in self._list:419 if header_key == normalized_key:420 items.append(header_value.decode(self.encoding))421422 if items:423 return ", ".join(items)424425 raise KeyError(key)426427 def __setitem__(self, key: str, value: str) -> None:428 """429 Set the header `key` to `value`, removing any duplicate entries.430 Retains insertion order.431 """432 set_key = key.lower().encode(self.encoding)433 set_value = value.encode(self.encoding)434435 found_indexes = []436 for idx, (item_key, item_value) in enumerate(self._list):437 if item_key == set_key:438 found_indexes.append(idx)439440 for idx in reversed(found_indexes[1:]):441 del self._list[idx]442443 if found_indexes:444 idx = found_indexes[0]445 self._list[idx] = (set_key, set_value)446 else:447 self._list.append((set_key, set_value))448449 def __delitem__(self, key: str) -> None:450 """451 Remove the header `key`.452 """453 del_key = key.lower().encode(self.encoding)454455 pop_indexes = []456 for idx, (item_key, item_value) in enumerate(self._list):457 if item_key == del_key:458 pop_indexes.append(idx)459460 for idx in reversed(pop_indexes):461 del self._list[idx]462463 def __contains__(self, key: typing.Any) -> bool:464 get_header_key = key.lower().encode(self.encoding)465 for header_key, header_value in self._list:466 if header_key == get_header_key:467 return True468 return False469470 def __iter__(self) -> typing.Iterator[typing.Any]:471 return iter(self.keys())472473 def __len__(self) -> int:474 return len(self._list)475476 def __eq__(self, other: typing.Any) -> bool:477 if not isinstance(other, Headers):478 return False479 return sorted(self._list) == sorted(other._list)480481 def __repr__(self) -> str:482 class_name = self.__class__.__name__483484 encoding_str = ""485 if self.encoding != "ascii":486 encoding_str = f", encoding={self.encoding!r}"487488 as_dict = dict(self.items())489 if len(as_dict) == len(self):490 return f"{class_name}({as_dict!r}{encoding_str})"491 as_list = self.items()492 return f"{class_name}({as_list!r}{encoding_str})"493494495class BaseRequest:496 def __init__(497 self,498 method: str,499 url: typing.Union[str, URL],500 *,501 params: QueryParamTypes = None,502 headers: HeaderTypes = None,503 cookies: CookieTypes = None,504 ):505 self.method = method.upper()506 self.url = URL(url, params=params)507 self.headers = Headers(headers)508 if cookies:509 self._cookies = Cookies(cookies)510 self._cookies.set_cookie_header(self)511512 def encode_data(513 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None514 ) -> typing.Tuple[bytes, str]:515 if json is not None:516 content = jsonlib.dumps(json).encode("utf-8")517 content_type = "application/json"518 elif files is not None:519 content, content_type = multipart_encode(data or {}, files)520 elif data is not None:521 content = urlencode(data, doseq=True).encode("utf-8")522 content_type = "application/x-www-form-urlencoded"523 else:524 content = b""525 content_type = ""526 return content, content_type527528 def prepare(self) -> None:529 content = getattr(self, "content", None) # type: bytes530 is_streaming = getattr(self, "is_streaming", False)531532 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]533534 has_host = "host" in self.headers535 has_user_agent = "user-agent" in self.headers536 has_accept = "accept" in self.headers537 has_content_length = (538 "content-length" in self.headers or "transfer-encoding" in self.headers539 )540 has_accept_encoding = "accept-encoding" in self.headers541 has_connection = "connection" in self.headers542543 if not has_host:544 auto_headers.append((b"host", self.url.authority.encode("ascii")))545 if not has_user_agent:546 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))547 if not has_accept:548 auto_headers.append((b"accept", b"*/*"))549 if not has_content_length:550 if is_streaming:551 auto_headers.append((b"transfer-encoding", b"chunked"))552 elif content:553 content_length = str(len(content)).encode()554 auto_headers.append((b"content-length", content_length))555 if not has_accept_encoding:556 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))557 if not has_connection:558 auto_headers.append((b"connection", b"keep-alive"))559560 for item in reversed(auto_headers):561 self.headers.raw.insert(0, item)562563 @property564 def cookies(self) -> "Cookies":565 if not hasattr(self, "_cookies"):566 self._cookies = Cookies()567 return self._cookies568569 def __repr__(self) -> str:570 class_name = self.__class__.__name__571 url = str(self.url)572 return f"<{class_name}({self.method!r}, {url!r})>"573574575class AsyncRequest(BaseRequest):576 def __init__(577 self,578 method: str,579 url: typing.Union[str, URL],580 *,581 params: QueryParamTypes = None,582 headers: HeaderTypes = None,583 cookies: CookieTypes = None,584 data: AsyncRequestData = None,585 files: RequestFiles = None,586 json: typing.Any = None,587 ):588 super().__init__(589 method=method, url=url, params=params, headers=headers, cookies=cookies590 )591592 if data is None or isinstance(data, dict):593 content, content_type = self.encode_data(data, files, json)594 self.is_streaming = False595 self.content = content596 if content_type:597 self.headers["Content-Type"] = content_type598 elif isinstance(data, (str, bytes)):599 data = data.encode("utf-8") if isinstance(data, str) else data600 self.is_streaming = False601 self.content = data602 else:603 assert hasattr(data, "__aiter__")604 self.is_streaming = True605 self.content_aiter = data606607 self.prepare()608609 async def read(self) -> bytes:610 """611 Read and return the response content.612 """613 if not hasattr(self, "content"):614 self.content = b"".join([part async for part in self.stream()])615 return self.content616617 async def stream(self) -> typing.AsyncIterator[bytes]:618 if self.is_streaming:619 async for part in self.content_aiter:620 yield part621 elif self.content:622 yield self.content623624625class Request(BaseRequest):626 def __init__(627 self,628 method: str,629 url: typing.Union[str, URL],630 *,631 params: QueryParamTypes = None,632 headers: HeaderTypes = None,633 cookies: CookieTypes = None,634 data: RequestData = None,635 files: RequestFiles = None,636 json: typing.Any = None,637 ):638 super().__init__(639 method=method, url=url, params=params, headers=headers, cookies=cookies640 )641642 if data is None or isinstance(data, dict):643 content, content_type = self.encode_data(data, files, json)644 self.is_streaming = False645 self.content = content646 if content_type:647 self.headers["Content-Type"] = content_type648 elif isinstance(data, (str, bytes)):649 data = data.encode("utf-8") if isinstance(data, str) else data650 self.is_streaming = False651 self.content = data652 else:653 assert hasattr(data, "__iter__")654 self.is_streaming = True655 self.content_iter = data656657 self.prepare()658659 def read(self) -> bytes:660 if not hasattr(self, "content"):661 self.content = b"".join([part for part in self.stream()])662 return self.content663664 def stream(self) -> typing.Iterator[bytes]:665 if self.is_streaming:666 for part in self.content_iter:667 yield part668 elif self.content:669 yield self.content670671672class BaseResponse:673 def __init__(674 self,675 status_code: int,676 *,677 protocol: str = None,678 headers: HeaderTypes = None,679 request: BaseRequest = None,680 on_close: typing.Callable = None,681 ):682 self.status_code = status_code683 self.protocol = protocol684 self.headers = Headers(headers)685686 self.request = request687 self.on_close = on_close688 self.next = None # typing.Optional[typing.Callable]689690 @property691 def reason_phrase(self) -> str:692 return StatusCode.get_reason_phrase(self.status_code)693694 @property695 def url(self) -> typing.Optional[URL]:696 """697 Returns the URL for which the request was made.698699 Requires that `request` was provided when instantiating the response.700 """701 return None if self.request is None else self.request.url702703 @property704 def content(self) -> bytes:705 if not hasattr(self, "_content"):706 if hasattr(self, "_raw_content"):707 raw_content = getattr(self, "_raw_content") # type: bytes708 content = self.decoder.decode(raw_content)709 content += self.decoder.flush()710 self._content = content711 else:712 raise ResponseNotRead()713 return self._content714715 @property716 def text(self) -> str:717 if not hasattr(self, "_text"):718 content = self.content719 if not content:720 self._text = ""721 else:722 encoding = self.encoding723 self._text = content.decode(encoding, errors="replace")724 return self._text725726 @property727 def encoding(self) -> str:728 if not hasattr(self, "_encoding"):729 encoding = self.charset_encoding730 if encoding is None or not is_known_encoding(encoding):731 encoding = self.apparent_encoding732 if encoding is None or not is_known_encoding(encoding):733 encoding = "utf-8"734 self._encoding = encoding735 return self._encoding736737 @encoding.setter738 def encoding(self, value: str) -> None:739 self._encoding = value740741 @property742 def charset_encoding(self) -> typing.Optional[str]:743 """744 Return the encoding, as specified by the Content-Type header.745 """746 content_type = self.headers.get("Content-Type")747 if content_type is None:748 return None749750 parsed = cgi.parse_header(content_type)751 media_type, params = parsed[0], parsed[-1]752 if "charset" in params:753 return params["charset"].strip("'\"")754755 # RFC 2616 specifies that 'iso-8859-1' should be used as the default756 # for 'text/*' media types, if no charset is provided.757 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1758 if media_type.startswith("text/"):759 return "iso-8859-1"760761 return None762763 @property764 def apparent_encoding(self) -> typing.Optional[str]:765 """766 Return the encoding, as it appears to autodetection.767 """768 return chardet.detect(self.content)["encoding"]769770 @property771 def decoder(self) -> Decoder:772 """773 Returns a decoder instance which can be used to decode the raw byte774 content, depending on the Content-Encoding used in the response.775 """776 if not hasattr(self, "_decoder"):777 decoders = [] # type: typing.List[Decoder]778 values = self.headers.getlist("content-encoding", split_commas=True)779 for value in values:780 value = value.strip().lower()781 decoder_cls = SUPPORTED_DECODERS[value]782 decoders.append(decoder_cls())783784 if len(decoders) == 1:785 self._decoder = decoders[0]786 elif len(decoders) > 1:787 self._decoder = MultiDecoder(decoders)788 else:789 self._decoder = IdentityDecoder()790791 return self._decoder792793 @property794 def is_redirect(self) -> bool:795 return StatusCode.is_redirect(self.status_code) and "location" in self.headers796797 def raise_for_status(self) -> None:798 """799 Raise the `HttpError` if one occurred.800 """801 message = (802 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"803 "For more information check: https://httpstatuses.com/{0.status_code}"804 )805806 if StatusCode.is_client_error(self.status_code):807 message = message.format(self, error_type="Client Error")808 elif StatusCode.is_server_error(self.status_code):809 message = message.format(self, error_type="Server Error")810 else:811 message = ""812813 if message:814 raise HttpError(message)815816 def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:817 if self.charset_encoding is None and self.content and len(self.content) > 3:818 encoding = guess_json_utf(self.content)819 if encoding is not None:820 try:821 return jsonlib.loads(self.content.decode(encoding), **kwargs)822 except UnicodeDecodeError:823 pass824 return jsonlib.loads(self.text, **kwargs)825826 @property827 def cookies(self) -> "Cookies":828 if not hasattr(self, "_cookies"):829 assert self.request is not None830 self._cookies = Cookies()831 self._cookies.extract_cookies(self)832 return self._cookies833834 def __repr__(self) -> str:835 return f"<Response [{self.status_code} {self.reason_phrase}]>"836837838class AsyncResponse(BaseResponse):839 def __init__(840 self,841 status_code: int,842 *,843 protocol: str = None,844 headers: HeaderTypes = None,845 content: AsyncResponseContent = None,846 on_close: typing.Callable = None,847 request: AsyncRequest = None,848 history: typing.List["BaseResponse"] = None,849 ):850 super().__init__(851 status_code=status_code,852 protocol=protocol,853 headers=headers,854 request=request,855 on_close=on_close,856 )857858 self.history = [] if history is None else list(history)859860 if content is None or isinstance(content, bytes):861 self.is_closed = True862 self.is_stream_consumed = True863 self._raw_content = content or b""864 else:865 self.is_closed = False866 self.is_stream_consumed = False867 self._raw_stream = content868869 async def read(self) -> bytes:870 """871 Read and return the response content.872 """873 if not hasattr(self, "_content"):874 self._content = b"".join([part async for part in self.stream()])875 return self._content876877 async def stream(self) -> typing.AsyncIterator[bytes]:878 """879 A byte-iterator over the decoded response content.880 This allows us to handle gzip, deflate, and brotli encoded responses.881 """882 if hasattr(self, "_content"):883 yield self._content884 else:885 async for chunk in self.raw():886 yield self.decoder.decode(chunk)887 yield self.decoder.flush()888889 async def raw(self) -> typing.AsyncIterator[bytes]:890 """891 A byte-iterator over the raw response content.892 """893 if hasattr(self, "_raw_content"):894 yield self._raw_content895 else:896 if self.is_stream_consumed:897 raise StreamConsumed()898 if self.is_closed:899 raise ResponseClosed()900901 self.is_stream_consumed = True902 async for part in self._raw_stream:903 yield part904 await self.close()905906 async def close(self) -> None:907 """908 Close the response and release the connection.909 Automatically called if the response body is read to completion.910 """911 if not self.is_closed:912 self.is_closed = True913 if self.on_close is not None:914 await self.on_close()915916917class Response(BaseResponse):918 def __init__(919 self,920 status_code: int,921 *,922 protocol: str = None,923 headers: HeaderTypes = None,924 content: ResponseContent = None,925 on_close: typing.Callable = None,926 request: Request = None,927 history: typing.List["BaseResponse"] = None,928 ):929 super().__init__(930 status_code=status_code,931 protocol=protocol,932 headers=headers,933 request=request,934 on_close=on_close,935 )936937 self.history = [] if history is None else list(history)938939 if content is None or isinstance(content, bytes):940 self.is_closed = True941 self.is_stream_consumed = True942 self._raw_content = content or b""943 else:944 self.is_closed = False945 self.is_stream_consumed = False946 self._raw_stream = content947948 def read(self) -> bytes:949 """950 Read and return the response content.951 """952 if not hasattr(self, "_content"):953 self._content = b"".join([part for part in self.stream()])954 return self._content955956 def stream(self) -> typing.Iterator[bytes]:957 """958 A byte-iterator over the decoded response content.959 This allows us to handle gzip, deflate, and brotli encoded responses.960 """961 if hasattr(self, "_content"):962 yield self._content963 else:964 for chunk in self.raw():965 yield self.decoder.decode(chunk)966 yield self.decoder.flush()967968 def raw(self) -> typing.Iterator[bytes]:969 """970 A byte-iterator over the raw response content.971 """972 if hasattr(self, "_raw_content"):973 yield self._raw_content974 else:975 if self.is_stream_consumed:976 raise StreamConsumed()977 if self.is_closed:978 raise ResponseClosed()979980 self.is_stream_consumed = True981 for part in self._raw_stream:982 yield part983 self.close()984985 def close(self) -> None:986 """987 Close the response and release the connection.988 Automatically called if the response body is read to completion.989 """990 if not self.is_closed:991 self.is_closed = True992 if self.on_close is not None:993 self.on_close()994995996class Cookies(MutableMapping):997 """998 HTTP Cookies, as a mutable mapping.999 """10001001 def __init__(self, cookies: CookieTypes = None) -> None:1002 if cookies is None or isinstance(cookies, dict):1003 self.jar = CookieJar()1004 if isinstance(cookies, dict):1005 for key, value in cookies.items():1006 self.set(key, value)1007 elif isinstance(cookies, Cookies):1008 self.jar = CookieJar()1009 for cookie in cookies.jar:1010 self.jar.set_cookie(cookie)1011 else:1012 self.jar = cookies10131014 def extract_cookies(self, response: BaseResponse) -> None:1015 """1016 Loads any cookies based on the response `Set-Cookie` headers.1017 """1018 assert response.request is not None1019 urlib_response = self._CookieCompatResponse(response)1020 urllib_request = self._CookieCompatRequest(response.request)10211022 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore10231024 def set_cookie_header(self, request: BaseRequest) -> None:1025 """1026 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1027 """1028 urllib_request = self._CookieCompatRequest(request)1029 self.jar.add_cookie_header(urllib_request)10301031 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1032 """1033 Set a cookie value by name. May optionally include domain and path.1034 """1035 kwargs = dict(1036 version=0,1037 name=name,1038 value=value,1039 port=None,1040 port_specified=False,1041 domain=domain,1042 domain_specified=bool(domain),1043 domain_initial_dot=domain.startswith("."),1044 path=path,1045 path_specified=bool(path),1046 secure=False,1047 expires=None,1048 discard=True,1049 comment=None,1050 comment_url=None,1051 rest={"HttpOnly": None},1052 rfc2109=False,1053 )1054 cookie = Cookie(**kwargs) # type: ignore1055 self.jar.set_cookie(cookie)10561057 def get( # type: ignore1058 self, name: str, default: str = None, domain: str = None, path: str = None1059 ) -> typing.Optional[str]:1060 """1061 Get a cookie by name. May optionally include domain and path1062 in order to specify exactly which cookie to retrieve.1063 """1064 value = None1065 for cookie in self.jar:1066 if cookie.name == name:1067 if domain is None or cookie.domain == domain: # type: ignore1068 if path is None or cookie.path == path:1069 if value is not None:1070 message = f"Multiple cookies exist with name={name}"1071 raise CookieConflict(message)1072 value = cookie.value10731074 if value is None:1075 return default1076 return value10771078 def delete(self, name: str, domain: str = None, path: str = None) -> None:1079 """1080 Delete a cookie by name. May optionally include domain and path1081 in order to specify exactly which cookie to delete.1082 """1083 if domain is not None and path is not None:1084 return self.jar.clear(domain, path, name)10851086 remove = []1087 for cookie in self.jar:1088 if cookie.name == name:1089 if domain is None or cookie.domain == domain: # type: ignore1090 if path is None or cookie.path == path:1091 remove.append(cookie)10921093 for cookie in remove:1094 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10951096 def clear(self, domain: str = None, path: str = None) -> None:1097 """1098 Delete all cookies. Optionally include a domain and path in1099 order to only delete a subset of all the cookies.1100 """1101 args = []1102 if domain is not None:1103 args.append(domain)1104 if path is not None:1105 assert domain is not None1106 args.append(path)1107 self.jar.clear(*args)11081109 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1110 cookies = Cookies(cookies)1111 for cookie in cookies.jar:1112 self.jar.set_cookie(cookie)11131114 def __setitem__(self, name: str, value: str) -> None:1115 return self.set(name, value)11161117 def __getitem__(self, name: str) -> str:1118 value = self.get(name)1119 if value is None:1120 raise KeyError(name)1121 return value11221123 def __delitem__(self, name: str) -> None:1124 return self.delete(name)11251126 def __len__(self) -> int:1127 return len(self.jar)11281129 def __iter__(self) -> typing.Iterator[str]:1130 return (cookie.name for cookie in self.jar)11311132 def __bool__(self) -> bool:1133 for cookie in self.jar:1134 return True1135 return False11361137 class _CookieCompatRequest(urllib.request.Request):1138 """1139 Wraps a `Request` instance up in a compatability interface suitable1140 for use with `CookieJar` operations.1141 """11421143 def __init__(self, request: BaseRequest) -> None:1144 super().__init__(1145 url=str(request.url),1146 headers=dict(request.headers),1147 method=request.method,1148 )1149 self.request = request11501151 def add_unredirected_header(self, key: str, value: str) -> None:1152 super().add_unredirected_header(key, value)1153 self.request.headers[key] = value11541155 class _CookieCompatResponse:1156 """1157 Wraps a `Request` instance up in a compatability interface suitable1158 for use with `CookieJar` operations.1159 """11601161 def __init__(self, response: BaseResponse):1162 self.response = response11631164 def info(self) -> email.message.Message:1165 info = email.message.Message()1166 for key, value in self.response.headers.items():1167 info[key] = value1168 return info
added:httpx/multipart.py+106 added
1import binascii2import mimetypes3import os4import typing5from io import BytesIO6from urllib.parse import quote789class Field:10 def render_headers(self) -> bytes:11 raise NotImplementedError() # pragma: nocover1213 def render_data(self) -> bytes:14 raise NotImplementedError() # pragma: nocover151617class DataField(Field):18 def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:19 if not isinstance(name, str):20 raise TypeError("Invalid type for name. Expected str.")21 if not isinstance(value, (str, bytes)):22 raise TypeError("Invalid type for value. Expected str or bytes.")23 self.name = name24 self.value = value2526 def render_headers(self) -> bytes:27 name = quote(self.name, encoding="utf-8").encode("ascii")28 return b"".join(29 [b'Content-Disposition: form-data; name="', name, b'"\r\n' b"\r\n"]30 )3132 def render_data(self) -> bytes:33 return (34 self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")35 )363738class FileField(Field):39 def __init__(40 self, name: str, value: typing.Union[typing.IO[typing.AnyStr], tuple]41 ) -> None:42 self.name = name43 if not isinstance(value, tuple):44 self.filename = os.path.basename(getattr(value, "name", "upload"))45 self.file = value # type: typing.Union[typing.IO[str], typing.IO[bytes]]46 self.content_type = self.guess_content_type()47 else:48 self.filename = value[0]49 self.file = value[1]50 self.content_type = (51 value[2] if len(value) > 2 else self.guess_content_type()52 )5354 def guess_content_type(self) -> str:55 return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"5657 def render_headers(self) -> bytes:58 name = quote(self.name, encoding="utf-8").encode("ascii")59 filename = quote(self.filename, encoding="utf-8").encode("ascii")60 content_type = self.content_type.encode("ascii")61 return b"".join(62 [63 b'Content-Disposition: form-data; name="',64 name,65 b'"; filename="',66 filename,67 b'"\r\n',68 b"Content-Type: ",69 content_type,70 b"\r\n",71 b"\r\n",72 ]73 )7475 def render_data(self) -> bytes:76 content = self.file.read()77 return content.encode("utf-8") if isinstance(content, str) else content787980def iter_fields(data: dict, files: dict) -> typing.Iterator[Field]:81 for name, value in data.items():82 if isinstance(value, (list, dict)):83 for item in value:84 yield DataField(name=name, value=item)85 else:86 yield DataField(name=name, value=value)8788 for name, value in files.items():89 yield FileField(name=name, value=value)909192def multipart_encode(data: dict, files: dict) -> typing.Tuple[bytes, str]:93 body = BytesIO()94 boundary = binascii.hexlify(os.urandom(16))9596 for field in iter_fields(data, files):97 body.write(b"--%s\r\n" % boundary)98 body.write(field.render_headers())99 body.write(field.render_data())100 body.write(b"\r\n")101102 body.write(b"--%s--\r\n" % boundary)103104 content_type = "multipart/form-data; boundary=%s" % boundary.decode("ascii")105106 return body.getvalue(), content_type
added:httpx/status_codes.py+131 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 get_reason_phrase(cls, value: int) -> str:30 try:31 return StatusCode(value).phrase # type: ignore32 except ValueError:33 return ""3435 @classmethod36 def is_redirect(cls, value: int) -> bool:37 return value in (38 # 301 (Cacheable redirect. Method may change to GET.)39 StatusCode.MOVED_PERMANENTLY,40 # 302 (Uncacheable redirect. Method may change to GET.)41 StatusCode.FOUND,42 # 303 (Client should make a GET or HEAD request.)43 StatusCode.SEE_OTHER,44 # 307 (Equiv. 302, but retain method)45 StatusCode.TEMPORARY_REDIRECT,46 # 308 (Equiv. 301, but retain method)47 StatusCode.PERMANENT_REDIRECT,48 )4950 @classmethod51 def is_client_error(cls, value: int) -> bool:52 return value >= 400 and value <= 4995354 @classmethod55 def is_server_error(cls, value: int) -> bool:56 return value >= 500 and value <= 5995758 # informational59 CONTINUE = 100, "Continue"60 SWITCHING_PROTOCOLS = 101, "Switching Protocols"61 PROCESSING = 102, "Processing"6263 # success64 OK = 200, "OK"65 CREATED = 201, "Created"66 ACCEPTED = 202, "Accepted"67 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"68 NO_CONTENT = 204, "No Content"69 RESET_CONTENT = 205, "Reset Content"70 PARTIAL_CONTENT = 206, "Partial Content"71 MULTI_STATUS = 207, "Multi-Status"72 ALREADY_REPORTED = 208, "Already Reported"73 IM_USED = 226, "IM Used"7475 # redirection76 MULTIPLE_CHOICES = 300, "Multiple Choices"77 MOVED_PERMANENTLY = 301, "Moved Permanently"78 FOUND = 302, "Found"79 SEE_OTHER = 303, "See Other"80 NOT_MODIFIED = 304, "Not Modified"81 USE_PROXY = 305, "Use Proxy"82 TEMPORARY_REDIRECT = 307, "Temporary Redirect"83 PERMANENT_REDIRECT = 308, "Permanent Redirect"8485 # client error86 BAD_REQUEST = 400, "Bad Request"87 UNAUTHORIZED = 401, "Unauthorized"88 PAYMENT_REQUIRED = 402, "Payment Required"89 FORBIDDEN = 403, "Forbidden"90 NOT_FOUND = 404, "Not Found"91 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"92 NOT_ACCEPTABLE = 406, "Not Acceptable"93 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"94 REQUEST_TIMEOUT = 408, "Request Timeout"95 CONFLICT = 409, "Conflict"96 GONE = 410, "Gone"97 LENGTH_REQUIRED = 411, "Length Required"98 PRECONDITION_FAILED = 412, "Precondition Failed"99 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"100 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"101 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"102 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"103 EXPECTATION_FAILED = 417, "Expectation Failed"104 MISDIRECTED_REQUEST = 421, "Misdirected Request"105 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"106 LOCKED = 423, "Locked"107 FAILED_DEPENDENCY = 424, "Failed Dependency"108 UPGRADE_REQUIRED = 426, "Upgrade Required"109 PRECONDITION_REQUIRED = 428, "Precondition Required"110 TOO_MANY_REQUESTS = 429, "Too Many Requests"111 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"112113 # server errors114 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"115 NOT_IMPLEMENTED = 501, "Not Implemented"116 BAD_GATEWAY = 502, "Bad Gateway"117 SERVICE_UNAVAILABLE = 503, "Service Unavailable"118 GATEWAY_TIMEOUT = 504, "Gateway Timeout"119 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"120 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"121 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"122 LOOP_DETECTED = 508, "Loop Detected"123 NOT_EXTENDED = 510, "Not Extended"124 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"125126127codes = StatusCode128129#  Include lower-case styles for `requests` compatability.130for code in codes:131 setattr(codes, code._name_.lower(), int(code))
added:httpx/utils.py+66 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 True323334# Null bytes; no need to recreate these on each call to guess_json_utf35_null = "\x00".encode("ascii") # encoding to ASCII for Python 336_null2 = _null * 237_null3 = _null * 3383940def guess_json_utf(data: bytes) -> typing.Optional[str]:41 # JSON always starts with two ASCII characters, so detection is as42 # easy as counting the nulls and from their location and count43 # determine the encoding. Also detect a BOM, if present.44 sample = data[:4]45 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):46 return "utf-32" # BOM included47 if sample[:3] == codecs.BOM_UTF8:48 return "utf-8-sig" # BOM included, MS style (discouraged)49 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):50 return "utf-16" # BOM included51 nullcount = sample.count(_null)52 if nullcount == 0:53 return "utf-8"54 if nullcount == 2:55 if sample[::2] == _null2: # 1st and 3rd are null56 return "utf-16-be"57 if sample[1::2] == _null2: # 2nd and 4th are null58 return "utf-16-le"59 # Did not detect 2 valid UTF-16 ascii-range characters60 if nullcount == 3:61 if sample[:3] == _null3:62 return "utf-32-be"63 if sample[1:] == _null3:64 return "utf-32-le"65 # Did not detect a valid UTF-32 ascii-range character66 return None
modified:scripts/clean+2 added-2 removed
7 unmodified lines
8fi9if [ -d 'htmlcov' ] ; then10 rm -r htmlcov11fi12if [ -d 'http3.egg-info' ] ; then13 rm -r http3.egg-info12if [ -d 'httpx.egg-info' ] ; then13 rm -r httpx.egg-info14fi
modified:scripts/lint+5 added-5 removed
5 unmodified lines
6fi78set -x910${PREFIX}autoflake --in-place --recursive http3 tests setup.py11${PREFIX}isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply http3 tests setup.py12${PREFIX}black http3 tests setup.py13${PREFIX}flake8 --max-line-length=88 --ignore=W503,E203 http3 tests setup.py14${PREFIX}mypy http3 --ignore-missing-imports --disallow-untyped-defs10${PREFIX}autoflake --in-place --recursive httpx tests setup.py11${PREFIX}isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply httpx tests setup.py12${PREFIX}black httpx tests setup.py13${PREFIX}flake8 --max-line-length=88 --ignore=W503,E203 httpx tests setup.py14${PREFIX}mypy httpx --ignore-missing-imports --disallow-untyped-defs1516scripts/clean
modified:scripts/publish+1 added-1 removed
1#!/bin/sh -e23export PACKAGE="http3"3export PACKAGE="httpx"4export VERSION=`cat ${PACKAGE}/__version__.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="http3"3export PACKAGE="httpx"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 http33import httpx456@pytest.mark.asyncio7async def test_get(server):8 url = "http://127.0.0.1:8000/"9 async with http3.AsyncClient() as client:9 async with httpx.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 http3.AsyncClient() as client:21 async with httpx.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 http3.AsyncClient() as client:29 async with httpx.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 http3.AsyncClient() as client:36 async with httpx.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 http3.AsyncClient() as client:46 async with httpx.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(http3.ResponseNotRead):49 with pytest.raises(httpx.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 http3.AsyncClient() as client:59 async with httpx.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 http3.AsyncClient() as client:68 async with httpx.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(http3.exceptions.HttpError):75 with pytest.raises(httpx.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 http3.AsyncClient() as client:84 async with httpx.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 http3.AsyncClient() as client:93 async with httpx.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 http3.AsyncClient() as client:102 async with httpx.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 http3.AsyncClient() as client:110 async with httpx.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 http3.AsyncClient() as client:118 async with httpx.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 http3.AsyncClient() as client:130 async with httpx.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 json23from http3 import (3from httpx import (4 AsyncDispatcher,5 AsyncRequest,6 AsyncResponse,7 CertTypes,
62 unmodified lines
modified:tests/client/test_client.py+17 added-17 removed
1 unmodified line
2import functools34import pytest56import http36import httpx789def threadpool(func):10 """
14 unmodified lines
2526@threadpool27def test_get(server):28 url = "http://127.0.0.1:8000/"29 with http3.Client() as http:29 with httpx.Client() as http:30 response = http.get(url)31 assert response.status_code == 20032 assert response.url == http3.URL(url)32 assert response.url == httpx.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 == http3.URL(url)37 assert response.request.url == httpx.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 http3.Client() as http:45 with httpx.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 http3.Client() as http:53 with httpx.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 http3.Client() as http:61 with httpx.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 http3.Client() as http:70 with httpx.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 http3.Client() as http:81 with httpx.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 http3.Client() as client:93 with httpx.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(http3.exceptions.HttpError):100 with pytest.raises(httpx.exceptions.HttpError):101 response.raise_for_status()102 else:103 assert response.raise_for_status() is None104105106@threadpool107def test_options(server):108 with http3.Client() as http:108 with httpx.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 http3.Client() as http:116 with httpx.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 http3.Client() as http:124 with httpx.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 http3.Client() as http:132 with httpx.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 http3.Client() as http:140 with httpx.Client() as http:141 response = http.delete("http://127.0.0.1:8000/")142 assert response.status_code == 200143 assert response.reason_phrase == "OK"144145146@threadpool147def test_base_url(server):148 base_url = "http://127.0.0.1:8000/"149 with http3.Client(base_url=base_url) as http:149 with httpx.Client(base_url=base_url) as http:150 response = http.get("/")151 assert response.status_code == 200152 assert str(response.url) == base_url
modified:tests/client/test_cookies.py+1 added-1 removed
1import json2from http.cookiejar import Cookie, CookieJar34from http3 import (4from httpx import (5 AsyncDispatcher,6 AsyncRequest,7 AsyncResponse,8 CertTypes,
116 unmodified lines
modified:tests/client/test_redirects.py+1 added-1 removed
1 unmodified line
2from urllib.parse import parse_qs34import pytest56from http3 import (6from httpx import (7 URL,8 AsyncClient,9 AsyncDispatcher,10 AsyncRequest,
242 unmodified lines
modified:tests/dispatch/test_connection_pools.py+10 added-10 removed
1import pytest23import http33import httpx456@pytest.mark.asyncio7async def test_keepalive_connections(server):8 """9 Connections should default to staying in a keep-alive state.10 """11 async with http3.ConnectionPool() as http:11 async with httpx.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 http3.ConnectionPool() as http:28 async with httpx.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 = http3.PoolLimits(soft_limit=1)45 pool_limits = httpx.PoolLimits(soft_limit=1)4647 async with http3.ConnectionPool(pool_limits=pool_limits) as http:47 async with httpx.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 http3.ConnectionPool() as http:64 async with httpx.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 http3.ConnectionPool() as http:80 async with httpx.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 http3.ConnectionPool() as http:104 async with httpx.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 http3.ConnectionPool() as http:116 async with httpx.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 http3.ConnectionPool() as http:129 async with httpx.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 http3 import HTTPConnection3from httpx import HTTPConnection456@pytest.mark.asyncio7async def test_get(server):
38 unmodified lines
modified:tests/dispatch/test_http2.py+1 added-1 removed
1import json23from http3 import Client, Response3from httpx import Client, Response45from .utils import MockHTTP2Backend67
71 unmodified lines
modified:tests/dispatch/test_threaded.py+1 added-1 removed
1import json23from http3 import (3from httpx import (4 CertTypes,5 Client,6 Dispatcher,7 Request,
91 unmodified lines
modified:tests/dispatch/utils.py+1 added-1 removed
4 unmodified lines
5import h2.config6import h2.connection7import h2.events89from http3 import (9from httpx import (10 AsyncioBackend,11 BaseReader,12 BaseWriter,13 Protocol,
109 unmodified lines
modified:tests/models/test_cookies.py+1 added-1 removed
1import pytest23from http3 import CookieConflict, Cookies3from httpx import CookieConflict, Cookies456def test_cookies():7 cookies = Cookies({"name": "value"})
43 unmodified lines
modified:tests/models/test_headers.py+20 added-20 removed
1import http31import httpx234def test_headers():5 h = http3.Headers([("a", "123"), ("a", "456"), ("b", "789")])5 h = httpx.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 == http3.Headers([("a", "123"), ("b", "789"), ("a", "456")])21 assert h == httpx.Headers([("a", "123"), ("b", "789"), ("a", "456")])22 assert h != [("a", "123"), ("A", "456"), ("b", "789")]2324 h = http3.Headers({"a": "123", "b": "789"})24 h = httpx.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 = http3.Headers()32 h = httpx.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 = http3.Headers({"custom": "example"})49 headers_copy = http3.Headers(headers)48 headers = httpx.Headers({"custom": "example"})49 headers_copy = httpx.Headers(headers)50 assert headers == headers_copy515253def test_headers_insert_retains_ordering():54 headers = http3.Headers({"a": "a", "b": "b", "c": "c"})54 headers = httpx.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 = http3.Headers({"a": "a", "b": "b", "c": "c"})60 headers = httpx.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 = http3.Headers([("a", "123"), ("a", "456")])66 headers = httpx.Headers([("a", "123"), ("a", "456")])67 headers["a"] = "789"68 assert dict(headers) == {"a": "789"}697071def test_headers_delete_removes_all_existing():72 headers = http3.Headers([("a", "123"), ("a", "456")])72 headers = httpx.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 = http3.Headers({"custom": "example"})81 headers = httpx.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 = http3.Headers({b"custom": "example ☃".encode("utf-8")})89 headers = httpx.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 = http3.Headers([("custom", "example 1"), ("custom", "example 2")])97 headers = httpx.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 = http3.Headers(raw_headers)108 headers = httpx.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 = http3.Headers(raw_headers)118 headers = httpx.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 = http3.Headers(raw_headers)128 headers = httpx.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 = http3.Headers(raw_headers)139 headers = httpx.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 = http3.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])149 h = httpx.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])150 h.getlist("Set-Cookie") == ["a, b", "b"]151152 h = http3.Headers([("vary", "a, b"), ("vary", "c")])152 h = httpx.Headers([("vary", "a, b"), ("vary", "c")])153 h.getlist("Vary") == ["a", "b", "c"]
modified:tests/models/test_queryparams.py+1 added-1 removed
1from http3 import QueryParams1from httpx import QueryParams234def test_queryparams():5 q = QueryParams("a=123&a=456&b=789")
28 unmodified lines
modified:tests/models/test_requests.py+16 added-16 removed
1import pytest23import http33import httpx456def test_request_repr():7 request = http3.Request("GET", "http://example.org")7 request = httpx.Request("GET", "http://example.org")8 assert repr(request) == "<Request('GET', 'http://example.org')>"91011def test_no_content():12 request = http3.Request("GET", "http://example.org")12 request = httpx.Request("GET", "http://example.org")13 assert "Content-Length" not in request.headers141516def test_content_length_header():17 request = http3.Request("POST", "http://example.org", data=b"test 123")17 request = httpx.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 (http3.Request, http3.AsyncRequest):22 for RequestClass in (httpx.Request, httpx.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 (http3.Request, http3.AsyncRequest):29 for RequestClass in (httpx.Request, httpx.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 = http3.Request("POST", "http://example.org", data=data)41 request = httpx.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 = http3.Request("GET", "http://example.org", headers=headers)49 request = httpx.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 = http3.Request("GET", "http://example.org", headers=headers)56 request = httpx.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 = http3.Request("POST", "http://example.org", data=data, headers=headers)67 request = httpx.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 = http3.Request("GET", url)73 request = httpx.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 = http3.Request("GET", url)79 request = httpx.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(http3.InvalidURL):87 http3.Request("GET", "example.org")86 with pytest.raises(httpx.InvalidURL):87 httpx.Request("GET", "example.org")8889 with pytest.raises(http3.InvalidURL):90 http3.Request("GET", "http:///foo")89 with pytest.raises(httpx.InvalidURL):90 httpx.Request("GET", "http:///foo")
modified:tests/models/test_responses.py+33 added-33 removed
1 unmodified line
2from unittest import mock34import pytest56import http36import httpx789def streaming_body():10 yield b"Hello, "
5 unmodified lines
16 yield b"world!"171819def test_response():20 response = http3.Response(200, content=b"Hello, world!")20 response = httpx.Response(200, content=b"Hello, world!")21 assert response.status_code == 20022 assert response.reason_phrase == "OK"23 assert response.text == "Hello, world!"242526def test_response_repr():27 response = http3.Response(200, content=b"Hello, world!")27 response = httpx.Response(200, content=b"Hello, world!")28 assert repr(response) == "<Response [200 OK]>"293031def test_response_content_type_encoding():
1 unmodified line
33 Use the charset encoding in the Content-Type header if possible.34 """35 headers = {"Content-Type": "text-plain; charset=latin-1"}36 content = "Latin 1: ÿ".encode("latin-1")37 response = http3.Response(200, content=content, headers=headers)37 response = httpx.Response(200, content=content, headers=headers)38 assert response.text == "Latin 1: ÿ"39 assert response.encoding == "latin-1"4041
1 unmodified line
43 """44 Autodetect encoding if there is no charset info in a Content-Type header.45 """46 content = "おはようございます。".encode("EUC-JP")47 response = http3.Response(200, content=content)47 response = httpx.Response(200, content=content)48 assert response.text == "おはようございます。"49 assert response.encoding == "EUC-JP"5051
2 unmodified lines
54 Fallback to autodetection if we get an invalid charset in the Content-Type header.55 """56 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}57 content = "おはようございます。".encode("EUC-JP")58 response = http3.Response(200, content=content, headers=headers)58 response = httpx.Response(200, content=content, headers=headers)59 assert response.text == "おはようございます。"60 assert response.encoding == "EUC-JP"6162
3 unmodified lines
66 See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.167 """68 content = b"Hello, world!"69 headers = {"Content-Type": "text/plain"}70 response = http3.Response(200, content=content, headers=headers)70 response = httpx.Response(200, content=content, headers=headers)71 assert response.status_code == 20072 assert response.encoding == "iso-8859-1"73 assert response.text == "Hello, world!"74
1 unmodified line
76def test_response_default_encoding():77 """78 Default to utf-8 if all else fails.79 """80 response = http3.Response(200, content=b"")80 response = httpx.Response(200, content=b"")81 assert response.text == ""82 assert response.encoding == "utf-8"8384
1 unmodified line
86 """87 Default to apparent encoding for non-text content-type headers.88 """89 headers = {"Content-Type": "image/png"}90 response = http3.Response(200, content=b"xyz", headers=headers)90 response = httpx.Response(200, content=b"xyz", headers=headers)91 assert response.text == "xyz"92 assert response.encoding == "ascii"939495def test_response_set_explicit_encoding():96 headers = {97 "Content-Type": "text-plain; charset=utf-8"98 } # Deliberately incorrect charset99 response = http3.Response(99 response = httpx.Response(100 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers101 )102 response.encoding = "latin-1"103 assert response.text == "Latin 1: ÿ"104 assert response.encoding == "latin-1"105106107def test_response_force_encoding():108 response = http3.Response(200, content="Snowman: ☃".encode("utf-8"))108 response = httpx.Response(200, content="Snowman: ☃".encode("utf-8"))109 response.encoding = "iso-8859-1"110 assert response.status_code == 200111 assert response.reason_phrase == "OK"112 assert response.text == "Snowman: â\x98\x83"113 assert response.encoding == "iso-8859-1"114115116def test_read_response():117 response = http3.Response(200, content=b"Hello, world!")117 response = httpx.Response(200, content=b"Hello, world!")118119 assert response.status_code == 200120 assert response.text == "Hello, world!"121 assert response.encoding == "ascii"
6 unmodified lines
128 assert response.is_closed129130131def test_raw_interface():132 response = http3.Response(200, content=b"Hello, world!")132 response = httpx.Response(200, content=b"Hello, world!")133134 raw = b""135 for part in response.raw():136 raw += part137 assert raw == b"Hello, world!"138139140def test_stream_interface():141 response = http3.Response(200, content=b"Hello, world!")141 response = httpx.Response(200, content=b"Hello, world!")142143 content = b""144 for part in response.stream():145 content += part
1 unmodified line
147148149@pytest.mark.asyncio150async def test_async_stream_interface():151 response = http3.AsyncResponse(200, content=b"Hello, world!")151 response = httpx.AsyncResponse(200, content=b"Hello, world!")152153 content = b""154 async for part in response.stream():155 content += part156 assert content == b"Hello, world!"157158159def test_stream_interface_after_read():160 response = http3.Response(200, content=b"Hello, world!")160 response = httpx.Response(200, content=b"Hello, world!")161162 response.read()163164 content = b""
3 unmodified lines
168169170@pytest.mark.asyncio171async def test_async_stream_interface_after_read():172 response = http3.AsyncResponse(200, content=b"Hello, world!")172 response = httpx.AsyncResponse(200, content=b"Hello, world!")173174 await response.read()175176 content = b""
2 unmodified lines
179 assert content == b"Hello, world!"180181182def test_streaming_response():183 response = http3.Response(200, content=streaming_body())183 response = httpx.Response(200, content=streaming_body())184185 assert response.status_code == 200186 assert not response.is_closed187
5 unmodified lines
193194195@pytest.mark.asyncio196async def test_async_streaming_response():197 response = http3.AsyncResponse(200, content=async_streaming_body())197 response = httpx.AsyncResponse(200, content=async_streaming_body())198199 assert response.status_code == 200200 assert not response.is_closed201
4 unmodified lines
206 assert response.is_closed207208209def test_cannot_read_after_stream_consumed():210 response = http3.Response(200, content=streaming_body())210 response = httpx.Response(200, content=streaming_body())211212 content = b""213 for part in response.stream():214 content += part215216 with pytest.raises(http3.StreamConsumed):216 with pytest.raises(httpx.StreamConsumed):217 response.read()218219220@pytest.mark.asyncio221async def test_async_cannot_read_after_stream_consumed():222 response = http3.AsyncResponse(200, content=async_streaming_body())222 response = httpx.AsyncResponse(200, content=async_streaming_body())223224 content = b""225 async for part in response.stream():226 content += part227228 with pytest.raises(http3.StreamConsumed):228 with pytest.raises(httpx.StreamConsumed):229 await response.read()230231232def test_cannot_read_after_response_closed():233 response = http3.Response(200, content=streaming_body())233 response = httpx.Response(200, content=streaming_body())234235 response.close()236237 with pytest.raises(http3.ResponseClosed):237 with pytest.raises(httpx.ResponseClosed):238 response.read()239240241@pytest.mark.asyncio242async def test_async_cannot_read_after_response_closed():243 response = http3.AsyncResponse(200, content=async_streaming_body())243 response = httpx.AsyncResponse(200, content=async_streaming_body())244245 await response.close()246247 with pytest.raises(http3.ResponseClosed):247 with pytest.raises(httpx.ResponseClosed):248 await response.read()249250251def test_unknown_status_code():252 response = http3.Response(600)252 response = httpx.Response(600)253 assert response.status_code == 600254 assert response.reason_phrase == ""255 assert response.text == ""256
1 unmodified line
258def test_json_with_specified_encoding():259 data = dict(greeting="hello", recipient="world")260 content = json.dumps(data).encode("utf-16")261 headers = {"Content-Type": "application/json, charset=utf-16"}262 response = http3.Response(200, content=content, headers=headers)262 response = httpx.Response(200, content=content, headers=headers)263 assert response.json() == data264265266def test_json_with_options():267 data = dict(greeting="hello", recipient="world", amount=1)268 content = json.dumps(data).encode("utf-16")269 headers = {"Content-Type": "application/json, charset=utf-16"}270 response = http3.Response(200, content=content, headers=headers)270 response = httpx.Response(200, content=content, headers=headers)271 assert response.json(parse_int=str)["amount"] == "1"272273274def test_json_without_specified_encoding():275 data = dict(greeting="hello", recipient="world")276 content = json.dumps(data).encode("utf-32-be")277 headers = {"Content-Type": "application/json"}278 response = http3.Response(200, content=content, headers=headers)278 response = httpx.Response(200, content=content, headers=headers)279 assert response.json() == data280281282def test_json_without_specified_encoding_decode_error():283 data = dict(greeting="hello", recipient="world")284 content = json.dumps(data).encode("utf-32-be")285 headers = {"Content-Type": "application/json"}286 # force incorrect guess from `guess_json_utf` to trigger error287 with mock.patch("http3.models.guess_json_utf", return_value="utf-32"):288 response = http3.Response(200, content=content, headers=headers)287 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):288 response = httpx.Response(200, content=content, headers=headers)289 with pytest.raises(json.JSONDecodeError):290 response.json()
modified:tests/models/test_url.py+1 added-1 removed
1from http3 import URL1from httpx import URL234def test_idna_url():5 url = URL("http://中国.icom.museum:80/")
39 unmodified lines
modified:tests/test_api.py+11 added-11 removed
1 unmodified line
2import functools34import pytest56import http36import httpx789def threadpool(func):10 """
13 unmodified lines
242526@threadpool27def test_get(server):28 response = http3.get("http://127.0.0.1:8000/")28 response = httpx.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 = http3.post("http://127.0.0.1:8000/", data=b"Hello, world!")36 response = httpx.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 = http3.post("http://127.0.0.1:8000/", data=data())48 response = httpx.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 = http3.options("http://127.0.0.1:8000/")55 response = httpx.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 = http3.head("http://127.0.0.1:8000/")62 response = httpx.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 = http3.put("http://127.0.0.1:8000/", data=b"Hello, world!")69 response = httpx.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 = http3.patch("http://127.0.0.1:8000/", data=b"Hello, world!")76 response = httpx.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 = http3.delete("http://127.0.0.1:8000/")83 response = httpx.delete("http://127.0.0.1:8000/")84 assert response.status_code == 20085 assert response.reason_phrase == "OK"868788@threadpool89def test_get_invalid_url(server):90 with pytest.raises(http3.InvalidURL):91 http3.get("invalid://example.org")90 with pytest.raises(httpx.InvalidURL):91 httpx.get("invalid://example.org")
modified:tests/test_asgi.py+5 added-5 removed
1import pytest23import http33import httpx456async def hello_world(scope, receive, send):7 status = 200
31 unmodified lines
39 raise ValueError()404142def test_asgi():43 client = http3.Client(app=hello_world)43 client = httpx.Client(app=hello_world)44 response = client.get("http://www.example.org/")45 assert response.status_code == 20046 assert response.text == "Hello, World!"474849def test_asgi_upload():50 client = http3.Client(app=echo_body)50 client = httpx.Client(app=echo_body)51 response = client.post("http://www.example.org/", data=b"example")52 assert response.status_code == 20053 assert response.text == "example"545556def test_asgi_exc():57 client = http3.Client(app=raise_exc)57 client = httpx.Client(app=raise_exc)58 with pytest.raises(ValueError):59 client.get("http://www.example.org/")606162def test_asgi_exc_after_response():63 client = http3.Client(app=raise_exc_after_response)63 client = httpx.Client(app=raise_exc_after_response)64 with pytest.raises(ValueError):65 client.get("http://www.example.org/")
modified:tests/test_config.py+25 added-25 removed
1 unmodified line
2import ssl34import pytest56import http36import httpx789@pytest.mark.asyncio10async def test_load_ssl_config():11 ssl_config = http3.SSLConfig()11 ssl_config = httpx.SSLConfig()12 context = await ssl_config.load_ssl_context()13 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED14 assert context.check_hostname is True151617@pytest.mark.asyncio18async def test_load_ssl_config_verify_non_existing_path():19 ssl_config = http3.SSLConfig(verify="/path/to/nowhere")19 ssl_config = httpx.SSLConfig(verify="/path/to/nowhere")20 with pytest.raises(IOError):21 await ssl_config.load_ssl_context()222324@pytest.mark.asyncio25async def test_load_ssl_config_verify_existing_file():26 ssl_config = http3.SSLConfig(verify=http3.config.DEFAULT_CA_BUNDLE_PATH)26 ssl_config = httpx.SSLConfig(verify=httpx.config.DEFAULT_CA_BUNDLE_PATH)27 context = await ssl_config.load_ssl_context()28 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED29 assert context.check_hostname is True303132@pytest.mark.asyncio33async def test_load_ssl_config_verify_directory():34 path = os.path.dirname(http3.config.DEFAULT_CA_BUNDLE_PATH)35 ssl_config = http3.SSLConfig(verify=path)34 path = os.path.dirname(httpx.config.DEFAULT_CA_BUNDLE_PATH)35 ssl_config = httpx.SSLConfig(verify=path)36 context = await ssl_config.load_ssl_context()37 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED38 assert context.check_hostname is True394041@pytest.mark.asyncio42async def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):43 ssl_config = http3.SSLConfig(cert=(cert_pem_file, cert_private_key_file))43 ssl_config = httpx.SSLConfig(cert=(cert_pem_file, cert_private_key_file))44 context = await ssl_config.load_ssl_context()45 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED46 assert context.check_hostname is True47
2 unmodified lines
50@pytest.mark.parametrize("password", [b"password", "password"])51async def test_load_ssl_config_cert_and_encrypted_key(52 cert_pem_file, cert_encrypted_private_key_file, password53):54 ssl_config = http3.SSLConfig(54 ssl_config = httpx.SSLConfig(55 cert=(cert_pem_file, cert_encrypted_private_key_file, password)56 )57 context = await ssl_config.load_ssl_context()58 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
3 unmodified lines
62@pytest.mark.asyncio63async def test_load_ssl_config_cert_and_key_invalid_password(64 cert_pem_file, cert_encrypted_private_key_file65):66 ssl_config = http3.SSLConfig(66 ssl_config = httpx.SSLConfig(67 cert=(cert_pem_file, cert_encrypted_private_key_file, "password1")68 )6970 with pytest.raises(ssl.SSLError):
1 unmodified line
727374@pytest.mark.asyncio75async def test_load_ssl_config_cert_without_key_raises(cert_pem_file):76 ssl_config = http3.SSLConfig(cert=cert_pem_file)76 ssl_config = httpx.SSLConfig(cert=cert_pem_file)77 with pytest.raises(ssl.SSLError):78 await ssl_config.load_ssl_context()798081@pytest.mark.asyncio82async def test_load_ssl_config_no_verify():83 ssl_config = http3.SSLConfig(verify=False)83 ssl_config = httpx.SSLConfig(verify=False)84 context = await ssl_config.load_ssl_context()85 assert context.verify_mode == ssl.VerifyMode.CERT_NONE86 assert context.check_hostname is False878889def test_ssl_repr():90 ssl = http3.SSLConfig(verify=False)90 ssl = httpx.SSLConfig(verify=False)91 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"929394def test_timeout_repr():95 timeout = http3.TimeoutConfig(timeout=5.0)95 timeout = httpx.TimeoutConfig(timeout=5.0)96 assert repr(timeout) == "TimeoutConfig(timeout=5.0)"9798 timeout = http3.TimeoutConfig(read_timeout=5.0)98 timeout = httpx.TimeoutConfig(read_timeout=5.0)99 assert (100 repr(timeout)101 == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, write_timeout=None)"102 )103104105def test_limits_repr():106 limits = http3.PoolLimits(hard_limit=100)106 limits = httpx.PoolLimits(hard_limit=100)107 assert (108 repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100, pool_timeout=None)"109 )110111112def test_ssl_eq():113 ssl = http3.SSLConfig(verify=False)114 assert ssl == http3.SSLConfig(verify=False)113 ssl = httpx.SSLConfig(verify=False)114 assert ssl == httpx.SSLConfig(verify=False)115116117def test_timeout_eq():118 timeout = http3.TimeoutConfig(timeout=5.0)119 assert timeout == http3.TimeoutConfig(timeout=5.0)118 timeout = httpx.TimeoutConfig(timeout=5.0)119 assert timeout == httpx.TimeoutConfig(timeout=5.0)120121122def test_limits_eq():123 limits = http3.PoolLimits(hard_limit=100)124 assert limits == http3.PoolLimits(hard_limit=100)123 limits = httpx.PoolLimits(hard_limit=100)124 assert limits == httpx.PoolLimits(hard_limit=100)125126127def test_timeout_from_tuple():128 timeout = http3.TimeoutConfig(timeout=(5.0, 5.0, 5.0))129 assert timeout == http3.TimeoutConfig(timeout=5.0)128 timeout = httpx.TimeoutConfig(timeout=(5.0, 5.0, 5.0))129 assert timeout == httpx.TimeoutConfig(timeout=5.0)130131132def test_timeout_from_config_instance():133 timeout = http3.TimeoutConfig(timeout=5.0)134 assert http3.TimeoutConfig(timeout) == http3.TimeoutConfig(timeout=5.0)133 timeout = httpx.TimeoutConfig(timeout=5.0)134 assert httpx.TimeoutConfig(timeout) == httpx.TimeoutConfig(timeout=5.0)
modified:tests/test_decoders.py+10 added-10 removed
1 unmodified line
23import brotli4import pytest56import http36import httpx789def 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 = http3.Response(200, headers=headers, content=compressed_body)15 response = httpx.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 = http3.Response(200, headers=headers, content=compressed_body)25 response = httpx.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 = http3.Response(200, headers=headers, content=compressed_body)34 response = httpx.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 = http3.Response(200, headers=headers, content=compressed_body)50 response = httpx.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 = http3.Response(200, headers=headers, content=compressed_body)59 response = httpx.Response(200, headers=headers, content=compressed_body)60 assert response.content == body6162 headers = [(b"Content-Encoding", b"identity, br")]63 response = http3.Response(200, headers=headers, content=compressed_body)63 response = httpx.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 = http3.Response(200, headers=headers, content=compress(body))76 response = httpx.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(http3.exceptions.DecodingError):87 response = http3.Response(200, headers=headers, content=compressed_body)86 with pytest.raises(httpx.exceptions.DecodingError):87 response = httpx.Response(200, headers=headers, content=compressed_body)88 response.content
modified:tests/test_multipart.py+1 added-1 removed
4 unmodified lines
5from unittest import mock67import pytest89from http3 import (9from httpx import (10 CertTypes,11 Client,12 Dispatcher,13 multipart,
111 unmodified lines
modified:tests/test_status_codes.py+6 added-6 removed
1import http31import httpx234def test_status_code_as_int():5 assert http3.codes.NOT_FOUND == 4046 assert str(http3.codes.NOT_FOUND) == "404"5 assert httpx.codes.NOT_FOUND == 4046 assert str(httpx.codes.NOT_FOUND) == "404"789def test_lowercase_status_code():10 assert http3.codes.not_found == 40410 assert httpx.codes.not_found == 404111213def test_reason_phrase_for_status_code():14 assert http3.codes.get_reason_phrase(404) == "Not Found"14 assert httpx.codes.get_reason_phrase(404) == "Not Found"151617def test_reason_phrase_for_unknown_status_code():18 assert http3.codes.get_reason_phrase(499) == ""18 assert httpx.codes.get_reason_phrase(499) == ""
modified:tests/test_timeouts.py+1 added-1 removed
1import pytest23from http3 import (3from httpx import (4 AsyncClient,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,
46 unmodified lines
modified:tests/test_utils.py+1 added-1 removed
1import pytest23from http3.utils import guess_json_utf3from httpx.utils import guess_json_utf456@pytest.mark.parametrize(7 "encoding",
32 unmodified lines
modified:tests/test_wsgi.py+5 added-5 removed
1import sys23import pytest45import http35import httpx678def hello_world(environ, start_response):9 status = "200 OK"
58 unmodified lines
68 return [output]697071def test_wsgi():72 client = http3.Client(app=hello_world)72 client = httpx.Client(app=hello_world)73 response = client.get("http://www.example.org/")74 assert response.status_code == 20075 assert response.text == "Hello, World!"767778def test_wsgi_upload():79 client = http3.Client(app=echo_body)79 client = httpx.Client(app=echo_body)80 response = client.post("http://www.example.org/", data=b"example")81 assert response.status_code == 20082 assert response.text == "example"838485def test_wsgi_upload_with_response_stream():86 client = http3.Client(app=echo_body_with_response_stream)86 client = httpx.Client(app=echo_body_with_response_stream)87 response = client.post("http://www.example.org/", data=b"example")88 assert response.status_code == 20089 assert response.text == "example"909192def test_wsgi_exc():93 client = http3.Client(app=raise_exc)93 client = httpx.Client(app=raise_exc)94 with pytest.raises(ValueError):95 client.get("http://www.example.org/")
modified:mkdocs.yml+4 added-4 removed
1site_name: HTTP32site_description: The next generation HTTP client.1site_name: HTTPX2site_description: A next-generation HTTP client for Python.34theme:5 name: 'material'67repo_name: encode/http38repo_url: https://github.com/encode/http37repo_name: encode/httpx8repo_url: https://github.com/encode/httpx9edit_uri: ""1011nav:12 - Introduction: 'index.md'
10 unmodified lines
modified:README.md+24 added-24 removed
1# HTTP31# HTTPX23<a href="https://travis-ci.org/encode/http3">4 <img src="https://travis-ci.org/encode/http3.svg?branch=master" alt="Build Status">3<a href="https://travis-ci.org/encode/httpx">4 <img src="https://travis-ci.org/encode/httpx.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">6<a href="https://codecov.io/gh/encode/httpx">7 <img src="https://codecov.io/gh/encode/httpx/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">9<a href="https://pypi.org/project/httpx/">10 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">11</a>1213HTTP3 is a next-generation HTTP client for Python 3.13HTTPX is a next-generation HTTP client for Python 3.1415**Note**: *This project should be considered as an "alpha" release. It is substantially API complete, but there are still some areas that need more work.*1617---1819Let's get started...2021```python22>>> import http323>>> r = http3.get('https://www.example.org/')22>>> import httpx23>>> r = httpx.get('https://www.example.org/')24>>> r25<Response [200 OK]>26>>> r.status_code27200
6 unmodified lines
34```3536## Features3738HTTP3 builds on the well-established usability of `requests`, and gives you:38HTTPX 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](https://www.encode.io/http3/parallel/). *(Coming soon)*43* Standard synchronous interface, but [with `async`/`await` support if you need it](https://www.encode.io/http3/async/).44* Ability to [make requests directly to WSGI or ASGI applications](https://www.encode.io/http3/advanced/#calling-into-python-web-apps).42* Support for [issuing HTTP requests in parallel](https://www.encode.io/httpx/parallel/). *(Coming soon)*43* Standard synchronous interface, but [with `async`/`await` support if you need it](https://www.encode.io/httpx/async/).44* Ability to [make requests directly to WSGI or ASGI applications](https://www.encode.io/httpx/advanced/#calling-into-python-web-apps).45* Strict timeouts everywhere.46* Fully type annotated.47* 100% test coverage.48
19 unmodified lines
6869Install with pip:7071```shell72$ pip install http372$ pip install httpx73```7475HTTP3 requires Python 3.6+75httpx requires Python 3.6+7677## Documentation7879Project documentation is available at [www.encode.io/http3/](https://www.encode.io/http3/).79Project documentation is available at [www.encode.io/httpx/](https://www.encode.io/httpx/).8081For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/http3/quickstart/).81For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/httpx/quickstart/).8283For more advanced topics, see the [Advanced Usage](https://www.encode.io/http3/advanced/) section, or84the specific topics on making [Parallel Requests](https://www.encode.io/http3/parallel/) or using the85[Async Client](https://www.encode.io/http3/async/).83For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section, or84the specific topics on making [Parallel Requests](https://www.encode.io/httpx/parallel/) or using the85[Async Client](https://www.encode.io/httpx/async/).8687The [Developer Interface](https://www.encode.io/http3/api/) provides a comprehensive API reference.87The [Developer Interface](https://www.encode.io/httpx/api/) provides a comprehensive API reference.8889## Dependencies9091The HTTP3 project relies on these excellent libraries:91The httpx project relies on these excellent libraries:9293* `h2` - HTTP/2 support.94* `h11` - HTTP/1.1 support.95* `certifi` - SSL certificates.
6 unmodified lines
102much of this work follows, as well as to `urllib3` for plenty of design103inspiration around the lower level networking details.104105<p align="center">&mdash; ⭐️ &mdash;</p>106<p align="center"><i>HTTP3 is <a href="https://github.com/encode/http3/blob/master/LICENSE.md">BSD licensed</a> code. Designed & built in Brighton, England.</i></p>106<p align="center"><i>httpx is <a href="https://github.com/encode/httpx/blob/master/LICENSE.md">BSD licensed</a> code. Designed & built in Brighton, England.</i></p>