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
Provenance
- Commit
2d09d5b- Tree
10368e6- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
0e8dae4
83 files changed+5230 added−5218 removed
added:docs/img/logo.jpgbinary
A binary file, added.
modified:docs/advanced.md+5 added-5 removed
5 unmodified lines67891010111213141516171818192021222323242526272829303031323334353637383939404142435 unmodified lineswill provide cookie persistence, and allows you to apply configuration acrossall outgoing requests.
```python>>> client = http3.Client()>>> client = httpx.Client()>>> r = client.get('https://example.org/')>>> r<Response [200 OK]>```
## Calling into Python Web Apps
You can configure an `http3` client to call directly into a Python webYou can configure an `httpx` client to call directly into a Python webapplication, using either the WSGI or ASGI protocol.
This is particularly useful for two main use-cases:
* Using `http3` as a client, inside test cases.* Using `httpx` as a client, inside test cases.* Mocking out external services, during tests or in dev/staging environments.
Here's an example of integrating against a Flask application:
```pythonfrom flask import Flaskimport http3import httpx
app = Flask(__name__)
@app.route("/")def hello(): return "Hello World!"
client = http3.Client(app=app)client = httpx.Client(app=app)r = client.get('http://example/')assert r.status_code == 200assert r.text == "Hello World!"```modified:docs/api.md+2 added-2 removed
14 unmodified lines1516171819192021222338 unmodified lines6263646566666768697076 unmodified lines14 unmodified lines
*An HTTP client, with connection pooling, redirects, cookie persistence, etc.*
```python>>> client = http3.Client()>>> client = httpx.Client()>>> response = client.get('https://example.org')```
* `def __init__([auth], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [app], [dispatch])`38 unmodified lines*An HTTP request. Can be constructed explicitly for more control over exactlywhat gets sent over the wire.*
```python>>> request = http3.Request("GET", "https://example.org", headers={'host': 'example.org'})>>> request = httpx.Request("GET", "https://example.org", headers={'host': 'example.org'})>>> response = client.send(request)```
* `def __init__(method, url, [params], [data], [json], [headers], [cookies])`76 unmodified linesmodified:docs/async.md+4 added-4 removed
1 # Async Client2 3-HTTP3 offers a standard synchronous API by default, but also gives you3+HTTPX offers a standard synchronous API by default, but also gives you4 the option of an async client if you need it.5 6 Async is a concurrency model that is far more efficient than multi-threading,7 and can provide significant performance benefits and enable the use of6 unmodified lines14 15 To make asynchronous requests, you'll need an `AsyncClient`.16 17 ```python18->>> client = http3.AsyncClient()18+>>> client = httpx.AsyncClient()19 >>> r = await client.get('https://www.example.com/')20 ```21 22 ## API Differences1 unmodified line24 If you're using streaming responses then there are a few bits of API that25 use async methods:26 27 ```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 lines43 44 If you're making parallel requests, then you'll also need to use an async API:45 46 ```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 linesmodified:docs/compatibility.md+2 added-2 removed
1 # Requests Compatibility Guide2 3-HTTP3 aims to be compatible with the `requests` API wherever possible.3+HTTPX aims to be compatible with the `requests` API wherever possible.4 5 This documentation outlines places where the API differs...6 7 ## QuickStart1 unmodified line9 Pretty much all the API mentioned in the `requests` QuickStart should be identical10 to the API in our own documentation. The following exceptions apply:11 12 * `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`,14 but 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.16 17 ## Advanced Usage3 unmodified linesmodified: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>4 5+<h1 align="center" style="font-size: 3rem; margin: -15px 0">6+HTTPX7+</h1>8+9+---10+11+<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 line18 </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>23 13-HTTP3 is a next-generation HTTP client for Python 3.24+<em>A next-generation HTTP client for Python.</em>25+</div>26 27 !!! 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 lines32 33 Let's get started...34 35 ```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_code41 2006 unmodified lines48 ```49 50 ## Features51 40-HTTP3 builds on the well-established usability of `requests`, and gives you:52+HTTPX builds on the well-established usability of `requests`, and gives you:53 54 * 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 lines89 The [Developer Interface](api.md) provides a comprehensive API reference.90 91 ## Dependencies92 81-The HTTP3 project relies on these excellent libraries:93+The HTTPX project relies on these excellent libraries:94 95 * `h2` - HTTP/2 support.96 * `h11` - HTTP/1.1 support.97 * `certifi` - SSL certificates.10 unmodified lines108 109 Install with pip:110 111 ```shell100-$ pip install http3112+$ pip install httpx113 ```114 103-HTTP3 requires Python 3.6+115+HTTPX requires Python 3.6+modified:docs/parallel.md+6 added-6 removed
1 # Parallel Requests2 3 !!! 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.7 8-HTTP3 allows you to make HTTP requests in parallel in a highly efficient way,8+HTTPX allows you to make HTTP requests in parallel in a highly efficient way,9 using async under the hood, while still presenting a standard threaded interface.10 11 This has the huge benefit of allowing you to efficiently make parallel HTTP12 requests without having to switch out to using async all the way through.2 unmodified lines15 16 Let's make two outgoing HTTP requests in parallel:17 18 ```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 lines27 responses sequentially, but rather deal with each response that comes back28 as soon as it's available:29 30 ```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 lines48 control the authentication or dispatch behaviour for all requests within the49 block.50 51 ```python52->>> client = http3.Client()52+>>> client = httpx.Client()53 >>> with client.parallel() as parallel:54 >>> ...55 ```56 2 unmodified lines59 If you're working within an async framework, then you'll want to use a fully60 async API for making requests.61 62 ```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 linesmodified:docs/quickstart.md+36 added-36 removed
1 # QuickStart2 3 !!! 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.7 8-First start by importing HTTP3:8+First start by importing HTTPX:9 10 ```11->>> import http311+>>> import httpx12 ```13 14 Now, let’s try to get a webpage.15 16 ```python17->>> r = http3.get('https://httpbin.org/get')17+>>> r = httpx.get('https://httpbin.org/get')18 >>> r19 <Response [200 OK]>20 ```21 22 Similarly, to make an HTTP POST request:23 24 ```python25->>> r = http3.post('https://httpbin.org/post', data={'key': 'value'})25+>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})26 ```27 28 The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:29 30 ```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 ```36 37 ## Passing Parameters in URLs38 39 To include URL query parameters in the request, use the `params` keyword:40 41 ```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 ```45 46 To see how the values get encoding into the URL string, we can inspect the47 resulting URL that was used to make the request:6 unmodified lines54 You can also pass a list of items as a value:55 56 ```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.url60 URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')61 ```62 63 ## Response Content64 65-HTTP3 will automatically handle decoding the response content into unicode text.65+HTTPX will automatically handle decoding the response content into unicode text.66 67 ```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 lines109 110 Often Web API responses will be encoded as JSON.111 112 ```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 lines121 122 ```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 ```127 128 ## Sending Form Encoded Data129 2 unmodified lines132 which is used for HTML forms.133 134 ```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 lines148 Form encoded data can also include multiple values form a given key.149 150 ```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 lines168 You can also upload files, using HTTP multipart encoding:169 170 ```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 lines184 of items for the file value:185 186 ```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 lines202 For more complicated data structures you'll often want to use JSON encoding instead.203 204 ```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 lines232 233 We can inspect the HTTP status code of the response:234 235 ```python236->>> r = http3.get('https://httpbin.org/get')236+>>> r = httpx.get('https://httpbin.org/get')237 >>> r.status_code238 200239 ```240 241-HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.241+HTTPX also includes an easy shortcut for accessing status codes by their text phrase.242 243 ```python244->>> r.status_code == http3.codes.OK244+>>> r.status_code == httpx.codes.OK245 True246 ```247 248 We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):249 250 ```python251->>> not_found = http3.get('https://httpbin.org/status/404')251+>>> not_found = httpx.get('https://httpbin.org/status/404')252 >>> not_found.status_code253 404254 >>> not_found.raise_for_status()255 Traceback (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)258-http3.exceptions.HttpError: 404 Not Found258+httpx.exceptions.HttpError: 404 Not Found259 ```260 261 Any successful response codes will simply return `None` rather than raising an exception.262 37 unmodified lines300 301 Any cookies that are set on the response can be easily accessed:302 303 ```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 ```308 309 To include cookies in an outgoing request, use the `cookies` parameter:310 311 ```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 ```317 318 Cookies are returned in a `Cookies` instance, which is a dict-like data structure319 with additional API for accessing cookies by their domain or path.320 321 ```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 ```329 330 ## Redirection and History331 332-By default HTTP3 will follow redirects for anything except `HEAD` requests.332+By default HTTPX will follow redirects for anything except `HEAD` requests.333 334 The `history` property of the response can be used to inspect any followed redirects.335 It contains a list of all any redirect responses that were followed, in the order336 in which they were made.337 338 For example, GitHub redirects all HTTP requests to HTTPS.339 340 ```python341->>> r = http3.get('http://github.com/')341+>>> r = httpx.get('http://github.com/')342 >>> r.url343 URL('https://github.com/')344 >>> r.status_code345 2003 unmodified lines349 350 You can modify the default redirection handling with the allow_redirects parameter:351 352 ```python353->>> r = http3.get('http://github.com/', allow_redirects=False)353+>>> r = httpx.get('http://github.com/', allow_redirects=False)354 >>> r.status_code355 301356 >>> r.history357 []1 unmodified line359 360 If you’re making a `HEAD` request, you can use this to enable redirection:361 362 ```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 ```369 370 ## Timeouts371 372-HTTP3 defaults to including reasonable timeouts for all network operations,372+HTTPX defaults to including reasonable timeouts for all network operations,373 meaning that if a connection is not properly established then it should always374 raise an error rather than hanging indefinitely.375 376 The default timeout for network inactivity is five seconds. You can modify the377 value to be more or less strict:378 379 ```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-"""2-Dispatch classes handle the raw network connections and the implementation3-details of making the HTTP request and receiving the response.4-"""deleted:http3/dispatch/asgi.py-187 removed
1-import asyncio2-import typing3-4-from ..config import CertTypes, TimeoutTypes, VerifyTypes5-from ..interfaces import AsyncDispatcher6-from ..models import AsyncRequest, AsyncResponse7-8-9-class ASGIDispatch(AsyncDispatcher):10- """11- A custom dispatcher that handles sending requests directly to an ASGI app.12-13- 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:16-17- ```18- client = http3.Client(app=app)19- ```20-21- Alternatively, you can setup the dispatch instance explicitly.22- This allows you to include any additional configuration arguments specific23- to the ASGIDispatch class:24-25- ```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- """34-35- 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 = client46-47- async def send(48- self,49- request: AsyncRequest,50- verify: VerifyTypes = None,51- cert: CertTypes = None,52- timeout: TimeoutTypes = None,53- ) -> AsyncResponse:54-55- scope = {56- "type": "http",57- "asgi": {"version": "3.0"},58- "http_version": "1.1",59- "method": request.method,60- "headers": request.headers.raw,61- "scheme": request.url.scheme,62- "path": request.url.path,63- "query_string": request.url.query.encode("ascii"),64- "server": request.url.host,65- "client": self.client,66- "root_path": self.root_path,67- }68- app = self.app69- app_exc = None70- status_code = None71- headers = None72- response_started = asyncio.Event()73- response_body = BodyIterator()74- request_stream = request.stream()75-76- async def receive() -> dict:77- nonlocal request_stream78-79- 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}84-85- async def send(message: dict) -> None:86- nonlocal status_code, headers, response_started, response_body, request87-88- 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()99-100- 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()108-109- # 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())117-118- tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]119-120- await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)121-122- if app_exc is not None and self.raise_app_exceptions:123- raise app_exc124-125- assert response_started.is_set(), "application did not return a response."126- assert status_code is not None127- assert headers is not None128-129- 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_exc135-136- 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- )144-145-146-class BodyIterator:147- """148- Provides a byte-iterator interface that the client can use to149- ingest the response content from.150- """151-152- def __init__(self) -> None:153- self._queue = asyncio.Queue(154- maxsize=1155- ) # type: asyncio.Queue[typing.Union[bytes, object]]156- self._done = object()157-158- 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 data168-169- 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 cover176-177- 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)182-183- 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
1-import typing2-3-from ..concurrency import AsyncioBackend4-from ..config import (5- DEFAULT_POOL_LIMITS,6- DEFAULT_TIMEOUT_CONFIG,7- CertTypes,8- PoolLimits,9- TimeoutTypes,10- VerifyTypes,11-)12-from ..exceptions import NotConnected13-from ..interfaces import AsyncDispatcher, ConcurrencyBackend14-from ..models import AsyncRequest, AsyncResponse, Origin15-from .connection import HTTPConnection16-17-CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]18-19-20-class ConnectionStore:21- """22- We need to maintain collections of connections in a way that allows us to:23-24- * Lookup connections by origin.25- * Iterate over connections by insertion time.26- * Return the total number of connections.27- """28-29- 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]]34-35- 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 None42-43- connection = next(reversed(list(connections.keys())))44- if http2_only and not connection.is_http2:45- return None46-47- del connections[connection]48- if not connections:49- del self.by_origin[origin]50- del self.all[connection]51-52- return connection53-54- 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}60-61- 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]66-67- def clear(self) -> None:68- self.all.clear()69- self.by_origin.clear()70-71- def __iter__(self) -> typing.Iterator[HTTPConnection]:72- return iter(self.all.keys())73-74- def __len__(self) -> int:75- return len(self.all)76-77-78-class 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 = False93-94- self.keepalive_connections = ConnectionStore()95- self.active_connections = ConnectionStore()96-97- self.backend = AsyncioBackend() if backend is None else backend98- self.max_connections = self.backend.get_semaphore(pool_limits)99-100- @property101- def num_connections(self) -> int:102- return len(self.keepalive_connections) + len(self.active_connections)103-104- 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 exc129-130- return response131-132- 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)140-141- 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- )151-152- self.active_connections.add(connection)153-154- return connection155-156- 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)170-171- 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
1-import functools2-import typing3-4-from ..concurrency import AsyncioBackend5-from ..config import (6- DEFAULT_TIMEOUT_CONFIG,7- CertTypes,8- SSLConfig,9- TimeoutConfig,10- TimeoutTypes,11- VerifyTypes,12-)13-from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol14-from ..models import AsyncRequest, AsyncResponse, Origin15-from .http2 import HTTP2Connection16-from .http11 import HTTP11Connection17-18-# Callback signature: async def callback(conn: HTTPConnection) -> None19-ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]20-21-22-class 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]39-40- 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)49-50- 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)55-56- return response57-58- 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)66-67- host = self.origin.host68- port = self.origin.port69- ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None70-71- if self.release_func is None:72- on_release = None73- else:74- on_release = functools.partial(self.release_func, self)75-76- 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- )87-88- 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()93-94- @property95- def is_http2(self) -> bool:96- return self.h2_connection is not None97-98- @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_closeddeleted:http3/dispatch/http11.py-190 removed
1-import typing2-3-import h114-5-from ..concurrency import TimeoutFlag6-from ..config import TimeoutConfig, TimeoutTypes7-from ..exceptions import NotConnected8-from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9-from ..models import AsyncRequest, AsyncResponse10-11-H11Event = typing.Union[12- h11.Request,13- h11.Response,14- h11.InformationalResponse,15- h11.Data,16- h11.EndOfMessage,17- h11.ConnectionClosed,18-]19-20-21-# Callback signature: async def callback() -> None22-# In practice the callback will be a functools partial, which binds23-# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.24-OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]25-26-27-class HTTP11Connection:28- READ_NUM_BYTES = 409629-30- 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()43-44- async def send(45- self, request: AsyncRequest, timeout: TimeoutTypes = None46- ) -> AsyncResponse:47- timeout = None if timeout is None else TimeoutConfig(timeout)48-49- 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 None55-56- 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)60-61- 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- )69-70- 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()78-79- 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)90-91- 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)102-103- # 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()114-115- 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)122-123- 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)141-142- 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- break155-156- 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 event173-174- 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()184-185- if self.on_release is not None:186- await self.on_release()187-188- @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
1-import functools2-import typing3-4-import h2.connection5-import h2.events6-7-from ..concurrency import TimeoutFlag8-from ..config import TimeoutConfig, TimeoutTypes9-from ..exceptions import NotConnected10-from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11-from ..models import AsyncRequest, AsyncResponse12-13-14-class HTTP2Connection:15- READ_NUM_BYTES = 409616-17- 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 = False32-33- async def send(34- self, request: AsyncRequest, timeout: TimeoutTypes = None35- ) -> AsyncResponse:36- timeout = None if timeout is None else TimeoutConfig(timeout)37-38- # Start sending the request.39- if not self.initialized:40- self.initiate_connection()41-42- try:43- stream_id = await self.send_headers(request, timeout)44- except ConnectionResetError:45- raise NotConnected() from None46-47- self.events[stream_id] = []48- self.timeout_flags[stream_id] = TimeoutFlag()49-50- 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)55-56- 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- )64-65- async def close(self) -> None:66- await self.writer.close()67-68- 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 = True73-74- 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_id88-89- 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()102-103- 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)113-114- 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)118-119- 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- break132-133- 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)141-142- 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- break152-153- 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)163-164- data_to_send = self.h2_state.data_to_send()165- await self.writer.write(data_to_send, timeout)166-167- return self.events[stream_id].pop(0)168-169- async def response_closed(self, stream_id: int) -> None:170- del self.events[stream_id]171- del self.timeout_flags[stream_id]172-173- if not self.events and self.on_release is not None:174- await self.on_release()175-176- @property177- def is_closed(self) -> bool:178- return Falsedeleted:http3/dispatch/threaded.py-96 removed
1-from ..config import CertTypes, TimeoutTypes, VerifyTypes2-from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3-from ..models import (4- AsyncRequest,5- AsyncRequestData,6- AsyncResponse,7- AsyncResponseContent,8- Request,9- RequestData,10- Response,11- ResponseContent,12-)13-14-15-class 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- """21-22- def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23- self.sync_dispatcher = dispatch24- self.backend = backend25-26- 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.backend34-35- data = getattr(request, "content", getattr(request, "content_aiter", None))36- sync_data = self._sync_request_data(data)37-38- sync_request = Request(39- method=request.method,40- url=request.url,41- headers=request.headers,42- data=sync_data,43- )44-45- 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)54-55- content = getattr(56- sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57- )58-59- async_content = self._async_response_content(content)60-61- async def async_on_close() -> None:62- nonlocal concurrency_backend, sync_response63- await concurrency_backend.run_in_threadpool(sync_response.close)64-65- 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- )74-75- 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)82-83- def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:84- if isinstance(content, bytes):85- return content86-87- # 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)91-92- def _sync_request_data(self, data: AsyncRequestData) -> RequestData:93- if isinstance(data, bytes):94- return data95-96- return self.backend.iterate(data)deleted:http3/dispatch/wsgi.py-154 removed
1-import io2-import typing3-4-from ..config import CertTypes, TimeoutTypes, VerifyTypes5-from ..interfaces import Dispatcher6-from ..models import Request, Response7-8-9-class WSGIDispatch(Dispatcher):10- """11- A custom dispatcher that handles sending requests directly to an ASGI app.12-13- 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:16-17- ```18- client = http3.Client(app=app)19- ```20-21- Alternatively, you can setup the dispatch instance explicitly.22- This allows you to include any additional configuration arguments specific23- to the WSGIDispatch class:24-25- ```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- """34-35- 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_addr46-47- 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] = value75-76- seen_status = None77- seen_response_headers = None78- seen_exc_info = None79-80- 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_info87-88- result = self.app(environ, start_response)89-90- 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]94-95- 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- )102-103-104-class BodyStream(io.RawIOBase):105- def __init__(self, iterator: typing.Iterator[bytes]) -> None:106- self._iterator = iterator107- self._buffer = b""108- self._closed = False109-110- def read(self, size: int = -1) -> bytes:111- if self._closed:112- return b""113-114- if size == -1:115- return self.readall()116-117- try:118- while len(self._buffer) < size:119- self._buffer += next(self._iterator)120- except StopIteration:121- self._closed = True122- return self._buffer123-124- output = self._buffer[:size]125- self._buffer = self._buffer[size:]126- return output127-128- def readall(self) -> bytes:129- if self._closed:130- raise OSError("Stream closed") # pragma: nocover131-132- for chunk in self._iterator:133- self._buffer += chunk134-135- self._closed = True136- return self._buffer137-138- def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover139- output = self.read(len(b))140- count = len(output)141- b[:count] = output142- return count143-144- def write(self, b: bytes) -> int:145- raise OSError("Operation not supported") # pragma: nocover146-147- def fileno(self) -> int:148- raise OSError("Operation not supported") # pragma: nocover149-150- def seek(self, offset: int, whence: int = 0) -> int:151- raise OSError("Operation not supported") # pragma: nocover152-153- def truncate(self, size: int = None) -> int:154- raise OSError("Operation not supported") # pragma: nocoverdeleted:http3/__init__.py-131 removed
1-from .__version__ import __description__, __title__, __version__2-from .api import delete, get, head, options, patch, post, put, request3-from .client import AsyncClient, Client4-from .concurrency import AsyncioBackend5-from .config import (6- USER_AGENT,7- CertTypes,8- PoolLimits,9- SSLConfig,10- TimeoutConfig,11- TimeoutTypes,12- VerifyTypes,13-)14-from .dispatch.connection import HTTPConnection15-from .dispatch.connection_pool import ConnectionPool16-from .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-)33-from .interfaces import (34- AsyncDispatcher,35- BaseReader,36- BaseWriter,37- ConcurrencyBackend,38- Dispatcher,39- Protocol,40-)41-from .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-)62-from .status_codes import StatusCode, codes63-64-__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
1-import typing2-3-from .client import Client4-from .config import CertTypes, TimeoutTypes, VerifyTypes5-from .models import (6- AuthTypes,7- CookieTypes,8- HeaderTypes,9- QueryParamTypes,10- RequestData,11- RequestFiles,12- Response,13- URLTypes,14-)15-16-17-def 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- )53-54-55-def 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- )81-82-83-def 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- )109-110-111-def 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- )137-138-139-def 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- )171-172-173-def 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- )205-206-207-def 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- )239-240-241-def 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
1-import typing2-from base64 import b64encode3-4-from .models import AsyncRequest5-6-7-class AuthBase:8- """9- Base class that all auth implementations derive from.10- """11-12- def __call__(self, request: AsyncRequest) -> AsyncRequest:13- raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover14-15-16-class 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 = password22-23- def __call__(self, request: AsyncRequest) -> AsyncRequest:24- request.headers["Authorization"] = self.build_auth_header()25- return request26-27- def build_auth_header(self) -> str:28- username, password = self.username, self.password29-30- if isinstance(username, str):31- username = username.encode("latin1")32-33- if isinstance(password, str):34- password = password.encode("latin1")35-36- userpass = b":".join((username, password))37- token = b64encode(userpass).decode().strip()38- return f"Basic {token}"deleted:http3/client.py-895 removed
1-import inspect2-import typing3-from types import TracebackType4-5-from .auth import HTTPBasicAuth6-from .concurrency import AsyncioBackend7-from .config import (8- DEFAULT_MAX_REDIRECTS,9- DEFAULT_POOL_LIMITS,10- DEFAULT_TIMEOUT_CONFIG,11- CertTypes,12- PoolLimits,13- TimeoutTypes,14- VerifyTypes,15-)16-from .dispatch.asgi import ASGIDispatch17-from .dispatch.connection_pool import ConnectionPool18-from .dispatch.threaded import ThreadedDispatcher19-from .dispatch.wsgi import WSGIDispatch20-from .exceptions import (21- InvalidURL,22- RedirectBodyUnavailable,23- RedirectLoop,24- TooManyRedirects,25-)26-from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher27-from .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-)45-from .status_codes import codes46-47-48-class 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()66-67- 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- )78-79- 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 = dispatch91-92- if base_url is None:93- self.base_url = URL("", allow_relative=True)94- else:95- self.base_url = URL(base_url)96-97- self.auth = auth98- self.cookies = Cookies(cookies)99- self.max_redirects = max_redirects100- self.dispatch = async_dispatch101- self.concurrency_backend = backend102-103- 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 cookies111-112- 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.auth125-126- url = request.url127-128- if url.scheme not in ("http", "https"):129- raise InvalidURL('URL scheme must be "http" or "https".')130-131- if auth is None and (url.username or url.password):132- auth = HTTPBasicAuth(username=url.username, password=url.password)133-134- if auth is not None:135- if isinstance(auth, tuple):136- auth = HTTPBasicAuth(username=auth[0], password=auth[1])137- request = auth(request)138-139- response = await self.send_handling_redirects(140- request,141- verify=verify,142- cert=cert,143- timeout=timeout,144- allow_redirects=allow_redirects,145- )146-147- if not stream:148- try:149- await response.read()150- finally:151- await response.close()152-153- return response154-155- 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 = []167-168- 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()175-176- 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]185-186- 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()194-195- if response.is_redirect:196-197- 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 response210-211- response.next = send_next # type: ignore212-213- return response214-215- 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- )226-227- 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.method233-234- # https://tools.ietf.org/html/rfc7231#section-6.4.4235- if response.status_code == codes.SEE_OTHER and method != "HEAD":236- method = "GET"237-238- # 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"242-243- # 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"247-248- return method249-250- 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"]255-256- url = URL(location, allow_relative=True)257-258- # 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)262-263- # 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)266-267- return url268-269- 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 headers278-279- 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.content288-289-290-class 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- )318-319- 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- )346-347- 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- )374-375- 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- )408-409- 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- )442-443- 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- )476-477- 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- )510-511- 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 response551-552- async def close(self) -> None:553- await self.dispatch.close()554-555- async def __aenter__(self) -> "AsyncClient":556- return self557-558- 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()565-566-567-class 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 data577-578- # 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)582-583- def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:584- if isinstance(data, bytes):585- return data586-587- # 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)591-592- 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_backend623-624- 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)635-636- content = getattr(637- async_response, "_raw_content", getattr(async_response, "_raw_stream", None)638- )639-640- sync_content = self._sync_data(content)641-642- def sync_on_close() -> None:643- nonlocal concurrency_backend, async_response644- concurrency_backend.run(async_response.on_close)645-646- 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 response661-662- 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- )689-690- 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- )717-718- 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- )745-746- 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- )779-780- 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- )813-814- 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- )847-848- 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- )881-882- def close(self) -> None:883- coroutine = self.dispatch.close884- self.concurrency_backend.run(coroutine)885-886- def __enter__(self) -> "Client":887- return self888-889- 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-"""2-The `Reader` and `Writer` classes here provide a lightweight layer over3-`asyncio.StreamReader` and `asyncio.StreamWriter`.4-5-Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6-7-These classes help encapsulate the timeout logic, make it easier to unit-test8-protocols, and help keep the rest of the package more `async`/`await`9-based, and less strictly `asyncio`-specific.10-"""11-import asyncio12-import functools13-import ssl14-import typing15-from types import TracebackType16-17-from .config import PoolLimits, TimeoutConfig18-from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19-from .interfaces import (20- BaseBackgroundManager,21- BasePoolSemaphore,22- BaseReader,23- BaseWriter,24- ConcurrencyBackend,25- Protocol,26-)27-28-SSL_MONKEY_PATCH_APPLIED = False29-30-31-def ssl_monkey_patch() -> None:32- """33- Monky-patch for https://bugs.python.org/issue3670934-35- This prevents console errors when outstanding HTTPS connections36- still exist at the point of exiting.37-38- 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: ignore42-43- _write = MonkeyPatch.write44-45- def _fixed_write(self, data: bytes) -> None: # type: ignore46- if self._loop and not self._loop.is_closed():47- _write(self, data)48-49- MonkeyPatch.write = _fixed_write50-51-52-class TimeoutFlag:53- """54- A timeout flag holds a state of either read-timeout or write-timeout mode.55-56- We use this so that we can attempt both reads and writes concurrently, while57- only enforcing timeouts in one direction.58-59- During a request/response cycle we start in write-timeout mode.60-61- Once we've sent a request fully, or once we start seeing a response,62- then we switch to read-timeout mode instead.63- """64-65- def __init__(self) -> None:66- self.raise_on_read_timeout = False67- self.raise_on_write_timeout = True68-69- 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 = False75-76- 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 = True82-83-84-class Reader(BaseReader):85- def __init__(86- self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87- ) -> None:88- self.stream_reader = stream_reader89- self.timeout = timeout90-91- async def read(92- self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93- ) -> bytes:94- if timeout is None:95- timeout = self.timeout96-97- 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 None108-109- return data110-111-112-class Writer(BaseWriter):113- def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):114- self.stream_writer = stream_writer115- self.timeout = timeout116-117- def write_no_block(self, data: bytes) -> None:118- self.stream_writer.write(data) # pragma: nocover119-120- async def write(121- self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None122- ) -> None:123- if not data:124- return125-126- if timeout is None:127- timeout = self.timeout128-129- 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 None143-144- async def close(self) -> None:145- self.stream_writer.close()146-147-148-class PoolSemaphore(BasePoolSemaphore):149- def __init__(self, pool_limits: PoolLimits):150- self.pool_limits = pool_limits151-152- @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._semaphore161-162- async def acquire(self) -> None:163- if self.semaphore is None:164- return165-166- timeout = self.pool_limits.pool_timeout167- try:168- await asyncio.wait_for(self.semaphore.acquire(), timeout)169- except asyncio.TimeoutError:170- raise PoolTimeout()171-172- def release(self) -> None:173- if self.semaphore is None:174- return175-176- self.semaphore.release()177-178-179-class AsyncioBackend(ConcurrencyBackend):180- def __init__(self) -> None:181- global SSL_MONKEY_PATCH_APPLIED182-183- if not SSL_MONKEY_PATCH_APPLIED:184- ssl_monkey_patch()185- SSL_MONKEY_PATCH_APPLIED = True186-187- @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._loop195-196- 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()210-211- 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()218-219- 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_11222-223- return (reader, writer, protocol)224-225- 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)232-233- 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 = loop243-244- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:245- return PoolSemaphore(limits)246-247- def background_manager(248- self, coroutine: typing.Callable, args: typing.Any249- ) -> "BackgroundManager":250- return BackgroundManager(coroutine, args)251-252-253-class BackgroundManager(BaseBackgroundManager):254- def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:255- self.coroutine = coroutine256- self.args = args257-258- async def __aenter__(self) -> "BackgroundManager":259- loop = asyncio.get_event_loop()260- self.task = loop.create_task(self.coroutine(*self.args))261- return self262-263- 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
1-import asyncio2-import os3-import ssl4-import typing5-6-import certifi7-8-from .__version__ import __version__9-10-CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11-VerifyTypes = typing.Union[str, bool]12-TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]13-14-15-USER_AGENT = f"python-http3/{__version__}"16-17-DEFAULT_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-)35-36-37-class SSLConfig:38- """39- SSL Configuration.40- """41-42- def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43- self.cert = cert44- self.verify = verify45-46- self.ssl_context: typing.Optional[ssl.SSLContext] = None47-48- 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- )54-55- def __repr__(self) -> str:56- class_name = self.__class__.__name__57- return f"{class_name}(cert={self.cert}, verify={self.verify})"58-59- 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)67-68- 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- )78-79- assert self.ssl_context is not None80- return self.ssl_context81-82- 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 context90-91- 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- )104-105- context = self._create_default_ssl_context()106- context.verify_mode = ssl.CERT_REQUIRED107- context.check_hostname = True108-109- # 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- pass115-116- # 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- pass122-123- 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)127-128- 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- )139-140- return context141-142- 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)152-153- 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"])157-158- return context159-160-161-class TimeoutConfig:162- """163- Timeout values.164- """165-166- 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 = timeout195-196- 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- )203-204- 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- )212-213-214-class PoolLimits:215- """216- Limits on the number of connections in a connection pool.217- """218-219- 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_timeout229-230- 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- )237-238- 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- )244-245-246-DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)247-DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)248-DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)249-DEFAULT_CA_BUNDLE_PATH = certifi.where()250-DEFAULT_MAX_REDIRECTS = 20deleted:http3/decoders.py-149 removed
1-"""2-Handlers for Content-Encoding.3-4-See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5-"""6-import typing7-import zlib8-9-from .exceptions import DecodingError10-11-try:12- import brotli13-except ImportError: # pragma: nocover14- brotli = None15-16-17-class Decoder:18- def decode(self, data: bytes) -> bytes:19- raise NotImplementedError() # pragma: nocover20-21- def flush(self) -> bytes:22- raise NotImplementedError() # pragma: nocover23-24-25-class IdentityDecoder(Decoder):26- """27- Handle unencoded data.28- """29-30- def decode(self, data: bytes) -> bytes:31- return data32-33- def flush(self) -> bytes:34- return b""35-36-37-class DeflateDecoder(Decoder):38- """39- Handle 'deflate' decoding.40-41- See: https://stackoverflow.com/questions/183869942- """43-44- def __init__(self) -> None:45- self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)46-47- def decode(self, data: bytes) -> bytes:48- try:49- return self.decompressor.decompress(data)50- except zlib.error as exc:51- raise DecodingError from exc52-53- def flush(self) -> bytes:54- try:55- return self.decompressor.flush()56- except zlib.error as exc: # pragma: nocover57- raise DecodingError from exc58-59-60-class GZipDecoder(Decoder):61- """62- Handle 'gzip' decoding.63-64- See: https://stackoverflow.com/questions/183869965- """66-67- def __init__(self) -> None:68- self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)69-70- def decode(self, data: bytes) -> bytes:71- try:72- return self.decompressor.decompress(data)73- except zlib.error as exc:74- raise DecodingError from exc75-76- def flush(self) -> bytes:77- try:78- return self.decompressor.flush()79- except zlib.error as exc: # pragma: nocover80- raise DecodingError from exc81-82-83-class BrotliDecoder(Decoder):84- """85- Handle 'brotli' decoding.86-87- Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/88- """89-90- 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()95-96- def decode(self, data: bytes) -> bytes:97- try:98- return self.decompressor.decompress(data)99- except brotli.Error as exc:100- raise DecodingError from exc101-102- def flush(self) -> bytes:103- try:104- self.decompressor.finish()105- return b""106- except brotli.Error as exc: # pragma: nocover107- raise DecodingError from exc108-109-110-class MultiDecoder(Decoder):111- """112- Handle the case where multiple encodings have been applied.113- """114-115- 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))122-123- def decode(self, data: bytes) -> bytes:124- for child in self.children:125- data = child.decode(data)126- return data127-128- def flush(self) -> bytes:129- data = b""130- for child in self.children:131- data = child.decode(data) + child.flush()132- return data133-134-135-SUPPORTED_DECODERS = {136- "identity": IdentityDecoder,137- "gzip": GZipDecoder,138- "deflate": DeflateDecoder,139- "br": BrotliDecoder,140-}141-142-143-if brotli is None:144- SUPPORTED_DECODERS.pop("br") # pragma: nocover145-146-147-ACCEPT_ENCODING = ", ".join(148- [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]149-)deleted:http3/exceptions.py-135 removed
1-# Timeout exceptions...2-3-4-class Timeout(Exception):5- """6- A base class for all timeouts.7- """8-9-10-class ConnectTimeout(Timeout):11- """12- Timeout while establishing a connection.13- """14-15-16-class ReadTimeout(Timeout):17- """18- Timeout while reading response data.19- """20-21-22-class WriteTimeout(Timeout):23- """24- Timeout while writing request data.25- """26-27-28-class PoolTimeout(Timeout):29- """30- Timeout while waiting to acquire a connection from the pool.31- """32-33-34-# HTTP exceptions...35-36-37-class NotConnected(Exception):38- """39- A connection was lost at the point of starting a request,40- prior to any writes succeeding.41- """42-43-44-class HttpError(Exception):45- """46- An HTTP error occurred.47- """48-49-50-class ProtocolError(Exception):51- """52- Malformed HTTP.53- """54-55-56-class DecodingError(Exception):57- """58- Decoding of the response failed.59- """60-61-62-# Redirect exceptions...63-64-65-class RedirectError(Exception):66- """67- Base class for HTTP redirect errors.68- """69-70-71-class TooManyRedirects(RedirectError):72- """73- Too many redirects.74- """75-76-77-class RedirectBodyUnavailable(RedirectError):78- """79- Got a redirect response, but the request body was streaming, and is80- no longer available.81- """82-83-84-class RedirectLoop(RedirectError):85- """86- Infinite redirect loop.87- """88-89-90-# Stream exceptions...91-92-93-class StreamException(Exception):94- """95- The base class for stream exceptions.96-97- The developer made an error in accessing the request stream in98- an invalid way.99- """100-101-102-class StreamConsumed(StreamException):103- """104- Attempted to read or stream response content, but the content has already105- been streamed.106- """107-108-109-class ResponseNotRead(StreamException):110- """111- Attempted to access response content, without having called `read()`112- after a streaming response.113- """114-115-116-class ResponseClosed(StreamException):117- """118- Attempted to read or stream response content, but the request has been119- closed.120- """121-122-123-# Other cases...124-125-126-class InvalidURL(Exception):127- """128- URL was missing a hostname, or was not one of HTTP/HTTPS.129- """130-131-132-class CookieConflict(Exception):133- """134- Attempted to lookup a cookie by name, but multiple cookies existed.135- """deleted:http3/interfaces.py-227 removed
1-import enum2-import ssl3-import typing4-from types import TracebackType5-6-from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7-from .models import (8- AsyncRequest,9- AsyncRequestData,10- AsyncResponse,11- HeaderTypes,12- QueryParamTypes,13- Request,14- RequestData,15- Response,16- URLTypes,17-)18-19-20-class Protocol(str, enum.Enum):21- HTTP_11 = "HTTP/1.1"22- HTTP_2 = "HTTP/2"23-24-25-class AsyncDispatcher:26- """27- Base class for async dispatcher classes, that handle sending the request.28-29- 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- """33-34- 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)48-49- 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: nocover57-58- async def close(self) -> None:59- pass # pragma: nocover60-61- async def __aenter__(self) -> "AsyncDispatcher":62- return self63-64- 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()71-72-73-class Dispatcher:74- """75- Base class for syncronous dispatcher classes, that handle sending the request.76-77- 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- """81-82- 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)96-97- 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: nocover105-106- def close(self) -> None:107- pass # pragma: nocover108-109- def __enter__(self) -> "Dispatcher":110- return self111-112- 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()119-120-121-class 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- """127-128- async def read(129- self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None130- ) -> bytes:131- raise NotImplementedError() # pragma: no cover132-133-134-class 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- """140-141- def write_no_block(self, data: bytes) -> None:142- raise NotImplementedError() # pragma: no cover143-144- async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:145- raise NotImplementedError() # pragma: no cover146-147- async def close(self) -> None:148- raise NotImplementedError() # pragma: no cover149-150-151-class BasePoolSemaphore:152- """153- A semaphore for use with connection pooling.154-155- Abstracts away any asyncio-specfic interfaces.156- """157-158- async def acquire(self) -> None:159- raise NotImplementedError() # pragma: no cover160-161- def release(self) -> None:162- raise NotImplementedError() # pragma: no cover163-164-165-class 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 cover174-175- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:176- raise NotImplementedError() # pragma: no cover177-178- async def run_in_threadpool(179- self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any180- ) -> typing.Any:181- raise NotImplementedError() # pragma: no cover182-183- async def iterate_in_threadpool(self, iterator): # type: ignore184- class IterationComplete(Exception):185- pass186-187- def next_wrapper(iterator): # type: ignore188- try:189- return next(iterator)190- except StopIteration:191- raise IterationComplete()192-193- while True:194- try:195- yield await self.run_in_threadpool(next_wrapper, iterator)196- except IterationComplete:197- break198-199- def run(200- self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any201- ) -> typing.Any:202- raise NotImplementedError() # pragma: no cover203-204- def iterate(self, async_iterator): # type: ignore205- while True:206- try:207- yield self.run(async_iterator.__anext__)208- except StopAsyncIteration:209- break210-211- def background_manager(212- self, coroutine: typing.Callable, args: typing.Any213- ) -> "BaseBackgroundManager":214- raise NotImplementedError() # pragma: no cover215-216-217-class BaseBackgroundManager:218- async def __aenter__(self) -> "BaseBackgroundManager":219- raise NotImplementedError() # pragma: no cover220-221- 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 coverdeleted:http3/models.py-1168 removed
1-import cgi2-import email.message3-import json as jsonlib4-import typing5-import urllib.request6-from collections.abc import MutableMapping7-from http.cookiejar import Cookie, CookieJar8-from urllib.parse import parse_qsl, urlencode9-10-import chardet11-import rfc398612-13-from .config import USER_AGENT14-from .decoders import (15- ACCEPT_ENCODING,16- SUPPORTED_DECODERS,17- Decoder,18- IdentityDecoder,19- MultiDecoder,20-)21-from .exceptions import (22- CookieConflict,23- HttpError,24- InvalidURL,25- ResponseClosed,26- ResponseNotRead,27- StreamConsumed,28-)29-from .multipart import multipart_encode30-from .status_codes import StatusCode31-from .utils import (32- guess_json_utf,33- is_known_encoding,34- normalize_header_key,35- normalize_header_value,36-)37-38-URLTypes = typing.Union["URL", str]39-40-QueryParamTypes = typing.Union[41- "QueryParams",42- typing.Mapping[str, str],43- typing.List[typing.Tuple[typing.Any, typing.Any]],44- str,45-]46-47-HeaderTypes = typing.Union[48- "Headers",49- typing.Dict[typing.AnyStr, typing.AnyStr],50- typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],51-]52-53-CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]54-55-AuthTypes = typing.Union[56- typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],57- typing.Callable[["AsyncRequest"], "AsyncRequest"],58-]59-60-AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]61-62-RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]63-64-RequestFiles = 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-]74-75-AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]76-77-ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]78-79-80-class 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.components93-94- # 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)99-100- # Normalize scheme and domain name.101- self.components = self.components.normalize()102-103- # Add any query parameters.104- if params:105- query_string = str(QueryParams(params))106- self.components = self.components.copy_with(query=query_string)107-108- # 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.")114-115- @property116- def scheme(self) -> str:117- return self.components.scheme or ""118-119- @property120- def authority(self) -> str:121- return self.components.authority or ""122-123- @property124- def username(self) -> str:125- userinfo = self.components.userinfo or ""126- return userinfo.partition(":")[0]127-128- @property129- def password(self) -> str:130- userinfo = self.components.userinfo or ""131- return userinfo.partition(":")[2]132-133- @property134- def host(self) -> str:135- return self.components.host or ""136-137- @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)143-144- @property145- def path(self) -> str:146- return self.components.path or "/"147-148- @property149- def query(self) -> str:150- return self.components.query or ""151-152- @property153- def full_path(self) -> str:154- path = self.path155- if self.query:156- path += "?" + self.query157- return path158-159- @property160- def fragment(self) -> str:161- return self.components.fragment or ""162-163- @property164- def is_ssl(self) -> bool:165- return self.components.scheme == "https"166-167- @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.host178-179- @property180- def is_relative_url(self) -> bool:181- return not self.is_absolute_url182-183- @property184- def origin(self) -> "Origin":185- return Origin(self)186-187- def copy_with(self, **kwargs: typing.Any) -> "URL":188- return URL(self.components.copy_with(**kwargs))189-190- 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)196-197- # 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))202-203- def __hash__(self) -> int:204- return hash(str(self))205-206- def __eq__(self, other: typing.Any) -> bool:207- return isinstance(other, URL) and str(self) == str(other)208-209- def __str__(self) -> str:210- return self.components.unsplit()211-212- def __repr__(self) -> str:213- class_name = self.__class__.__name__214- url_str = str(self)215- return f"{class_name}({url_str!r})"216-217-218-class Origin:219- """220- The URL scheme and authority information, as a comparable, hashable object.221- """222-223- 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.port229-230- 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- )237-238- def __hash__(self) -> int:239- return hash((self.is_ssl, self.host, self.port))240-241-242-class QueryParams(typing.Mapping[str, str]):243- """244- URL query parameters, as a multi-dict.245- """246-247- 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."250-251- value = args[0] if args else kwargs252-253- 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: ignore261-262- self._list = [(str(k), str(v)) for k, v in items]263- self._dict = {str(k): str(v) for k, v in items}264-265- 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]267-268- def keys(self) -> typing.KeysView:269- return self._dict.keys()270-271- def values(self) -> typing.ValuesView:272- return self._dict.values()273-274- def items(self) -> typing.ItemsView:275- return self._dict.items()276-277- def multi_items(self) -> typing.List[typing.Tuple[str, str]]:278- return list(self._list)279-280- 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 default284-285- def __getitem__(self, key: typing.Any) -> str:286- return self._dict[key]287-288- def __contains__(self, key: typing.Any) -> bool:289- return key in self._dict290-291- def __iter__(self) -> typing.Iterator[typing.Any]:292- return iter(self.keys())293-294- def __len__(self) -> int:295- return len(self._dict)296-297- def __eq__(self, other: typing.Any) -> bool:298- if not isinstance(other, self.__class__):299- return False300- return sorted(self._list) == sorted(other._list)301-302- def __str__(self) -> str:303- return urlencode(self._list)304-305- def __repr__(self) -> str:306- class_name = self.__class__.__name__307- query_string = str(self)308- return f"{class_name}({query_string!r})"309-310-311-class Headers(typing.MutableMapping[str, str]):312- """313- HTTP headers, as a case-insensitive multi-dict.314- """315-316- 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 = encoding332-333- @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._encoding357-358- @encoding.setter359- def encoding(self, value: str) -> None:360- self._encoding = value361-362- @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._list369-370- def keys(self) -> typing.List[str]: # type: ignore371- return [key.decode(self.encoding) for key, value in self._list]372-373- def values(self) -> typing.List[str]: # type: ignore374- return [value.decode(self.encoding) for key, value in self._list]375-376- 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- ]381-382- def get(self, key: str, default: typing.Any = None) -> typing.Any:383- try:384- return self[key]385- except KeyError:386- return default387-388- 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)393-394- values = [395- item_value.decode(self.encoding)396- for item_key, item_value in self._list397- if item_key == get_header_key398- ]399-400- if not split_commas:401- return values402-403- split_values = []404- for value in values:405- split_values.extend([item.strip() for item in value.split(",")])406- return split_values407-408- def __getitem__(self, key: str) -> str:409- """410- Return a single header value.411-412- 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)416-417- items = []418- for header_key, header_value in self._list:419- if header_key == normalized_key:420- items.append(header_value.decode(self.encoding))421-422- if items:423- return ", ".join(items)424-425- raise KeyError(key)426-427- 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)434-435- found_indexes = []436- for idx, (item_key, item_value) in enumerate(self._list):437- if item_key == set_key:438- found_indexes.append(idx)439-440- for idx in reversed(found_indexes[1:]):441- del self._list[idx]442-443- 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))448-449- def __delitem__(self, key: str) -> None:450- """451- Remove the header `key`.452- """453- del_key = key.lower().encode(self.encoding)454-455- pop_indexes = []456- for idx, (item_key, item_value) in enumerate(self._list):457- if item_key == del_key:458- pop_indexes.append(idx)459-460- for idx in reversed(pop_indexes):461- del self._list[idx]462-463- 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 False469-470- def __iter__(self) -> typing.Iterator[typing.Any]:471- return iter(self.keys())472-473- def __len__(self) -> int:474- return len(self._list)475-476- def __eq__(self, other: typing.Any) -> bool:477- if not isinstance(other, Headers):478- return False479- return sorted(self._list) == sorted(other._list)480-481- def __repr__(self) -> str:482- class_name = self.__class__.__name__483-484- encoding_str = ""485- if self.encoding != "ascii":486- encoding_str = f", encoding={self.encoding!r}"487-488- 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})"493-494-495-class 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)511-512- 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_type527-528- def prepare(self) -> None:529- content = getattr(self, "content", None) # type: bytes530- is_streaming = getattr(self, "is_streaming", False)531-532- auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]533-534- 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.headers542-543- 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"))559-560- for item in reversed(auto_headers):561- self.headers.raw.insert(0, item)562-563- @property564- def cookies(self) -> "Cookies":565- if not hasattr(self, "_cookies"):566- self._cookies = Cookies()567- return self._cookies568-569- 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})>"573-574-575-class 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- )591-592- 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 = data606-607- self.prepare()608-609- 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.content616-617- 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.content623-624-625-class 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- )641-642- 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 = data656-657- self.prepare()658-659- def read(self) -> bytes:660- if not hasattr(self, "content"):661- self.content = b"".join([part for part in self.stream()])662- return self.content663-664- 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.content670-671-672-class 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)685-686- self.request = request687- self.on_close = on_close688- self.next = None # typing.Optional[typing.Callable]689-690- @property691- def reason_phrase(self) -> str:692- return StatusCode.get_reason_phrase(self.status_code)693-694- @property695- def url(self) -> typing.Optional[URL]:696- """697- Returns the URL for which the request was made.698-699- Requires that `request` was provided when instantiating the response.700- """701- return None if self.request is None else self.request.url702-703- @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._content714-715- @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._text725-726- @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._encoding736-737- @encoding.setter738- def encoding(self, value: str) -> None:739- self._encoding = value740-741- @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 None749-750- parsed = cgi.parse_header(content_type)751- media_type, params = parsed[0], parsed[-1]752- if "charset" in params:753- return params["charset"].strip("'\"")754-755- # 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"760-761- return None762-763- @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"]769-770- @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())783-784- 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()790-791- return self._decoder792-793- @property794- def is_redirect(self) -> bool:795- return StatusCode.is_redirect(self.status_code) and "location" in self.headers796-797- 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- )805-806- 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 = ""812-813- if message:814- raise HttpError(message)815-816- 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)825-826- @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._cookies833-834- def __repr__(self) -> str:835- return f"<Response [{self.status_code} {self.reason_phrase}]>"836-837-838-class 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- )857-858- self.history = [] if history is None else list(history)859-860- 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 = content868-869- 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._content876-877- 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()888-889- 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()900-901- self.is_stream_consumed = True902- async for part in self._raw_stream:903- yield part904- await self.close()905-906- 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()915-916-917-class 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- )936-937- self.history = [] if history is None else list(history)938-939- 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 = content947-948- 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._content955-956- 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()967-968- 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()979-980- self.is_stream_consumed = True981- for part in self._raw_stream:982- yield part983- self.close()984-985- 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()994-995-996-class Cookies(MutableMapping):997- """998- HTTP Cookies, as a mutable mapping.999- """1000-1001- 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 = cookies1013-1014- 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)1021-1022- self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore1023-1024- 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)1030-1031- 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)1056-1057- 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.value1073-1074- if value is None:1075- return default1076- return value1077-1078- 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)1085-1086- 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)1092-1093- for cookie in remove:1094- self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore1095-1096- 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)1108-1109- def update(self, cookies: CookieTypes = None) -> None: # type: ignore1110- cookies = Cookies(cookies)1111- for cookie in cookies.jar:1112- self.jar.set_cookie(cookie)1113-1114- def __setitem__(self, name: str, value: str) -> None:1115- return self.set(name, value)1116-1117- def __getitem__(self, name: str) -> str:1118- value = self.get(name)1119- if value is None:1120- raise KeyError(name)1121- return value1122-1123- def __delitem__(self, name: str) -> None:1124- return self.delete(name)1125-1126- def __len__(self) -> int:1127- return len(self.jar)1128-1129- def __iter__(self) -> typing.Iterator[str]:1130- return (cookie.name for cookie in self.jar)1131-1132- def __bool__(self) -> bool:1133- for cookie in self.jar:1134- return True1135- return False1136-1137- class _CookieCompatRequest(urllib.request.Request):1138- """1139- Wraps a `Request` instance up in a compatability interface suitable1140- for use with `CookieJar` operations.1141- """1142-1143- 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 = request1150-1151- def add_unredirected_header(self, key: str, value: str) -> None:1152- super().add_unredirected_header(key, value)1153- self.request.headers[key] = value1154-1155- class _CookieCompatResponse:1156- """1157- Wraps a `Request` instance up in a compatability interface suitable1158- for use with `CookieJar` operations.1159- """1160-1161- def __init__(self, response: BaseResponse):1162- self.response = response1163-1164- 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 infodeleted:http3/multipart.py-106 removed
1-import binascii2-import mimetypes3-import os4-import typing5-from io import BytesIO6-from urllib.parse import quote7-8-9-class Field:10- def render_headers(self) -> bytes:11- raise NotImplementedError() # pragma: nocover12-13- def render_data(self) -> bytes:14- raise NotImplementedError() # pragma: nocover15-16-17-class 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 = value25-26- 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- )31-32- def render_data(self) -> bytes:33- return (34- self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")35- )36-37-38-class 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- )53-54- def guess_content_type(self) -> str:55- return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"56-57- 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- )74-75- def render_data(self) -> bytes:76- content = self.file.read()77- return content.encode("utf-8") if isinstance(content, str) else content78-79-80-def 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)87-88- for name, value in files.items():89- yield FileField(name=name, value=value)90-91-92-def multipart_encode(data: dict, files: dict) -> typing.Tuple[bytes, str]:93- body = BytesIO()94- boundary = binascii.hexlify(os.urandom(16))95-96- 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")101-102- body.write(b"--%s--\r\n" % boundary)103-104- content_type = "multipart/form-data; boundary=%s" % boundary.decode("ascii")105-106- return body.getvalue(), content_typedeleted:http3/status_codes.py-131 removed
1-from enum import IntEnum2-3-4-class 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- """17-18- def __new__(cls, value: int, phrase: str = "") -> "StatusCode":19- obj = int.__new__(cls, value) # type: ignore20- obj._value_ = value21-22- obj.phrase = phrase23- return obj24-25- def __str__(self) -> str:26- return str(self.value)27-28- @classmethod29- def get_reason_phrase(cls, value: int) -> str:30- try:31- return StatusCode(value).phrase # type: ignore32- except ValueError:33- return ""34-35- @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- )49-50- @classmethod51- def is_client_error(cls, value: int) -> bool:52- return value >= 400 and value <= 49953-54- @classmethod55- def is_server_error(cls, value: int) -> bool:56- return value >= 500 and value <= 59957-58- # informational59- CONTINUE = 100, "Continue"60- SWITCHING_PROTOCOLS = 101, "Switching Protocols"61- PROCESSING = 102, "Processing"62-63- # 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"74-75- # 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"84-85- # 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"112-113- # 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"125-126-127-codes = StatusCode128-129-# Include lower-case styles for `requests` compatability.130-for code in codes:131- setattr(codes, code._name_.lower(), int(code))deleted:http3/utils.py-66 removed
1-import codecs2-import typing3-4-5-def 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()12-13-14-def 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")21-22-23-def 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 True32-33-34-# 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 * 338-39-40-def 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 Noneadded:httpx/dispatch/__init__.py+4 added
1+"""2+Dispatch classes handle the raw network connections and the implementation3+details of making the HTTP request and receiving the response.4+"""added:httpx/dispatch/asgi.py+187 added
1+import asyncio2+import typing3+4+from ..config import CertTypes, TimeoutTypes, VerifyTypes5+from ..interfaces import AsyncDispatcher6+from ..models import AsyncRequest, AsyncResponse7+8+9+class ASGIDispatch(AsyncDispatcher):10+ """11+ A custom dispatcher that handles sending requests directly to an ASGI app.12+13+ 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:16+17+ ```18+ client = httpx.Client(app=app)19+ ```20+21+ Alternatively, you can setup the dispatch instance explicitly.22+ This allows you to include any additional configuration arguments specific23+ to the ASGIDispatch class:24+25+ ```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+ """34+35+ 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 = client46+47+ async def send(48+ self,49+ request: AsyncRequest,50+ verify: VerifyTypes = None,51+ cert: CertTypes = None,52+ timeout: TimeoutTypes = None,53+ ) -> AsyncResponse:54+55+ scope = {56+ "type": "http",57+ "asgi": {"version": "3.0"},58+ "http_version": "1.1",59+ "method": request.method,60+ "headers": request.headers.raw,61+ "scheme": request.url.scheme,62+ "path": request.url.path,63+ "query_string": request.url.query.encode("ascii"),64+ "server": request.url.host,65+ "client": self.client,66+ "root_path": self.root_path,67+ }68+ app = self.app69+ app_exc = None70+ status_code = None71+ headers = None72+ response_started = asyncio.Event()73+ response_body = BodyIterator()74+ request_stream = request.stream()75+76+ async def receive() -> dict:77+ nonlocal request_stream78+79+ 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}84+85+ async def send(message: dict) -> None:86+ nonlocal status_code, headers, response_started, response_body, request87+88+ 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()99+100+ 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()108+109+ # 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())117+118+ tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]119+120+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)121+122+ if app_exc is not None and self.raise_app_exceptions:123+ raise app_exc124+125+ assert response_started.is_set(), "application did not return a response."126+ assert status_code is not None127+ assert headers is not None128+129+ 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_exc135+136+ 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+ )144+145+146+class BodyIterator:147+ """148+ Provides a byte-iterator interface that the client can use to149+ ingest the response content from.150+ """151+152+ def __init__(self) -> None:153+ self._queue = asyncio.Queue(154+ maxsize=1155+ ) # type: asyncio.Queue[typing.Union[bytes, object]]156+ self._done = object()157+158+ 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 data168+169+ 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 cover176+177+ 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)182+183+ 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
1+import typing2+3+from ..concurrency import AsyncioBackend4+from ..config import (5+ DEFAULT_POOL_LIMITS,6+ DEFAULT_TIMEOUT_CONFIG,7+ CertTypes,8+ PoolLimits,9+ TimeoutTypes,10+ VerifyTypes,11+)12+from ..exceptions import NotConnected13+from ..interfaces import AsyncDispatcher, ConcurrencyBackend14+from ..models import AsyncRequest, AsyncResponse, Origin15+from .connection import HTTPConnection16+17+CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]18+19+20+class ConnectionStore:21+ """22+ We need to maintain collections of connections in a way that allows us to:23+24+ * Lookup connections by origin.25+ * Iterate over connections by insertion time.26+ * Return the total number of connections.27+ """28+29+ 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]]34+35+ 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 None42+43+ connection = next(reversed(list(connections.keys())))44+ if http2_only and not connection.is_http2:45+ return None46+47+ del connections[connection]48+ if not connections:49+ del self.by_origin[origin]50+ del self.all[connection]51+52+ return connection53+54+ 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}60+61+ 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]66+67+ def clear(self) -> None:68+ self.all.clear()69+ self.by_origin.clear()70+71+ def __iter__(self) -> typing.Iterator[HTTPConnection]:72+ return iter(self.all.keys())73+74+ def __len__(self) -> int:75+ return len(self.all)76+77+78+class 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 = False93+94+ self.keepalive_connections = ConnectionStore()95+ self.active_connections = ConnectionStore()96+97+ self.backend = AsyncioBackend() if backend is None else backend98+ self.max_connections = self.backend.get_semaphore(pool_limits)99+100+ @property101+ def num_connections(self) -> int:102+ return len(self.keepalive_connections) + len(self.active_connections)103+104+ 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 exc129+130+ return response131+132+ 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)140+141+ 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+ )151+152+ self.active_connections.add(connection)153+154+ return connection155+156+ 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)170+171+ 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
1+import functools2+import typing3+4+from ..concurrency import AsyncioBackend5+from ..config import (6+ DEFAULT_TIMEOUT_CONFIG,7+ CertTypes,8+ SSLConfig,9+ TimeoutConfig,10+ TimeoutTypes,11+ VerifyTypes,12+)13+from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Protocol14+from ..models import AsyncRequest, AsyncResponse, Origin15+from .http2 import HTTP2Connection16+from .http11 import HTTP11Connection17+18+# Callback signature: async def callback(conn: HTTPConnection) -> None19+ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]20+21+22+class 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]39+40+ 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)49+50+ 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)55+56+ return response57+58+ 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)66+67+ host = self.origin.host68+ port = self.origin.port69+ ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None70+71+ if self.release_func is None:72+ on_release = None73+ else:74+ on_release = functools.partial(self.release_func, self)75+76+ 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+ )87+88+ 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()93+94+ @property95+ def is_http2(self) -> bool:96+ return self.h2_connection is not None97+98+ @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_closedadded:httpx/dispatch/http11.py+190 added
1+import typing2+3+import h114+5+from ..concurrency import TimeoutFlag6+from ..config import TimeoutConfig, TimeoutTypes7+from ..exceptions import NotConnected8+from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9+from ..models import AsyncRequest, AsyncResponse10+11+H11Event = typing.Union[12+ h11.Request,13+ h11.Response,14+ h11.InformationalResponse,15+ h11.Data,16+ h11.EndOfMessage,17+ h11.ConnectionClosed,18+]19+20+21+# Callback signature: async def callback() -> None22+# In practice the callback will be a functools partial, which binds23+# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.24+OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]25+26+27+class HTTP11Connection:28+ READ_NUM_BYTES = 409629+30+ 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()43+44+ async def send(45+ self, request: AsyncRequest, timeout: TimeoutTypes = None46+ ) -> AsyncResponse:47+ timeout = None if timeout is None else TimeoutConfig(timeout)48+49+ 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 None55+56+ 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)60+61+ 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+ )69+70+ 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()78+79+ 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)90+91+ 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)102+103+ # 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()114+115+ 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)122+123+ 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)141+142+ 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+ break155+156+ 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 event173+174+ 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()184+185+ if self.on_release is not None:186+ await self.on_release()187+188+ @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
1+import functools2+import typing3+4+import h2.connection5+import h2.events6+7+from ..concurrency import TimeoutFlag8+from ..config import TimeoutConfig, TimeoutTypes9+from ..exceptions import NotConnected10+from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11+from ..models import AsyncRequest, AsyncResponse12+13+14+class HTTP2Connection:15+ READ_NUM_BYTES = 409616+17+ 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 = False32+33+ async def send(34+ self, request: AsyncRequest, timeout: TimeoutTypes = None35+ ) -> AsyncResponse:36+ timeout = None if timeout is None else TimeoutConfig(timeout)37+38+ # Start sending the request.39+ if not self.initialized:40+ self.initiate_connection()41+42+ try:43+ stream_id = await self.send_headers(request, timeout)44+ except ConnectionResetError:45+ raise NotConnected() from None46+47+ self.events[stream_id] = []48+ self.timeout_flags[stream_id] = TimeoutFlag()49+50+ 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)55+56+ 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+ )64+65+ async def close(self) -> None:66+ await self.writer.close()67+68+ 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 = True73+74+ 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_id88+89+ 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()102+103+ 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)113+114+ 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)118+119+ 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+ break132+133+ 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)141+142+ 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+ break152+153+ 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)163+164+ data_to_send = self.h2_state.data_to_send()165+ await self.writer.write(data_to_send, timeout)166+167+ return self.events[stream_id].pop(0)168+169+ async def response_closed(self, stream_id: int) -> None:170+ del self.events[stream_id]171+ del self.timeout_flags[stream_id]172+173+ if not self.events and self.on_release is not None:174+ await self.on_release()175+176+ @property177+ def is_closed(self) -> bool:178+ return Falseadded:httpx/dispatch/threaded.py+96 added
1+from ..config import CertTypes, TimeoutTypes, VerifyTypes2+from ..interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher3+from ..models import (4+ AsyncRequest,5+ AsyncRequestData,6+ AsyncResponse,7+ AsyncResponseContent,8+ Request,9+ RequestData,10+ Response,11+ ResponseContent,12+)13+14+15+class 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+ """21+22+ def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:23+ self.sync_dispatcher = dispatch24+ self.backend = backend25+26+ 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.backend34+35+ data = getattr(request, "content", getattr(request, "content_aiter", None))36+ sync_data = self._sync_request_data(data)37+38+ sync_request = Request(39+ method=request.method,40+ url=request.url,41+ headers=request.headers,42+ data=sync_data,43+ )44+45+ 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)54+55+ content = getattr(56+ sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)57+ )58+59+ async_content = self._async_response_content(content)60+61+ async def async_on_close() -> None:62+ nonlocal concurrency_backend, sync_response63+ await concurrency_backend.run_in_threadpool(sync_response.close)64+65+ 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+ )74+75+ 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)82+83+ def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:84+ if isinstance(content, bytes):85+ return content86+87+ # 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)91+92+ def _sync_request_data(self, data: AsyncRequestData) -> RequestData:93+ if isinstance(data, bytes):94+ return data95+96+ return self.backend.iterate(data)added:httpx/dispatch/wsgi.py+154 added
1+import io2+import typing3+4+from ..config import CertTypes, TimeoutTypes, VerifyTypes5+from ..interfaces import Dispatcher6+from ..models import Request, Response7+8+9+class WSGIDispatch(Dispatcher):10+ """11+ A custom dispatcher that handles sending requests directly to an ASGI app.12+13+ 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:16+17+ ```18+ client = httpx.Client(app=app)19+ ```20+21+ Alternatively, you can setup the dispatch instance explicitly.22+ This allows you to include any additional configuration arguments specific23+ to the WSGIDispatch class:24+25+ ```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+ """34+35+ 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_addr46+47+ 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] = value75+76+ seen_status = None77+ seen_response_headers = None78+ seen_exc_info = None79+80+ 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_info87+88+ result = self.app(environ, start_response)89+90+ 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]94+95+ 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+ )102+103+104+class BodyStream(io.RawIOBase):105+ def __init__(self, iterator: typing.Iterator[bytes]) -> None:106+ self._iterator = iterator107+ self._buffer = b""108+ self._closed = False109+110+ def read(self, size: int = -1) -> bytes:111+ if self._closed:112+ return b""113+114+ if size == -1:115+ return self.readall()116+117+ try:118+ while len(self._buffer) < size:119+ self._buffer += next(self._iterator)120+ except StopIteration:121+ self._closed = True122+ return self._buffer123+124+ output = self._buffer[:size]125+ self._buffer = self._buffer[size:]126+ return output127+128+ def readall(self) -> bytes:129+ if self._closed:130+ raise OSError("Stream closed") # pragma: nocover131+132+ for chunk in self._iterator:133+ self._buffer += chunk134+135+ self._closed = True136+ return self._buffer137+138+ def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover139+ output = self.read(len(b))140+ count = len(output)141+ b[:count] = output142+ return count143+144+ def write(self, b: bytes) -> int:145+ raise OSError("Operation not supported") # pragma: nocover146+147+ def fileno(self) -> int:148+ raise OSError("Operation not supported") # pragma: nocover149+150+ def seek(self, offset: int, whence: int = 0) -> int:151+ raise OSError("Operation not supported") # pragma: nocover152+153+ def truncate(self, size: int = None) -> int:154+ raise OSError("Operation not supported") # pragma: nocoveradded:httpx/__init__.py+131 added
1+from .__version__ import __description__, __title__, __version__2+from .api import delete, get, head, options, patch, post, put, request3+from .client import AsyncClient, Client4+from .concurrency import AsyncioBackend5+from .config import (6+ USER_AGENT,7+ CertTypes,8+ PoolLimits,9+ SSLConfig,10+ TimeoutConfig,11+ TimeoutTypes,12+ VerifyTypes,13+)14+from .dispatch.connection import HTTPConnection15+from .dispatch.connection_pool import ConnectionPool16+from .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+)33+from .interfaces import (34+ AsyncDispatcher,35+ BaseReader,36+ BaseWriter,37+ ConcurrencyBackend,38+ Dispatcher,39+ Protocol,40+)41+from .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+)62+from .status_codes import StatusCode, codes63+64+__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
1+import typing2+3+from .client import Client4+from .config import CertTypes, TimeoutTypes, VerifyTypes5+from .models import (6+ AuthTypes,7+ CookieTypes,8+ HeaderTypes,9+ QueryParamTypes,10+ RequestData,11+ RequestFiles,12+ Response,13+ URLTypes,14+)15+16+17+def 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+ )53+54+55+def 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+ )81+82+83+def 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+ )109+110+111+def 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+ )137+138+139+def 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+ )171+172+173+def 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+ )205+206+207+def 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+ )239+240+241+def 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
1+import typing2+from base64 import b64encode3+4+from .models import AsyncRequest5+6+7+class AuthBase:8+ """9+ Base class that all auth implementations derive from.10+ """11+12+ def __call__(self, request: AsyncRequest) -> AsyncRequest:13+ raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover14+15+16+class 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 = password22+23+ def __call__(self, request: AsyncRequest) -> AsyncRequest:24+ request.headers["Authorization"] = self.build_auth_header()25+ return request26+27+ def build_auth_header(self) -> str:28+ username, password = self.username, self.password29+30+ if isinstance(username, str):31+ username = username.encode("latin1")32+33+ if isinstance(password, str):34+ password = password.encode("latin1")35+36+ userpass = b":".join((username, password))37+ token = b64encode(userpass).decode().strip()38+ return f"Basic {token}"added:httpx/client.py+895 added
1+import inspect2+import typing3+from types import TracebackType4+5+from .auth import HTTPBasicAuth6+from .concurrency import AsyncioBackend7+from .config import (8+ DEFAULT_MAX_REDIRECTS,9+ DEFAULT_POOL_LIMITS,10+ DEFAULT_TIMEOUT_CONFIG,11+ CertTypes,12+ PoolLimits,13+ TimeoutTypes,14+ VerifyTypes,15+)16+from .dispatch.asgi import ASGIDispatch17+from .dispatch.connection_pool import ConnectionPool18+from .dispatch.threaded import ThreadedDispatcher19+from .dispatch.wsgi import WSGIDispatch20+from .exceptions import (21+ InvalidURL,22+ RedirectBodyUnavailable,23+ RedirectLoop,24+ TooManyRedirects,25+)26+from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher27+from .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+)45+from .status_codes import codes46+47+48+class 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()66+67+ 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+ )78+79+ 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 = dispatch91+92+ if base_url is None:93+ self.base_url = URL("", allow_relative=True)94+ else:95+ self.base_url = URL(base_url)96+97+ self.auth = auth98+ self.cookies = Cookies(cookies)99+ self.max_redirects = max_redirects100+ self.dispatch = async_dispatch101+ self.concurrency_backend = backend102+103+ 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 cookies111+112+ 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.auth125+126+ url = request.url127+128+ if url.scheme not in ("http", "https"):129+ raise InvalidURL('URL scheme must be "http" or "https".')130+131+ if auth is None and (url.username or url.password):132+ auth = HTTPBasicAuth(username=url.username, password=url.password)133+134+ if auth is not None:135+ if isinstance(auth, tuple):136+ auth = HTTPBasicAuth(username=auth[0], password=auth[1])137+ request = auth(request)138+139+ response = await self.send_handling_redirects(140+ request,141+ verify=verify,142+ cert=cert,143+ timeout=timeout,144+ allow_redirects=allow_redirects,145+ )146+147+ if not stream:148+ try:149+ await response.read()150+ finally:151+ await response.close()152+153+ return response154+155+ 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 = []167+168+ 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()175+176+ 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]185+186+ 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()194+195+ if response.is_redirect:196+197+ 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 response210+211+ response.next = send_next # type: ignore212+213+ return response214+215+ 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+ )226+227+ 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.method233+234+ # https://tools.ietf.org/html/rfc7231#section-6.4.4235+ if response.status_code == codes.SEE_OTHER and method != "HEAD":236+ method = "GET"237+238+ # 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"242+243+ # 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"247+248+ return method249+250+ 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"]255+256+ url = URL(location, allow_relative=True)257+258+ # 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)262+263+ # 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)266+267+ return url268+269+ 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 headers278+279+ 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.content288+289+290+class 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+ )318+319+ 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+ )346+347+ 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+ )374+375+ 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+ )408+409+ 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+ )442+443+ 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+ )476+477+ 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+ )510+511+ 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 response551+552+ async def close(self) -> None:553+ await self.dispatch.close()554+555+ async def __aenter__(self) -> "AsyncClient":556+ return self557+558+ 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()565+566+567+class 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 data577+578+ # 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)582+583+ def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:584+ if isinstance(data, bytes):585+ return data586+587+ # 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)591+592+ 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_backend623+624+ 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)635+636+ content = getattr(637+ async_response, "_raw_content", getattr(async_response, "_raw_stream", None)638+ )639+640+ sync_content = self._sync_data(content)641+642+ def sync_on_close() -> None:643+ nonlocal concurrency_backend, async_response644+ concurrency_backend.run(async_response.on_close)645+646+ 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 response661+662+ 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+ )689+690+ 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+ )717+718+ 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+ )745+746+ 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+ )779+780+ 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+ )813+814+ 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+ )847+848+ 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+ )881+882+ def close(self) -> None:883+ coroutine = self.dispatch.close884+ self.concurrency_backend.run(coroutine)885+886+ def __enter__(self) -> "Client":887+ return self888+889+ 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+"""2+The `Reader` and `Writer` classes here provide a lightweight layer over3+`asyncio.StreamReader` and `asyncio.StreamWriter`.4+5+Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6+7+These classes help encapsulate the timeout logic, make it easier to unit-test8+protocols, and help keep the rest of the package more `async`/`await`9+based, and less strictly `asyncio`-specific.10+"""11+import asyncio12+import functools13+import ssl14+import typing15+from types import TracebackType16+17+from .config import PoolLimits, TimeoutConfig18+from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19+from .interfaces import (20+ BaseBackgroundManager,21+ BasePoolSemaphore,22+ BaseReader,23+ BaseWriter,24+ ConcurrencyBackend,25+ Protocol,26+)27+28+SSL_MONKEY_PATCH_APPLIED = False29+30+31+def ssl_monkey_patch() -> None:32+ """33+ Monky-patch for https://bugs.python.org/issue3670934+35+ This prevents console errors when outstanding HTTPS connections36+ still exist at the point of exiting.37+38+ 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: ignore42+43+ _write = MonkeyPatch.write44+45+ def _fixed_write(self, data: bytes) -> None: # type: ignore46+ if self._loop and not self._loop.is_closed():47+ _write(self, data)48+49+ MonkeyPatch.write = _fixed_write50+51+52+class TimeoutFlag:53+ """54+ A timeout flag holds a state of either read-timeout or write-timeout mode.55+56+ We use this so that we can attempt both reads and writes concurrently, while57+ only enforcing timeouts in one direction.58+59+ During a request/response cycle we start in write-timeout mode.60+61+ Once we've sent a request fully, or once we start seeing a response,62+ then we switch to read-timeout mode instead.63+ """64+65+ def __init__(self) -> None:66+ self.raise_on_read_timeout = False67+ self.raise_on_write_timeout = True68+69+ 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 = False75+76+ 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 = True82+83+84+class Reader(BaseReader):85+ def __init__(86+ self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87+ ) -> None:88+ self.stream_reader = stream_reader89+ self.timeout = timeout90+91+ async def read(92+ self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93+ ) -> bytes:94+ if timeout is None:95+ timeout = self.timeout96+97+ 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 None108+109+ return data110+111+112+class Writer(BaseWriter):113+ def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):114+ self.stream_writer = stream_writer115+ self.timeout = timeout116+117+ def write_no_block(self, data: bytes) -> None:118+ self.stream_writer.write(data) # pragma: nocover119+120+ async def write(121+ self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None122+ ) -> None:123+ if not data:124+ return125+126+ if timeout is None:127+ timeout = self.timeout128+129+ 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 None143+144+ async def close(self) -> None:145+ self.stream_writer.close()146+147+148+class PoolSemaphore(BasePoolSemaphore):149+ def __init__(self, pool_limits: PoolLimits):150+ self.pool_limits = pool_limits151+152+ @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._semaphore161+162+ async def acquire(self) -> None:163+ if self.semaphore is None:164+ return165+166+ timeout = self.pool_limits.pool_timeout167+ try:168+ await asyncio.wait_for(self.semaphore.acquire(), timeout)169+ except asyncio.TimeoutError:170+ raise PoolTimeout()171+172+ def release(self) -> None:173+ if self.semaphore is None:174+ return175+176+ self.semaphore.release()177+178+179+class AsyncioBackend(ConcurrencyBackend):180+ def __init__(self) -> None:181+ global SSL_MONKEY_PATCH_APPLIED182+183+ if not SSL_MONKEY_PATCH_APPLIED:184+ ssl_monkey_patch()185+ SSL_MONKEY_PATCH_APPLIED = True186+187+ @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._loop195+196+ 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()210+211+ 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()218+219+ 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_11222+223+ return (reader, writer, protocol)224+225+ 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)232+233+ 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 = loop243+244+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:245+ return PoolSemaphore(limits)246+247+ def background_manager(248+ self, coroutine: typing.Callable, args: typing.Any249+ ) -> "BackgroundManager":250+ return BackgroundManager(coroutine, args)251+252+253+class BackgroundManager(BaseBackgroundManager):254+ def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:255+ self.coroutine = coroutine256+ self.args = args257+258+ async def __aenter__(self) -> "BackgroundManager":259+ loop = asyncio.get_event_loop()260+ self.task = loop.create_task(self.coroutine(*self.args))261+ return self262+263+ 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
1+import asyncio2+import os3+import ssl4+import typing5+6+import certifi7+8+from .__version__ import __version__9+10+CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11+VerifyTypes = typing.Union[str, bool]12+TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]13+14+15+USER_AGENT = f"python-httpx/{__version__}"16+17+DEFAULT_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+)35+36+37+class SSLConfig:38+ """39+ SSL Configuration.40+ """41+42+ def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43+ self.cert = cert44+ self.verify = verify45+46+ self.ssl_context: typing.Optional[ssl.SSLContext] = None47+48+ 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+ )54+55+ def __repr__(self) -> str:56+ class_name = self.__class__.__name__57+ return f"{class_name}(cert={self.cert}, verify={self.verify})"58+59+ 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)67+68+ 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+ )78+79+ assert self.ssl_context is not None80+ return self.ssl_context81+82+ 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 context90+91+ 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+ )104+105+ context = self._create_default_ssl_context()106+ context.verify_mode = ssl.CERT_REQUIRED107+ context.check_hostname = True108+109+ # 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+ pass115+116+ # 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+ pass122+123+ 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)127+128+ 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+ )139+140+ return context141+142+ 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)152+153+ 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"])157+158+ return context159+160+161+class TimeoutConfig:162+ """163+ Timeout values.164+ """165+166+ 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 = timeout195+196+ 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+ )203+204+ 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+ )212+213+214+class PoolLimits:215+ """216+ Limits on the number of connections in a connection pool.217+ """218+219+ 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_timeout229+230+ 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+ )237+238+ 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+ )244+245+246+DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)247+DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)248+DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)249+DEFAULT_CA_BUNDLE_PATH = certifi.where()250+DEFAULT_MAX_REDIRECTS = 20added:httpx/decoders.py+149 added
1+"""2+Handlers for Content-Encoding.3+4+See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding5+"""6+import typing7+import zlib8+9+from .exceptions import DecodingError10+11+try:12+ import brotli13+except ImportError: # pragma: nocover14+ brotli = None15+16+17+class Decoder:18+ def decode(self, data: bytes) -> bytes:19+ raise NotImplementedError() # pragma: nocover20+21+ def flush(self) -> bytes:22+ raise NotImplementedError() # pragma: nocover23+24+25+class IdentityDecoder(Decoder):26+ """27+ Handle unencoded data.28+ """29+30+ def decode(self, data: bytes) -> bytes:31+ return data32+33+ def flush(self) -> bytes:34+ return b""35+36+37+class DeflateDecoder(Decoder):38+ """39+ Handle 'deflate' decoding.40+41+ See: https://stackoverflow.com/questions/183869942+ """43+44+ def __init__(self) -> None:45+ self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)46+47+ def decode(self, data: bytes) -> bytes:48+ try:49+ return self.decompressor.decompress(data)50+ except zlib.error as exc:51+ raise DecodingError from exc52+53+ def flush(self) -> bytes:54+ try:55+ return self.decompressor.flush()56+ except zlib.error as exc: # pragma: nocover57+ raise DecodingError from exc58+59+60+class GZipDecoder(Decoder):61+ """62+ Handle 'gzip' decoding.63+64+ See: https://stackoverflow.com/questions/183869965+ """66+67+ def __init__(self) -> None:68+ self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)69+70+ def decode(self, data: bytes) -> bytes:71+ try:72+ return self.decompressor.decompress(data)73+ except zlib.error as exc:74+ raise DecodingError from exc75+76+ def flush(self) -> bytes:77+ try:78+ return self.decompressor.flush()79+ except zlib.error as exc: # pragma: nocover80+ raise DecodingError from exc81+82+83+class BrotliDecoder(Decoder):84+ """85+ Handle 'brotli' decoding.86+87+ Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/88+ """89+90+ 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()95+96+ def decode(self, data: bytes) -> bytes:97+ try:98+ return self.decompressor.decompress(data)99+ except brotli.Error as exc:100+ raise DecodingError from exc101+102+ def flush(self) -> bytes:103+ try:104+ self.decompressor.finish()105+ return b""106+ except brotli.Error as exc: # pragma: nocover107+ raise DecodingError from exc108+109+110+class MultiDecoder(Decoder):111+ """112+ Handle the case where multiple encodings have been applied.113+ """114+115+ 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))122+123+ def decode(self, data: bytes) -> bytes:124+ for child in self.children:125+ data = child.decode(data)126+ return data127+128+ def flush(self) -> bytes:129+ data = b""130+ for child in self.children:131+ data = child.decode(data) + child.flush()132+ return data133+134+135+SUPPORTED_DECODERS = {136+ "identity": IdentityDecoder,137+ "gzip": GZipDecoder,138+ "deflate": DeflateDecoder,139+ "br": BrotliDecoder,140+}141+142+143+if brotli is None:144+ SUPPORTED_DECODERS.pop("br") # pragma: nocover145+146+147+ACCEPT_ENCODING = ", ".join(148+ [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]149+)added:httpx/exceptions.py+135 added
1+# Timeout exceptions...2+3+4+class Timeout(Exception):5+ """6+ A base class for all timeouts.7+ """8+9+10+class ConnectTimeout(Timeout):11+ """12+ Timeout while establishing a connection.13+ """14+15+16+class ReadTimeout(Timeout):17+ """18+ Timeout while reading response data.19+ """20+21+22+class WriteTimeout(Timeout):23+ """24+ Timeout while writing request data.25+ """26+27+28+class PoolTimeout(Timeout):29+ """30+ Timeout while waiting to acquire a connection from the pool.31+ """32+33+34+# HTTP exceptions...35+36+37+class NotConnected(Exception):38+ """39+ A connection was lost at the point of starting a request,40+ prior to any writes succeeding.41+ """42+43+44+class HttpError(Exception):45+ """46+ An HTTP error occurred.47+ """48+49+50+class ProtocolError(Exception):51+ """52+ Malformed HTTP.53+ """54+55+56+class DecodingError(Exception):57+ """58+ Decoding of the response failed.59+ """60+61+62+# Redirect exceptions...63+64+65+class RedirectError(Exception):66+ """67+ Base class for HTTP redirect errors.68+ """69+70+71+class TooManyRedirects(RedirectError):72+ """73+ Too many redirects.74+ """75+76+77+class RedirectBodyUnavailable(RedirectError):78+ """79+ Got a redirect response, but the request body was streaming, and is80+ no longer available.81+ """82+83+84+class RedirectLoop(RedirectError):85+ """86+ Infinite redirect loop.87+ """88+89+90+# Stream exceptions...91+92+93+class StreamException(Exception):94+ """95+ The base class for stream exceptions.96+97+ The developer made an error in accessing the request stream in98+ an invalid way.99+ """100+101+102+class StreamConsumed(StreamException):103+ """104+ Attempted to read or stream response content, but the content has already105+ been streamed.106+ """107+108+109+class ResponseNotRead(StreamException):110+ """111+ Attempted to access response content, without having called `read()`112+ after a streaming response.113+ """114+115+116+class ResponseClosed(StreamException):117+ """118+ Attempted to read or stream response content, but the request has been119+ closed.120+ """121+122+123+# Other cases...124+125+126+class InvalidURL(Exception):127+ """128+ URL was missing a hostname, or was not one of HTTP/HTTPS.129+ """130+131+132+class CookieConflict(Exception):133+ """134+ Attempted to lookup a cookie by name, but multiple cookies existed.135+ """added:httpx/interfaces.py+227 added
1+import enum2+import ssl3+import typing4+from types import TracebackType5+6+from .config import CertTypes, PoolLimits, TimeoutConfig, TimeoutTypes, VerifyTypes7+from .models import (8+ AsyncRequest,9+ AsyncRequestData,10+ AsyncResponse,11+ HeaderTypes,12+ QueryParamTypes,13+ Request,14+ RequestData,15+ Response,16+ URLTypes,17+)18+19+20+class Protocol(str, enum.Enum):21+ HTTP_11 = "HTTP/1.1"22+ HTTP_2 = "HTTP/2"23+24+25+class AsyncDispatcher:26+ """27+ Base class for async dispatcher classes, that handle sending the request.28+29+ 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+ """33+34+ 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)48+49+ 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: nocover57+58+ async def close(self) -> None:59+ pass # pragma: nocover60+61+ async def __aenter__(self) -> "AsyncDispatcher":62+ return self63+64+ 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()71+72+73+class Dispatcher:74+ """75+ Base class for syncronous dispatcher classes, that handle sending the request.76+77+ 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+ """81+82+ 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)96+97+ 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: nocover105+106+ def close(self) -> None:107+ pass # pragma: nocover108+109+ def __enter__(self) -> "Dispatcher":110+ return self111+112+ 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()119+120+121+class 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+ """127+128+ async def read(129+ self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None130+ ) -> bytes:131+ raise NotImplementedError() # pragma: no cover132+133+134+class 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+ """140+141+ def write_no_block(self, data: bytes) -> None:142+ raise NotImplementedError() # pragma: no cover143+144+ async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:145+ raise NotImplementedError() # pragma: no cover146+147+ async def close(self) -> None:148+ raise NotImplementedError() # pragma: no cover149+150+151+class BasePoolSemaphore:152+ """153+ A semaphore for use with connection pooling.154+155+ Abstracts away any asyncio-specfic interfaces.156+ """157+158+ async def acquire(self) -> None:159+ raise NotImplementedError() # pragma: no cover160+161+ def release(self) -> None:162+ raise NotImplementedError() # pragma: no cover163+164+165+class 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 cover174+175+ def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:176+ raise NotImplementedError() # pragma: no cover177+178+ async def run_in_threadpool(179+ self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any180+ ) -> typing.Any:181+ raise NotImplementedError() # pragma: no cover182+183+ async def iterate_in_threadpool(self, iterator): # type: ignore184+ class IterationComplete(Exception):185+ pass186+187+ def next_wrapper(iterator): # type: ignore188+ try:189+ return next(iterator)190+ except StopIteration:191+ raise IterationComplete()192+193+ while True:194+ try:195+ yield await self.run_in_threadpool(next_wrapper, iterator)196+ except IterationComplete:197+ break198+199+ def run(200+ self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any201+ ) -> typing.Any:202+ raise NotImplementedError() # pragma: no cover203+204+ def iterate(self, async_iterator): # type: ignore205+ while True:206+ try:207+ yield self.run(async_iterator.__anext__)208+ except StopAsyncIteration:209+ break210+211+ def background_manager(212+ self, coroutine: typing.Callable, args: typing.Any213+ ) -> "BaseBackgroundManager":214+ raise NotImplementedError() # pragma: no cover215+216+217+class BaseBackgroundManager:218+ async def __aenter__(self) -> "BaseBackgroundManager":219+ raise NotImplementedError() # pragma: no cover220+221+ 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 coveradded:httpx/models.py+1168 added
1+import cgi2+import email.message3+import json as jsonlib4+import typing5+import urllib.request6+from collections.abc import MutableMapping7+from http.cookiejar import Cookie, CookieJar8+from urllib.parse import parse_qsl, urlencode9+10+import chardet11+import rfc398612+13+from .config import USER_AGENT14+from .decoders import (15+ ACCEPT_ENCODING,16+ SUPPORTED_DECODERS,17+ Decoder,18+ IdentityDecoder,19+ MultiDecoder,20+)21+from .exceptions import (22+ CookieConflict,23+ HttpError,24+ InvalidURL,25+ ResponseClosed,26+ ResponseNotRead,27+ StreamConsumed,28+)29+from .multipart import multipart_encode30+from .status_codes import StatusCode31+from .utils import (32+ guess_json_utf,33+ is_known_encoding,34+ normalize_header_key,35+ normalize_header_value,36+)37+38+URLTypes = typing.Union["URL", str]39+40+QueryParamTypes = typing.Union[41+ "QueryParams",42+ typing.Mapping[str, str],43+ typing.List[typing.Tuple[typing.Any, typing.Any]],44+ str,45+]46+47+HeaderTypes = typing.Union[48+ "Headers",49+ typing.Dict[typing.AnyStr, typing.AnyStr],50+ typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],51+]52+53+CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]54+55+AuthTypes = typing.Union[56+ typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],57+ typing.Callable[["AsyncRequest"], "AsyncRequest"],58+]59+60+AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]61+62+RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]63+64+RequestFiles = 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+]74+75+AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]76+77+ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]78+79+80+class 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.components93+94+ # 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)99+100+ # Normalize scheme and domain name.101+ self.components = self.components.normalize()102+103+ # Add any query parameters.104+ if params:105+ query_string = str(QueryParams(params))106+ self.components = self.components.copy_with(query=query_string)107+108+ # 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.")114+115+ @property116+ def scheme(self) -> str:117+ return self.components.scheme or ""118+119+ @property120+ def authority(self) -> str:121+ return self.components.authority or ""122+123+ @property124+ def username(self) -> str:125+ userinfo = self.components.userinfo or ""126+ return userinfo.partition(":")[0]127+128+ @property129+ def password(self) -> str:130+ userinfo = self.components.userinfo or ""131+ return userinfo.partition(":")[2]132+133+ @property134+ def host(self) -> str:135+ return self.components.host or ""136+137+ @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)143+144+ @property145+ def path(self) -> str:146+ return self.components.path or "/"147+148+ @property149+ def query(self) -> str:150+ return self.components.query or ""151+152+ @property153+ def full_path(self) -> str:154+ path = self.path155+ if self.query:156+ path += "?" + self.query157+ return path158+159+ @property160+ def fragment(self) -> str:161+ return self.components.fragment or ""162+163+ @property164+ def is_ssl(self) -> bool:165+ return self.components.scheme == "https"166+167+ @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.host178+179+ @property180+ def is_relative_url(self) -> bool:181+ return not self.is_absolute_url182+183+ @property184+ def origin(self) -> "Origin":185+ return Origin(self)186+187+ def copy_with(self, **kwargs: typing.Any) -> "URL":188+ return URL(self.components.copy_with(**kwargs))189+190+ 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)196+197+ # 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))202+203+ def __hash__(self) -> int:204+ return hash(str(self))205+206+ def __eq__(self, other: typing.Any) -> bool:207+ return isinstance(other, URL) and str(self) == str(other)208+209+ def __str__(self) -> str:210+ return self.components.unsplit()211+212+ def __repr__(self) -> str:213+ class_name = self.__class__.__name__214+ url_str = str(self)215+ return f"{class_name}({url_str!r})"216+217+218+class Origin:219+ """220+ The URL scheme and authority information, as a comparable, hashable object.221+ """222+223+ 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.port229+230+ 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+ )237+238+ def __hash__(self) -> int:239+ return hash((self.is_ssl, self.host, self.port))240+241+242+class QueryParams(typing.Mapping[str, str]):243+ """244+ URL query parameters, as a multi-dict.245+ """246+247+ 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."250+251+ value = args[0] if args else kwargs252+253+ 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: ignore261+262+ self._list = [(str(k), str(v)) for k, v in items]263+ self._dict = {str(k): str(v) for k, v in items}264+265+ 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]267+268+ def keys(self) -> typing.KeysView:269+ return self._dict.keys()270+271+ def values(self) -> typing.ValuesView:272+ return self._dict.values()273+274+ def items(self) -> typing.ItemsView:275+ return self._dict.items()276+277+ def multi_items(self) -> typing.List[typing.Tuple[str, str]]:278+ return list(self._list)279+280+ 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 default284+285+ def __getitem__(self, key: typing.Any) -> str:286+ return self._dict[key]287+288+ def __contains__(self, key: typing.Any) -> bool:289+ return key in self._dict290+291+ def __iter__(self) -> typing.Iterator[typing.Any]:292+ return iter(self.keys())293+294+ def __len__(self) -> int:295+ return len(self._dict)296+297+ def __eq__(self, other: typing.Any) -> bool:298+ if not isinstance(other, self.__class__):299+ return False300+ return sorted(self._list) == sorted(other._list)301+302+ def __str__(self) -> str:303+ return urlencode(self._list)304+305+ def __repr__(self) -> str:306+ class_name = self.__class__.__name__307+ query_string = str(self)308+ return f"{class_name}({query_string!r})"309+310+311+class Headers(typing.MutableMapping[str, str]):312+ """313+ HTTP headers, as a case-insensitive multi-dict.314+ """315+316+ 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 = encoding332+333+ @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._encoding357+358+ @encoding.setter359+ def encoding(self, value: str) -> None:360+ self._encoding = value361+362+ @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._list369+370+ def keys(self) -> typing.List[str]: # type: ignore371+ return [key.decode(self.encoding) for key, value in self._list]372+373+ def values(self) -> typing.List[str]: # type: ignore374+ return [value.decode(self.encoding) for key, value in self._list]375+376+ 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+ ]381+382+ def get(self, key: str, default: typing.Any = None) -> typing.Any:383+ try:384+ return self[key]385+ except KeyError:386+ return default387+388+ 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)393+394+ values = [395+ item_value.decode(self.encoding)396+ for item_key, item_value in self._list397+ if item_key == get_header_key398+ ]399+400+ if not split_commas:401+ return values402+403+ split_values = []404+ for value in values:405+ split_values.extend([item.strip() for item in value.split(",")])406+ return split_values407+408+ def __getitem__(self, key: str) -> str:409+ """410+ Return a single header value.411+412+ 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)416+417+ items = []418+ for header_key, header_value in self._list:419+ if header_key == normalized_key:420+ items.append(header_value.decode(self.encoding))421+422+ if items:423+ return ", ".join(items)424+425+ raise KeyError(key)426+427+ 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)434+435+ found_indexes = []436+ for idx, (item_key, item_value) in enumerate(self._list):437+ if item_key == set_key:438+ found_indexes.append(idx)439+440+ for idx in reversed(found_indexes[1:]):441+ del self._list[idx]442+443+ 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))448+449+ def __delitem__(self, key: str) -> None:450+ """451+ Remove the header `key`.452+ """453+ del_key = key.lower().encode(self.encoding)454+455+ pop_indexes = []456+ for idx, (item_key, item_value) in enumerate(self._list):457+ if item_key == del_key:458+ pop_indexes.append(idx)459+460+ for idx in reversed(pop_indexes):461+ del self._list[idx]462+463+ 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 False469+470+ def __iter__(self) -> typing.Iterator[typing.Any]:471+ return iter(self.keys())472+473+ def __len__(self) -> int:474+ return len(self._list)475+476+ def __eq__(self, other: typing.Any) -> bool:477+ if not isinstance(other, Headers):478+ return False479+ return sorted(self._list) == sorted(other._list)480+481+ def __repr__(self) -> str:482+ class_name = self.__class__.__name__483+484+ encoding_str = ""485+ if self.encoding != "ascii":486+ encoding_str = f", encoding={self.encoding!r}"487+488+ 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})"493+494+495+class 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)511+512+ 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_type527+528+ def prepare(self) -> None:529+ content = getattr(self, "content", None) # type: bytes530+ is_streaming = getattr(self, "is_streaming", False)531+532+ auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]533+534+ 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.headers542+543+ 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"))559+560+ for item in reversed(auto_headers):561+ self.headers.raw.insert(0, item)562+563+ @property564+ def cookies(self) -> "Cookies":565+ if not hasattr(self, "_cookies"):566+ self._cookies = Cookies()567+ return self._cookies568+569+ 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})>"573+574+575+class 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+ )591+592+ 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 = data606+607+ self.prepare()608+609+ 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.content616+617+ 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.content623+624+625+class 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+ )641+642+ 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 = data656+657+ self.prepare()658+659+ def read(self) -> bytes:660+ if not hasattr(self, "content"):661+ self.content = b"".join([part for part in self.stream()])662+ return self.content663+664+ 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.content670+671+672+class 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)685+686+ self.request = request687+ self.on_close = on_close688+ self.next = None # typing.Optional[typing.Callable]689+690+ @property691+ def reason_phrase(self) -> str:692+ return StatusCode.get_reason_phrase(self.status_code)693+694+ @property695+ def url(self) -> typing.Optional[URL]:696+ """697+ Returns the URL for which the request was made.698+699+ Requires that `request` was provided when instantiating the response.700+ """701+ return None if self.request is None else self.request.url702+703+ @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._content714+715+ @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._text725+726+ @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._encoding736+737+ @encoding.setter738+ def encoding(self, value: str) -> None:739+ self._encoding = value740+741+ @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 None749+750+ parsed = cgi.parse_header(content_type)751+ media_type, params = parsed[0], parsed[-1]752+ if "charset" in params:753+ return params["charset"].strip("'\"")754+755+ # 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"760+761+ return None762+763+ @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"]769+770+ @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())783+784+ 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()790+791+ return self._decoder792+793+ @property794+ def is_redirect(self) -> bool:795+ return StatusCode.is_redirect(self.status_code) and "location" in self.headers796+797+ 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+ )805+806+ 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 = ""812+813+ if message:814+ raise HttpError(message)815+816+ 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)825+826+ @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._cookies833+834+ def __repr__(self) -> str:835+ return f"<Response [{self.status_code} {self.reason_phrase}]>"836+837+838+class 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+ )857+858+ self.history = [] if history is None else list(history)859+860+ 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 = content868+869+ 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._content876+877+ 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()888+889+ 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()900+901+ self.is_stream_consumed = True902+ async for part in self._raw_stream:903+ yield part904+ await self.close()905+906+ 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()915+916+917+class 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+ )936+937+ self.history = [] if history is None else list(history)938+939+ 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 = content947+948+ 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._content955+956+ 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()967+968+ 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()979+980+ self.is_stream_consumed = True981+ for part in self._raw_stream:982+ yield part983+ self.close()984+985+ 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()994+995+996+class Cookies(MutableMapping):997+ """998+ HTTP Cookies, as a mutable mapping.999+ """1000+1001+ 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 = cookies1013+1014+ 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)1021+1022+ self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore1023+1024+ 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)1030+1031+ 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)1056+1057+ 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.value1073+1074+ if value is None:1075+ return default1076+ return value1077+1078+ 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)1085+1086+ 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)1092+1093+ for cookie in remove:1094+ self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore1095+1096+ 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)1108+1109+ def update(self, cookies: CookieTypes = None) -> None: # type: ignore1110+ cookies = Cookies(cookies)1111+ for cookie in cookies.jar:1112+ self.jar.set_cookie(cookie)1113+1114+ def __setitem__(self, name: str, value: str) -> None:1115+ return self.set(name, value)1116+1117+ def __getitem__(self, name: str) -> str:1118+ value = self.get(name)1119+ if value is None:1120+ raise KeyError(name)1121+ return value1122+1123+ def __delitem__(self, name: str) -> None:1124+ return self.delete(name)1125+1126+ def __len__(self) -> int:1127+ return len(self.jar)1128+1129+ def __iter__(self) -> typing.Iterator[str]:1130+ return (cookie.name for cookie in self.jar)1131+1132+ def __bool__(self) -> bool:1133+ for cookie in self.jar:1134+ return True1135+ return False1136+1137+ class _CookieCompatRequest(urllib.request.Request):1138+ """1139+ Wraps a `Request` instance up in a compatability interface suitable1140+ for use with `CookieJar` operations.1141+ """1142+1143+ 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 = request1150+1151+ def add_unredirected_header(self, key: str, value: str) -> None:1152+ super().add_unredirected_header(key, value)1153+ self.request.headers[key] = value1154+1155+ class _CookieCompatResponse:1156+ """1157+ Wraps a `Request` instance up in a compatability interface suitable1158+ for use with `CookieJar` operations.1159+ """1160+1161+ def __init__(self, response: BaseResponse):1162+ self.response = response1163+1164+ 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 infoadded:httpx/multipart.py+106 added
1+import binascii2+import mimetypes3+import os4+import typing5+from io import BytesIO6+from urllib.parse import quote7+8+9+class Field:10+ def render_headers(self) -> bytes:11+ raise NotImplementedError() # pragma: nocover12+13+ def render_data(self) -> bytes:14+ raise NotImplementedError() # pragma: nocover15+16+17+class 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 = value25+26+ 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+ )31+32+ def render_data(self) -> bytes:33+ return (34+ self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")35+ )36+37+38+class 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+ )53+54+ def guess_content_type(self) -> str:55+ return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"56+57+ 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+ )74+75+ def render_data(self) -> bytes:76+ content = self.file.read()77+ return content.encode("utf-8") if isinstance(content, str) else content78+79+80+def 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)87+88+ for name, value in files.items():89+ yield FileField(name=name, value=value)90+91+92+def multipart_encode(data: dict, files: dict) -> typing.Tuple[bytes, str]:93+ body = BytesIO()94+ boundary = binascii.hexlify(os.urandom(16))95+96+ 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")101+102+ body.write(b"--%s--\r\n" % boundary)103+104+ content_type = "multipart/form-data; boundary=%s" % boundary.decode("ascii")105+106+ return body.getvalue(), content_typeadded:httpx/status_codes.py+131 added
1+from enum import IntEnum2+3+4+class 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+ """17+18+ def __new__(cls, value: int, phrase: str = "") -> "StatusCode":19+ obj = int.__new__(cls, value) # type: ignore20+ obj._value_ = value21+22+ obj.phrase = phrase23+ return obj24+25+ def __str__(self) -> str:26+ return str(self.value)27+28+ @classmethod29+ def get_reason_phrase(cls, value: int) -> str:30+ try:31+ return StatusCode(value).phrase # type: ignore32+ except ValueError:33+ return ""34+35+ @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+ )49+50+ @classmethod51+ def is_client_error(cls, value: int) -> bool:52+ return value >= 400 and value <= 49953+54+ @classmethod55+ def is_server_error(cls, value: int) -> bool:56+ return value >= 500 and value <= 59957+58+ # informational59+ CONTINUE = 100, "Continue"60+ SWITCHING_PROTOCOLS = 101, "Switching Protocols"61+ PROCESSING = 102, "Processing"62+63+ # 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"74+75+ # 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"84+85+ # 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"112+113+ # 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"125+126+127+codes = StatusCode128+129+# Include lower-case styles for `requests` compatability.130+for code in codes:131+ setattr(codes, code._name_.lower(), int(code))added:httpx/utils.py+66 added
1+import codecs2+import typing3+4+5+def 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()12+13+14+def 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")21+22+23+def 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 True32+33+34+# 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 * 338+39+40+def 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 Nonemodified:scripts/clean+2 added-2 removed
7 unmodified lines8 fi9 if [ -d 'htmlcov' ] ; then10 rm -r htmlcov11 fi12-if [ -d 'http3.egg-info' ] ; then13- rm -r http3.egg-info12+if [ -d 'httpx.egg-info' ] ; then13+ rm -r httpx.egg-info14 fimodified:scripts/lint+5 added-5 removed
5 unmodified lines6 fi7 8 set -x9 10-${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-defs15 16 scripts/cleanmodified:scripts/publish+1 added-1 removed
1 #!/bin/sh -e2 3-export PACKAGE="http3"3+export PACKAGE="httpx"4 export VERSION=`cat ${PACKAGE}/__version__.py | grep __version__ | sed "s/__version__ = //" | sed "s/'//g"`5 export PREFIX=""6 if [ -d 'venv' ] ; then7 export PREFIX="venv/bin/"21 unmodified linesmodified:scripts/test+1 added-1 removed
1 #!/bin/sh -e2 3-export PACKAGE="http3"3+export PACKAGE="httpx"4 export PREFIX=""5 if [ -d 'venv' ] ; then6 export PREFIX="venv/bin/"7 fi5 unmodified linesmodified:tests/client/test_async_client.py+16 added-16 removed
1 import pytest2 3-import http33+import httpx4 5 6 @pytest.mark.asyncio7 async 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 lines17 18 @pytest.mark.asyncio19 async 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 == 20024 25 26 @pytest.mark.asyncio27 async 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 == 20032 33 34 @pytest.mark.asyncio35 async 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 line42 43 44 @pytest.mark.asyncio45 async 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.content51 52 53 @pytest.mark.asyncio1 unmodified line55 async def hello_world():56 yield b"Hello, "57 yield b"world!"58 59- 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 == 20064 65 66 @pytest.mark.asyncio67 async 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 )73 74 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 None79 80 81 @pytest.mark.asyncio82 async 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!"88 89 90 @pytest.mark.asyncio91 async 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 == ""97 98 99 @pytest.mark.asyncio100 async 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 == 200105 106 107 @pytest.mark.asyncio108 async 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 == 200113 114 115 @pytest.mark.asyncio116 async 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 lines126 url = "http://127.0.0.1:8000/echo_body"127 headers = {"Expect": "100-continue"}128 data = b"Echo request body"129 130- async with http3.AsyncClient() as client:130+ async with httpx.AsyncClient() as client:131 response = await client.post(url, headers=headers, data=data)132 133 assert response.status_code == 200134 assert response.content == datamodified:tests/client/test_auth.py+1 added-1 removed
1 import json2 3-from http3 import (3+from httpx import (4 AsyncDispatcher,5 AsyncRequest,6 AsyncResponse,7 CertTypes,62 unmodified linesmodified:tests/client/test_client.py+17 added-17 removed
1 unmodified line2 import functools3 4 import pytest5 6-import http36+import httpx7 8 9 def threadpool(func):10 """14 unmodified lines25 26 @threadpool27 def 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]>"41 42 43 @threadpool44 def 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"49 50 51 @threadpool52 def 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"57 58 59 @threadpool60 def 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!"66 67 68 @threadpool69 def 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 lines77 78 79 @threadpool80 def 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 lines89 90 91 @threadpool92 def 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 )98 99 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 None104 105 106 @threadpool107 def 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"112 113 114 @threadpool115 def 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"120 121 122 @threadpool123 def 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"128 129 130 @threadpool131 def 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"136 137 138 @threadpool139 def 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"144 145 146 @threadpool147 def 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_urlmodified:tests/client/test_cookies.py+1 added-1 removed
1 import json2 from http.cookiejar import Cookie, CookieJar3 4-from http3 import (4+from httpx import (5 AsyncDispatcher,6 AsyncRequest,7 AsyncResponse,8 CertTypes,116 unmodified linesmodified:tests/client/test_redirects.py+1 added-1 removed
1 unmodified line2 from urllib.parse import parse_qs3 4 import pytest5 6-from http3 import (6+from httpx import (7 URL,8 AsyncClient,9 AsyncDispatcher,10 AsyncRequest,242 unmodified linesmodified:tests/dispatch/test_connection_pools.py+10 added-10 removed
1 import pytest2 3-import http33+import httpx4 5 6 @pytest.mark.asyncio7 async 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) == 18 unmodified lines24 async 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) == 18 unmodified lines41 async 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)46 47- 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) == 18 unmodified lines60 async 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 lines76 async 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 lines100 """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) == 03 unmodified lines112 async 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) == 04 unmodified lines125 async 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) == 0modified:tests/dispatch/test_connections.py+1 added-1 removed
1 import pytest2 3-from http3 import HTTPConnection3+from httpx import HTTPConnection4 5 6 @pytest.mark.asyncio7 async def test_get(server):38 unmodified linesmodified:tests/dispatch/test_http2.py+1 added-1 removed
1 import json2 3-from http3 import Client, Response3+from httpx import Client, Response4 5 from .utils import MockHTTP2Backend6 7 71 unmodified linesmodified:tests/dispatch/test_threaded.py+1 added-1 removed
1 import json2 3-from http3 import (3+from httpx import (4 CertTypes,5 Client,6 Dispatcher,7 Request,91 unmodified linesmodified:tests/dispatch/utils.py+1 added-1 removed
4 unmodified lines5 import h2.config6 import h2.connection7 import h2.events8 9-from http3 import (9+from httpx import (10 AsyncioBackend,11 BaseReader,12 BaseWriter,13 Protocol,109 unmodified linesmodified:tests/models/test_cookies.py+1 added-1 removed
1 import pytest2 3-from http3 import CookieConflict, Cookies3+from httpx import CookieConflict, Cookies4 5 6 def test_cookies():7 cookies = Cookies({"name": "value"})43 unmodified linesmodified:tests/models/test_headers.py+20 added-20 removed
1-import http31+import httpx2 3 4 def 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 h7 unmodified lines17 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")]23 24- 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'})"29 30 31 def 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 lines44 assert h.raw == [(b"b", b"4")]45 46 47 def 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_copy51 52 53 def 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"]57 58 59 def 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"]63 64 65 def 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"}69 70 71 def 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) == {}75 76 77 def 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'})"83 84 85 def 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')"91 92 93 def 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 lines104 """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"111 112 1 unmodified line114 """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"121 122 1 unmodified line124 """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"131 132 2 unmodified lines135 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 line145 def 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"]151 152- 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
1-from http3 import QueryParams1+from httpx import QueryParams2 3 4 def test_queryparams():5 q = QueryParams("a=123&a=456&b=789")28 unmodified linesmodified:tests/models/test_requests.py+16 added-16 removed
1 import pytest2 3-import http33+import httpx4 5 6 def 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')>"9 10 11 def 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.headers14 15 16 def 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"19 20 21 def 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"26 27 28 def 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 lines37 yield data # pragma: nocover38 39 data = streaming_body(b"test 123")40 41- 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"44 45 46 def test_override_host_header():47 headers = {"host": "1.2.3.4:80"}48 49- 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"51 52 53 def test_override_accept_encoding_header():54 headers = {"Accept-Encoding": "identity"}55 56- 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"58 59 60 def test_override_content_length_header():2 unmodified lines63 64 data = streaming_body(b"test 123")65 headers = {"Content-Length": "8"}66 67- 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"69 70 71 def 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 == "/"77 78 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"83 84 85 def 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")88 89- 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 line2 from unittest import mock3 4 import pytest5 6-import http36+import httpx7 8 9 def streaming_body():10 yield b"Hello, "5 unmodified lines16 yield b"world!"17 18 19 def 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!"24 25 26 def 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]>"29 30 31 def test_response_content_type_encoding():1 unmodified line33 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"40 41 1 unmodified line43 """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"50 51 2 unmodified lines54 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"61 62 3 unmodified lines66 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 line76 def 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"83 84 1 unmodified line86 """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"93 94 95 def 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"105 106 107 def 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"114 115 116 def test_read_response():117- response = http3.Response(200, content=b"Hello, world!")117+ response = httpx.Response(200, content=b"Hello, world!")118 119 assert response.status_code == 200120 assert response.text == "Hello, world!"121 assert response.encoding == "ascii"6 unmodified lines128 assert response.is_closed129 130 131 def test_raw_interface():132- response = http3.Response(200, content=b"Hello, world!")132+ response = httpx.Response(200, content=b"Hello, world!")133 134 raw = b""135 for part in response.raw():136 raw += part137 assert raw == b"Hello, world!"138 139 140 def test_stream_interface():141- response = http3.Response(200, content=b"Hello, world!")141+ response = httpx.Response(200, content=b"Hello, world!")142 143 content = b""144 for part in response.stream():145 content += part1 unmodified line147 148 149 @pytest.mark.asyncio150 async def test_async_stream_interface():151- response = http3.AsyncResponse(200, content=b"Hello, world!")151+ response = httpx.AsyncResponse(200, content=b"Hello, world!")152 153 content = b""154 async for part in response.stream():155 content += part156 assert content == b"Hello, world!"157 158 159 def test_stream_interface_after_read():160- response = http3.Response(200, content=b"Hello, world!")160+ response = httpx.Response(200, content=b"Hello, world!")161 162 response.read()163 164 content = b""3 unmodified lines168 169 170 @pytest.mark.asyncio171 async 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!")173 174 await response.read()175 176 content = b""2 unmodified lines179 assert content == b"Hello, world!"180 181 182 def test_streaming_response():183- response = http3.Response(200, content=streaming_body())183+ response = httpx.Response(200, content=streaming_body())184 185 assert response.status_code == 200186 assert not response.is_closed187 5 unmodified lines193 194 195 @pytest.mark.asyncio196 async def test_async_streaming_response():197- response = http3.AsyncResponse(200, content=async_streaming_body())197+ response = httpx.AsyncResponse(200, content=async_streaming_body())198 199 assert response.status_code == 200200 assert not response.is_closed201 4 unmodified lines206 assert response.is_closed207 208 209 def test_cannot_read_after_stream_consumed():210- response = http3.Response(200, content=streaming_body())210+ response = httpx.Response(200, content=streaming_body())211 212 content = b""213 for part in response.stream():214 content += part215 216- with pytest.raises(http3.StreamConsumed):216+ with pytest.raises(httpx.StreamConsumed):217 response.read()218 219 220 @pytest.mark.asyncio221 async 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())223 224 content = b""225 async for part in response.stream():226 content += part227 228- with pytest.raises(http3.StreamConsumed):228+ with pytest.raises(httpx.StreamConsumed):229 await response.read()230 231 232 def test_cannot_read_after_response_closed():233- response = http3.Response(200, content=streaming_body())233+ response = httpx.Response(200, content=streaming_body())234 235 response.close()236 237- with pytest.raises(http3.ResponseClosed):237+ with pytest.raises(httpx.ResponseClosed):238 response.read()239 240 241 @pytest.mark.asyncio242 async 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())244 245 await response.close()246 247- with pytest.raises(http3.ResponseClosed):247+ with pytest.raises(httpx.ResponseClosed):248 await response.read()249 250 251 def 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 line258 def 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() == data264 265 266 def 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"272 273 274 def 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() == data280 281 282 def 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
1-from http3 import URL1+from httpx import URL2 3 4 def test_idna_url():5 url = URL("http://中国.icom.museum:80/")39 unmodified linesmodified:tests/test_api.py+11 added-11 removed
1 unmodified line2 import functools3 4 import pytest5 6-import http36+import httpx7 8 9 def threadpool(func):10 """13 unmodified lines24 25 26 @threadpool27 def 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!"32 33 34 @threadpool35 def 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"39 40 3 unmodified lines44 yield b"Hello"45 yield b", "46 yield b"world!"47 48- 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"51 52 53 @threadpool54 def 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"58 59 60 @threadpool61 def 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"65 66 67 @threadpool68 def 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"72 73 74 @threadpool75 def 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"79 80 81 @threadpool82 def 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"86 87 88 @threadpool89 def 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
1 import pytest2 3-import http33+import httpx4 5 6 async def hello_world(scope, receive, send):7 status = 20031 unmodified lines39 raise ValueError()40 41 42 def 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!"47 48 49 def 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"54 55 56 def 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/")60 61 62 def 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 line2 import ssl3 4 import pytest5 6-import http36+import httpx7 8 9 @pytest.mark.asyncio10 async 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 True15 16 17 @pytest.mark.asyncio18 async 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()22 23 24 @pytest.mark.asyncio25 async 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 True30 31 32 @pytest.mark.asyncio33 async 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 True39 40 41 @pytest.mark.asyncio42 async 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 lines50 @pytest.mark.parametrize("password", [b"password", "password"])51 async 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_REQUIRED3 unmodified lines62 @pytest.mark.asyncio63 async 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 )69 70 with pytest.raises(ssl.SSLError):1 unmodified line72 73 74 @pytest.mark.asyncio75 async 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()79 80 81 @pytest.mark.asyncio82 async 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 False87 88 89 def test_ssl_repr():90- ssl = http3.SSLConfig(verify=False)90+ ssl = httpx.SSLConfig(verify=False)91 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"92 93 94 def 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)"97 98- 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 )103 104 105 def 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 )110 111 112 def 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)115 116 117 def 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)120 121 122 def 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)125 126 127 def 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)130 131 132 def 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 line2 3 import brotli4 import pytest5 6-import http36+import httpx7 8 9 def 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()13 14 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 == body17 18 19 def test_gzip():1 unmodified line21 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22 compressed_body = compressor.compress(body) + compressor.flush()23 24 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 == body27 28 29 def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)32 33 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 == body36 37 38 def test_multi():7 unmodified lines46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )48 49 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 == body52 53 54 def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)57 58 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 == body61 62 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 == body65 66 67 def test_streaming():4 unmodified lines72 yield compressor.compress(body)73 yield compressor.flush()74 75 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() == body79 80 1 unmodified line82 def 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.contentmodified:tests/test_multipart.py+1 added-1 removed
4 unmodified lines5 from unittest import mock6 7 import pytest8 9-from http3 import (9+from httpx import (10 CertTypes,11 Client,12 Dispatcher,13 multipart,111 unmodified linesmodified:tests/test_status_codes.py+6 added-6 removed
1-import http31+import httpx2 3 4 def 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"7 8 9 def test_lowercase_status_code():10- assert http3.codes.not_found == 40410+ assert httpx.codes.not_found == 40411 12 13 def 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"15 16 17 def 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
1 import pytest2 3-from http3 import (3+from httpx import (4 AsyncClient,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,46 unmodified linesmodified:tests/test_utils.py+1 added-1 removed
1 import pytest2 3-from http3.utils import guess_json_utf3+from httpx.utils import guess_json_utf4 5 6 @pytest.mark.parametrize(7 "encoding",32 unmodified linesmodified:tests/test_wsgi.py+5 added-5 removed
1 import sys2 3 import pytest4 5-import http35+import httpx6 7 8 def hello_world(environ, start_response):9 status = "200 OK"58 unmodified lines68 return [output]69 70 71 def 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!"76 77 78 def 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"83 84 85 def 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"90 91 92 def 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
1-site_name: HTTP32-site_description: The next generation HTTP client.1+site_name: HTTPX2+site_description: A next-generation HTTP client for Python.3 4 theme:5 name: 'material'6 7-repo_name: encode/http38-repo_url: https://github.com/encode/http37+repo_name: encode/httpx8+repo_url: https://github.com/encode/httpx9 edit_uri: ""10 11 nav:12 - Introduction: 'index.md'10 unmodified linesmodified:README.md+24 added-24 removed
1-# HTTP31+# HTTPX2 3-<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>12 13-HTTP3 is a next-generation HTTP client for Python 3.13+HTTPX is a next-generation HTTP client for Python 3.14 15 **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.*16 17 ---18 19 Let's get started...20 21 ```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_code27 2006 unmodified lines34 ```35 36 ## Features37 38-HTTP3 builds on the well-established usability of `requests`, and gives you:38+HTTPX builds on the well-established usability of `requests`, and gives you:39 40 * 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 lines68 69 Install with pip:70 71 ```shell72-$ pip install http372+$ pip install httpx73 ```74 75-HTTP3 requires Python 3.6+75+httpx requires Python 3.6+76 77 ## Documentation78 79-Project documentation is available at [www.encode.io/http3/](https://www.encode.io/http3/).79+Project documentation is available at [www.encode.io/httpx/](https://www.encode.io/httpx/).80 81-For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/http3/quickstart/).81+For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/httpx/quickstart/).82 83-For more advanced topics, see the [Advanced Usage](https://www.encode.io/http3/advanced/) section, or84-the specific topics on making [Parallel Requests](https://www.encode.io/http3/parallel/) or using the85-[Async Client](https://www.encode.io/http3/async/).83+For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section, or84+the specific topics on making [Parallel Requests](https://www.encode.io/httpx/parallel/) or using the85+[Async Client](https://www.encode.io/httpx/async/).86 87-The [Developer Interface](https://www.encode.io/http3/api/) provides a comprehensive API reference.87+The [Developer Interface](https://www.encode.io/httpx/api/) provides a comprehensive API reference.88 89 ## Dependencies90 91-The HTTP3 project relies on these excellent libraries:91+The httpx project relies on these excellent libraries:92 93 * `h2` - HTTP/2 support.94 * `h11` - HTTP/1.1 support.95 * `certifi` - SSL certificates.6 unmodified lines102 much of this work follows, as well as to `urllib3` for plenty of design103 inspiration around the lower level networking details.104 105 <p align="center">— ⭐️ —</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>