README.md
This file
Path
README.md
90 lines · 2.1 KiB · Markdown
Last changed by
Only serve http requests, ignore websocket and lifespan eventsTom Christiebefore adoption3d6aba6
History of this fileTake it
StuffTom Christiebefore adoption30530d4
lines 1–10why, one step back1# HTTPCore23```python4import httpcore56response = await httpcore.request('GET', 'http://example.com')7assert response.status_code == 2008assert response.body == b'Hello, world'9```10Update READMETom Christiebefore adoption68b80dc
line 11why, one step back11Top-level API...StuffTom Christiebefore adoption30530d4
lines 12–21why, one step back1213```python14response = await httpcore.request(method, url, [headers], [body], [stream])15```1617Explicit PoolManager...1819```python20async with httpcore.PoolManager([ssl], [timeout], [limits]) as pool:21 response = await pool.request(method, url, [headers], [body], [stream])Update READMETom Christiebefore adoption68b80dc
lines 22–29why, one step back22```2324Streaming...2526```python27response = await httpcore.request(method, url, stream=True)28async for part in response.stream():29 ...Added proxy exampleTom Christiebefore adoption87b21b0
lines 30–45why, one step back30```3132The level of abstraction fits in really well if you're just writing at33the raw ASGI level. Eg. Here's an how an ASGI gateway server looks against the34API, including streaming uploads and downloads...3536```python37import httpcore383940class GatewayServer:41 def __init__(self, base_url):42 self.base_url = base_url43 self.pool = httpcore.PoolManager()4445 async def __call__(self, scope, receive, send):Only serve http requests, ignore websocket and lifespan eventsTom Christiebefore adoption3d6aba6
line 46why, one step back46 assert scope['type'] == 'http'Added proxy exampleTom Christiebefore adoption87b21b0
lines 47–89why, one step back47 path = scope['path']48 query = scope['query_string']49 method = scope['method']50 headers = scope['headers']5152 url = self.base_url + path53 if query:54 url += '?' + query.decode()5556 async def body():57 nonlocal receive5859 while True:60 message = await receive()61 yield message.get('body', b'')62 if not message.get('more_body', False):63 break6465 response = await self.pool.request(66 method, url, headers=headers, body=body, stream=True67 )6869 await send({70 'type': 'http.response.start',71 'status': response.status_code,72 'headers': response.headers73 })74 async for data in response.stream():75 await send({76 'type': 'http.response.body',77 'body': data,78 'more_body': True79 })80 await send({'type': 'http.response.body'})818283app = GatewayServer('http://example.org')84```8586Run with...8788```shell89uvicorn example:appStuffTom Christiebefore adoption30530d4
line 90why, one step back90```