Support WSGI and ASGI apps. (#94)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add 'Client(app=...)' support * Add ASGI support with Client(app=app) * Improve exc cases when using client with ASGI * Tighten up exception handling when using as a test client * Fix up stream I/O for WSGI/ASGI apps * Docs for WSGI/ASGI integration
authored by Tom Christie · committed by GitHub · parent fdc4ab2 · Browse files · 11 files·+562 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+562 added−15 removed
- tests:+160 added−0 removed
- other:+402 added−15 removed
Provenance
- Commit
bb86970- Tree
b0b2da2- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
fdc4ab2
11 files changed+562 added−15 removed
added:docs/advanced.md+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243# Advanced Usage
## Client Instances
Using a Client instance to make requests will give you HTTP connection pooling,will provide cookie persistence, and allows you to apply configuration acrossall outgoing requests.
```python>>> client = http3.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 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.* 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 http3
app = Flask(__name__)
@app.route("/")def hello(): return "Hello World!"
client = http3.Client(app=app)r = client.get('http://example/')assert r.status_code == 200assert r.text == "Hello World!"```modified:docs/api.md+1 added-1 removed
18 unmodified lines19202122232324252627119 unmodified linesExpand all18 unmodified lines>>> client = http3.Client()>>> response = client.get('https://example.org')```
* `def __init__([auth], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [dispatch])`* `def __init__([auth], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [app], [dispatch])`* `def .get(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`* `def .options(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`* `def .head(url, [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`* `def .post(url, [data], [json], [params], [headers], [cookies], [auth], [stream], [allow_redirects], [verify], [cert], [timeout])`119 unmodified linesExpand allmodified:docs/async.md+2 added-3 removed
5 unmodified lines6 Async is a concurrency model that is far more efficient than multi-threading,7 and can provide significant performance benefits and enable the use of8 long-lived network connections such as WebSockets.9 10-If you're working with an async web framework such as Sanic, Starlette, FastAPI,11-Responder or Bocadillo, then you'll also want to use an async client for sending12-outgoing HTTP requests.10+If you're working with an async web framework then you'll also want to use an11+async client for sending outgoing HTTP requests.12 13 ## Making Async requests14 15 To make asynchronous requests, you'll need an `AsyncClient`.44 unmodified linesmodified:docs/index.md+9 added-6 removed
39 unmodified lines40 HTTP3 builds on the well-established usability of `requests`, and gives you:41 42 * A requests-compatible API.43 * HTTP/2 and HTTP/1.1 support.44-* Support for issuing HTTP requests in parallel.45-* Standard synchronous interface, but with `async`/`await` support if you need it.44+* Support for [issuing HTTP requests in parallel](parallel.md). *(Coming soon)*45+* Standard synchronous interface, but [with `async`/`await` support if you need it](async.md).46+* Ability to [make requests directly to WSGI or ASGI applications](advanced.md#calling-into-python-web-apps).47 * Strict timeouts everywhere.48 * Fully type annotated.49 * 100% test coverage.50 2 unmodified lines53 * International Domains and URLs54 * Keep-Alive & Connection Pooling55 * Sessions with Cookie Persistence56 * Browser-style SSL Verification56-* Basic/Digest Authentication *Digest is still TODO*57+* Basic/Digest Authentication *(Digest is still TODO)*58 * Elegant Key/Value Cookies59 * Automatic Decompression60 * Automatic Content Decoding61 * Unicode Response Bodies62 * Multipart File Uploads62-* HTTP(S) Proxy Support *TODO*63+* HTTP(S) Proxy Support *(TODO)*64 * Connection Timeouts65 * Streaming Downloads65-* .netrc Support *TODO*66+* .netrc Support *(TODO)*67 * Chunked Requests68 69 ## Documentation70 71 For a run-through of all the basics, head over to the [QuickStart](quickstart.md).72 72-For more advanced topics, see the [Parallel Requests](parallel.md) or [Async Client](async.md) documentation.73+For more advanced topics, see the [Advanced Usage](advanced.md) section, or74+the specific topics on making [Parallel Requests](parallel.md) or using the75+[Async Client](async.md).76 77 The [Developer Interface](api.md) provides a comprehensive API reference.78 79 ## Dependencies24 unmodified linesadded:http3/dispatch/asgi.py+176 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 = 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+ root_path: str = "",39+ client: typing.Tuple[str, int] = ("127.0.0.1", 123),40+ ) -> None:41+ self.app = app42+ self.root_path = root_path43+ self.client = client44+45+ async def send(46+ self,47+ request: AsyncRequest,48+ verify: VerifyTypes = None,49+ cert: CertTypes = None,50+ timeout: TimeoutTypes = None,51+ ) -> AsyncResponse:52+53+ scope = {54+ "type": "http",55+ "asgi": {"version": "3.0"},56+ "method": request.method,57+ "headers": request.headers.raw,58+ "scheme": request.url.scheme,59+ "path": request.url.path,60+ "query": request.url.query.encode("ascii"),61+ "server": request.url.host,62+ "client": self.client,63+ "root_path": self.root_path,64+ }65+ app = self.app66+ app_exc = None67+ status_code = None68+ headers = None69+ response_started = asyncio.Event()70+ response_body = BodyIterator()71+ request_stream = request.stream()72+73+ async def receive() -> dict:74+ nonlocal request_stream75+76+ try:77+ body = await request_stream.__anext__()78+ except StopAsyncIteration:79+ return {"type": "http.request", "body": b"", "more_body": False}80+ return {"type": "http.request", "body": body, "more_body": True}81+82+ async def send(message: dict) -> None:83+ nonlocal status_code, headers, response_started, response_body84+85+ if message["type"] == "http.response.start":86+ status_code = message["status"]87+ headers = message.get("headers", [])88+ response_started.set()89+ elif message["type"] == "http.response.body":90+ body = message.get("body", b"")91+ more_body = message.get("more_body", False)92+ if body:93+ await response_body.put(body)94+ if not more_body:95+ await response_body.done()96+97+ async def run_app() -> None:98+ nonlocal app, scope, receive, send, app_exc, response_body99+100+ try:101+ await app(scope, receive, send)102+ except Exception as exc:103+ app_exc = exc104+ finally:105+ await response_body.done()106+107+ # Really we'd like to push all `asyncio` logic into concurrency.py,108+ # with a standardized interface, so that we can support other event109+ # loop implementations, such as Trio and Curio.110+ # That's a bit fiddly here, so we're not yet supporting using a custom111+ # `ConcurrencyBackend` with the `Client(app=asgi_app)` case.112+ loop = asyncio.get_event_loop()113+ app_task = loop.create_task(run_app())114+ response_task = loop.create_task(response_started.wait())115+116+ tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]117+118+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)119+120+ if app_exc is not None:121+ raise app_exc122+123+ assert response_started.is_set, "application did not return a response."124+ assert status_code is not None125+ assert headers is not None126+127+ async def on_close() -> None:128+ nonlocal app_task129+ await app_task130+ if app_exc is not None:131+ raise app_exc132+133+ return AsyncResponse(134+ status_code=status_code,135+ protocol="HTTP/1.1",136+ headers=headers,137+ content=response_body.iterate(),138+ on_close=on_close,139+ request=request,140+ )141+142+143+class BodyIterator:144+ """145+ Provides a byte-iterator interface that the client can use to146+ ingest the response content from.147+ """148+149+ def __init__(self) -> None:150+ self._queue = asyncio.Queue(151+ maxsize=1152+ ) # type: asyncio.Queue[typing.Union[bytes, object]]153+ self._done = object()154+155+ async def iterate(self) -> typing.AsyncIterator[bytes]:156+ """157+ A byte-iterator, used by the client to consume the response body.158+ """159+ while True:160+ data = await self._queue.get()161+ if data is self._done:162+ break163+ assert isinstance(data, bytes)164+ yield data165+166+ async def put(self, data: bytes) -> None:167+ """168+ Used by the server to add data to the response body.169+ """170+ await self._queue.put(data)171+172+ async def done(self) -> None:173+ """174+ Used by the server to signal the end of the response body.175+ """176+ await self._queue.put(self._done)added:http3/dispatch/wsgi.py+152 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 = 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+ script_name: str = "",39+ remote_addr: str = "127.0.0.1",40+ ) -> None:41+ self.app = app42+ self.script_name = script_name43+ self.remote_addr = remote_addr44+45+ def send(46+ self,47+ request: Request,48+ verify: VerifyTypes = None,49+ cert: CertTypes = None,50+ timeout: TimeoutTypes = None,51+ ) -> Response:52+ environ = {53+ "wsgi.version": (1, 0),54+ "wsgi.url_scheme": request.url.scheme,55+ "wsgi.input": BodyStream(request.stream()),56+ "wsgi.errors": io.BytesIO(),57+ "wsgi.multithread": True,58+ "wsgi.multiprocess": False,59+ "wsgi.run_once": False,60+ "REQUEST_METHOD": request.method,61+ "SCRIPT_NAME": self.script_name,62+ "PATH_INFO": request.url.path,63+ "QUERY_STRING": request.url.query,64+ "SERVER_NAME": request.url.host,65+ "SERVER_PORT": str(request.url.port),66+ "REMOTE_ADDR": self.remote_addr,67+ }68+ for key, value in request.headers.items():69+ key = key.upper().replace("-", "_")70+ if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):71+ key = "HTTP_" + key72+ environ[key] = value73+74+ seen_status = None75+ seen_response_headers = None76+ seen_exc_info = None77+78+ def start_response(79+ status: str, response_headers: list, exc_info: typing.Any = None80+ ) -> None:81+ nonlocal seen_status, seen_response_headers, seen_exc_info82+ seen_status = status83+ seen_response_headers = response_headers84+ seen_exc_info = exc_info85+86+ result = self.app(environ, start_response)87+88+ assert seen_status is not None89+ assert seen_response_headers is not None90+ if seen_exc_info:91+ raise seen_exc_info[1]92+93+ return Response(94+ status_code=int(seen_status.split()[0]),95+ protocol="HTTP/1.1",96+ headers=seen_response_headers,97+ content=(chunk for chunk in result),98+ on_close=getattr(result, "close", None),99+ )100+101+102+class BodyStream(io.RawIOBase):103+ def __init__(self, iterator: typing.Iterator[bytes]) -> None:104+ self._iterator = iterator105+ self._buffer = b""106+ self._closed = False107+108+ def read(self, size: int = -1) -> bytes:109+ if self._closed:110+ return b""111+112+ if size == -1:113+ return self.readall()114+115+ try:116+ while len(self._buffer) < size:117+ self._buffer += next(self._iterator)118+ except StopIteration:119+ self._closed = True120+ return self._buffer121+122+ output = self._buffer[:size]123+ self._buffer = self._buffer[size:]124+ return output125+126+ def readall(self) -> bytes:127+ if self._closed:128+ raise OSError("Stream closed") # pragma: nocover129+130+ for chunk in self._iterator:131+ self._buffer += chunk132+133+ self._closed = True134+ return self._buffer135+136+ def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover137+ output = self.read(len(b))138+ count = len(output)139+ b[:count] = output140+ return count141+142+ def write(self, b: bytes) -> int:143+ raise OSError("Operation not supported") # pragma: nocover144+145+ def fileno(self) -> int:146+ raise OSError("Operation not supported") # pragma: nocover147+148+ def seek(self, offset: int, whence: int = 0) -> int:149+ raise OSError("Operation not supported") # pragma: nocover150+151+ def truncate(self, size: int = None) -> int:152+ raise OSError("Operation not supported") # pragma: nocovermodified:http3/client.py+12 added
1+import inspect2 import typing3 from types import TracebackType4 5 from .auth import HTTPBasicAuth6 unmodified lines12 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 RedirectBodyUnavailable, RedirectLoop, TooManyRedirects21 from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher22 from .models import (23 URL,27 unmodified lines51 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,52 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,53 max_redirects: int = DEFAULT_MAX_REDIRECTS,54 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,55+ app: typing.Callable = None,56 backend: ConcurrencyBackend = None,57 ):58 if backend is None:59 backend = AsyncioBackend()60 61+ if app is not None:62+ param_count = len(inspect.signature(app).parameters)63+ assert param_count in (2, 3)64+ if param_count == 2:65+ dispatch = WSGIDispatch(app=app)66+ else:67+ dispatch = ASGIDispatch(app=app)68+69 if dispatch is None:70 async_dispatch = ConnectionPool(71 verify=verify,72 cert=cert,799 unmodified linesadded:tests/test_asgi.py+65 added
1+import pytest2+3+import http34+5+6+async def hello_world(scope, receive, send):7+ status = 2008+ output = b"Hello, World!"9+ headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]10+11+ await send({"type": "http.response.start", "status": status, "headers": headers})12+ await send({"type": "http.response.body", "body": output})13+14+15+async def echo_body(scope, receive, send):16+ status = 20017+ headers = [(b"content-type", "text/plain")]18+19+ await send({"type": "http.response.start", "status": status, "headers": headers})20+ more_body = True21+ while more_body:22+ message = await receive()23+ body = message.get("body", b"")24+ more_body = message.get("more_body", False)25+ await send({"type": "http.response.body", "body": body, "more_body": more_body})26+27+28+async def raise_exc(scope, receive, send):29+ raise ValueError()30+31+32+async def raise_exc_after_response(scope, receive, send):33+ status = 20034+ output = b"Hello, World!"35+ headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]36+37+ await send({"type": "http.response.start", "status": status, "headers": headers})38+ await send({"type": "http.response.body", "body": output})39+ raise ValueError()40+41+42+def test_asgi():43+ client = http3.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)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)58+ with pytest.raises(ValueError):59+ response = client.get("http://www.example.org/")60+61+62+def test_asgi_exc_after_response():63+ client = http3.Client(app=raise_exc_after_response)64+ with pytest.raises(ValueError):65+ response = client.get("http://www.example.org/")added:tests/test_wsgi.py+95 added
1+import sys2+3+import pytest4+5+import http36+7+8+def hello_world(environ, start_response):9+ status = "200 OK"10+ output = b"Hello, World!"11+12+ response_headers = [13+ ("Content-type", "text/plain"),14+ ("Content-Length", str(len(output))),15+ ]16+17+ start_response(status, response_headers)18+19+ return [output]20+21+22+def echo_body(environ, start_response):23+ status = "200 OK"24+ output = environ["wsgi.input"].read()25+26+ response_headers = [27+ ("Content-type", "text/plain"),28+ ("Content-Length", str(len(output))),29+ ]30+31+ start_response(status, response_headers)32+33+ return [output]34+35+36+def echo_body_with_response_stream(environ, start_response):37+ status = "200 OK"38+39+ response_headers = [("Content-Type", "text/plain")]40+41+ start_response(status, response_headers)42+43+ def output_generator(f):44+ while True:45+ output = f.read(2)46+ if not output:47+ break48+ yield output49+50+ return output_generator(f=environ["wsgi.input"])51+52+53+def raise_exc(environ, start_response):54+ status = "500 Server Error"55+ output = b"Nope!"56+57+ response_headers = [58+ ("Content-type", "text/plain"),59+ ("Content-Length", str(len(output))),60+ ]61+62+ try:63+ raise ValueError()64+ except:65+ exc_info = sys.exc_info()66+ start_response(status, response_headers, exc_info=exc_info)67+68+ return [output]69+70+71+def test_wsgi():72+ client = http3.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)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)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)94+ with pytest.raises(ValueError):95+ response = client.get("http://www.example.org/")modified:mkdocs.yml+1 added
9 unmodified lines1011121314151617184 unmodified lines9 unmodified lines
nav: - Introduction: 'index.md' - QuickStart: 'quickstart.md' - Advanced Usage: 'advanced.md' - Parallel Requests: 'parallel.md' - Async Client: 'async.md' - Requests Compatibility: 'compatibility.md' - Developer Interface: 'api.md'4 unmodified linesmodified:README.md+6 added-5 removed
37 unmodified lines38 HTTP3 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.43-* Standard synchronous interface, but with `async`/`await` support if you need it.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).45 * Strict timeouts everywhere.46 * Fully type annotated.47 * 100% test coverage.48 2 unmodified lines51 * International Domains and URLs52 * Keep-Alive & Connection Pooling53 * Sessions with Cookie Persistence54 * Browser-style SSL Verification54-* Basic/Digest Authentication *Digest is still TODO*55+* Basic/Digest Authentication *(Digest is still TODO)*56 * Elegant Key/Value Cookies57 * Automatic Decompression58 * Automatic Content Decoding59 * Unicode Response Bodies60 * Multipart File Uploads60-* HTTP(S) Proxy Support *TODO*61+* HTTP(S) Proxy Support *(TODO)*62 * Connection Timeouts63 * Streaming Downloads63-* .netrc Support *TODO*64+* .netrc Support *(TODO)*65 * Chunked Requests66 67 ## Installation68 36 unmodified lines