Skip to content
Myr

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

11 files+562 added−15 removed

added:docs/advanced.md+43 added
modified:docs/api.md+1 added-1 removed
modified:docs/async.md+2 added-3 removed
5 unmodified lines
6Async is a concurrency model that is far more efficient than multi-threading,7and can provide significant performance benefits and enable the use of8long-lived network connections such as WebSockets.910If you're working with an async web framework such as Sanic, Starlette, FastAPI,11Responder or Bocadillo, then you'll also want to use an async client for sending12outgoing HTTP requests.10If you're working with an async web framework then you'll also want to use an11async client for sending outgoing HTTP requests.1213## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.
44 unmodified lines
modified:docs/index.md+9 added-6 removed
39 unmodified lines
40HTTP3 builds on the well-established usability of `requests`, and gives you:4142* 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 lines
53* 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 Requests6869## Documentation7071For a run-through of all the basics, head over to the [QuickStart](quickstart.md).7272For more advanced topics, see the [Parallel Requests](parallel.md) or [Async Client](async.md) documentation.73For more advanced topics, see the [Advanced Usage](advanced.md) section, or74the specific topics on making [Parallel Requests](parallel.md) or using the75[Async Client](async.md).7677The [Developer Interface](api.md) provides a comprehensive API reference.7879## Dependencies
24 unmodified lines
added:http3/dispatch/asgi.py+176 added
1import asyncio2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import AsyncDispatcher6from ..models import AsyncRequest, AsyncResponse789class ASGIDispatch(AsyncDispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = http3.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the ASGIDispatch class:2425 ```26 dispatch = http3.ASGIDispatch(27 app=app,28 root_path="/submount",29 client=("1.2.3.4", 123)30 )31 client = http3.Client(dispatch=dispatch)32 ```33 """3435 def __init__(36 self,37 app: typing.Callable,38 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 = client4445 async def send(46 self,47 request: AsyncRequest,48 verify: VerifyTypes = None,49 cert: CertTypes = None,50 timeout: TimeoutTypes = None,51 ) -> AsyncResponse:5253 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()7273 async def receive() -> dict:74 nonlocal request_stream7576 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}8182 async def send(message: dict) -> None:83 nonlocal status_code, headers, response_started, response_body8485 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()9697 async def run_app() -> None:98 nonlocal app, scope, receive, send, app_exc, response_body99100 try:101 await app(scope, receive, send)102 except Exception as exc:103 app_exc = exc104 finally:105 await response_body.done()106107 # 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())115116 tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]117118 await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)119120 if app_exc is not None:121 raise app_exc122123 assert response_started.is_set, "application did not return a response."124 assert status_code is not None125 assert headers is not None126127 async def on_close() -> None:128 nonlocal app_task129 await app_task130 if app_exc is not None:131 raise app_exc132133 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 )141142143class BodyIterator:144 """145 Provides a byte-iterator interface that the client can use to146 ingest the response content from.147 """148149 def __init__(self) -> None:150 self._queue = asyncio.Queue(151 maxsize=1152 ) # type: asyncio.Queue[typing.Union[bytes, object]]153 self._done = object()154155 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 data165166 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)171172 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
1import io2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..interfaces import Dispatcher6from ..models import Request, Response789class WSGIDispatch(Dispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = http3.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the WSGIDispatch class:2425 ```26 dispatch = http3.WSGIDispatch(27 app=app,28 script_name="/submount",29 remote_addr="1.2.3.4"30 )31 client = http3.Client(dispatch=dispatch)32 ```33 """3435 def __init__(36 self,37 app: typing.Callable,38 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_addr4445 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] = value7374 seen_status = None75 seen_response_headers = None76 seen_exc_info = None7778 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_info8586 result = self.app(environ, start_response)8788 assert seen_status is not None89 assert seen_response_headers is not None90 if seen_exc_info:91 raise seen_exc_info[1]9293 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 )100101102class BodyStream(io.RawIOBase):103 def __init__(self, iterator: typing.Iterator[bytes]) -> None:104 self._iterator = iterator105 self._buffer = b""106 self._closed = False107108 def read(self, size: int = -1) -> bytes:109 if self._closed:110 return b""111112 if size == -1:113 return self.readall()114115 try:116 while len(self._buffer) < size:117 self._buffer += next(self._iterator)118 except StopIteration:119 self._closed = True120 return self._buffer121122 output = self._buffer[:size]123 self._buffer = self._buffer[size:]124 return output125126 def readall(self) -> bytes:127 if self._closed:128 raise OSError("Stream closed") # pragma: nocover129130 for chunk in self._iterator:131 self._buffer += chunk132133 self._closed = True134 return self._buffer135136 def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover137 output = self.read(len(b))138 count = len(output)139 b[:count] = output140 return count141142 def write(self, b: bytes) -> int:143 raise OSError("Operation not supported") # pragma: nocover144145 def fileno(self) -> int:146 raise OSError("Operation not supported") # pragma: nocover147148 def seek(self, offset: int, whence: int = 0) -> int:149 raise OSError("Operation not supported") # pragma: nocover150151 def truncate(self, size: int = None) -> int:152 raise OSError("Operation not supported") # pragma: nocover
modified:http3/client.py+12 added
1import inspect2import typing3from types import TracebackType45from .auth import HTTPBasicAuth
6 unmodified lines
12 PoolLimits,13 TimeoutTypes,14 VerifyTypes,15)16from .dispatch.asgi import ASGIDispatch17from .dispatch.connection_pool import ConnectionPool18from .dispatch.threaded import ThreadedDispatcher19from .dispatch.wsgi import WSGIDispatch20from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects21from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher22from .models import (23 URL,
27 unmodified lines
51 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()6061 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)6869 if dispatch is None:70 async_dispatch = ConnectionPool(71 verify=verify,72 cert=cert,
799 unmodified lines
added:tests/test_asgi.py+65 added
1import pytest23import http3456async 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)))]1011 await send({"type": "http.response.start", "status": status, "headers": headers})12 await send({"type": "http.response.body", "body": output})131415async def echo_body(scope, receive, send):16 status = 20017 headers = [(b"content-type", "text/plain")]1819 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})262728async def raise_exc(scope, receive, send):29 raise ValueError()303132async 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)))]3637 await send({"type": "http.response.start", "status": status, "headers": headers})38 await send({"type": "http.response.body", "body": output})39 raise ValueError()404142def 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!"474849def 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"545556def test_asgi_exc():57 client = http3.Client(app=raise_exc)58 with pytest.raises(ValueError):59 response = client.get("http://www.example.org/")606162def 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
1import sys23import pytest45import http3678def hello_world(environ, start_response):9 status = "200 OK"10 output = b"Hello, World!"1112 response_headers = [13 ("Content-type", "text/plain"),14 ("Content-Length", str(len(output))),15 ]1617 start_response(status, response_headers)1819 return [output]202122def echo_body(environ, start_response):23 status = "200 OK"24 output = environ["wsgi.input"].read()2526 response_headers = [27 ("Content-type", "text/plain"),28 ("Content-Length", str(len(output))),29 ]3031 start_response(status, response_headers)3233 return [output]343536def echo_body_with_response_stream(environ, start_response):37 status = "200 OK"3839 response_headers = [("Content-Type", "text/plain")]4041 start_response(status, response_headers)4243 def output_generator(f):44 while True:45 output = f.read(2)46 if not output:47 break48 yield output4950 return output_generator(f=environ["wsgi.input"])515253def raise_exc(environ, start_response):54 status = "500 Server Error"55 output = b"Nope!"5657 response_headers = [58 ("Content-type", "text/plain"),59 ("Content-Length", str(len(output))),60 ]6162 try:63 raise ValueError()64 except:65 exc_info = sys.exc_info()66 start_response(status, response_headers, exc_info=exc_info)6768 return [output]697071def 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!"767778def 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"838485def 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"909192def 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
modified:README.md+6 added-5 removed
37 unmodified lines
38HTTP3 builds on the well-established usability of `requests`, and gives you:3940* A requests-compatible API.41* HTTP/2 and HTTP/1.1 support.42* Support for issuing HTTP requests in parallel.43* Standard synchronous interface, but with `async`/`await` support if you need it.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 lines
51* 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 Requests6667## Installation68
36 unmodified lines