Improve GatewayService example
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 1124cc4 · Browse files · 1 file·+37 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+37 added−10 removed
- other:+37 added−10 removed
Provenance
- Commit
9d59a5a- Tree
61c2597- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
1124cc4
1 file changed+37 added−10 removed
modified:README.md+37 added-10 removed
108 unmodified linesExpand all1091101111121131131141151161171181191201211191221231241251261271281291301311322 unmodified lines1351361371381391401301311321331341351361411421431441451461471481491381501511521531541551561571581591601611621631641651661671681691701711721731741754 unmodified lines108 unmodified linesExpand all assert scope['type'] == 'http' path = scope['path'] query = scope['query_string'] method = scope['method'] headers = scope['headers'] headers = [ (k, v) for (k, v) in scope['headers'] if k not in (b'host', b'content-length', b'transfer-encoding') ]
url = self.base_url + path if query: url += '?' + query.decode()
body = self.stream_body(receive) initial_body, more_body = await self.initial_body(receive) if more_body: # Streaming request. body = self.stream_body(receive, initial_body) else: # Standard request. body = initial_body
response = await self.http.request( method, url, headers=headers, body=body, stream=True )2 unmodified lines 'type': 'http.response.start', 'status': response.status_code, 'headers': response.headers }) data = b'' async for next_data in response.stream(): async for data in response.stream(): await send({ 'type': 'http.response.body', 'body': data, 'more_body': True }) await send({'type': 'http.response.body'}) if data: await send({ 'type': 'http.response.body', 'body': data, 'more_body': True }) data = next_data await send({'type': 'http.response.body', 'body': data})
async def stream_body(self, receive): async def initial_body(self, receive): """ Pull the first body message off the 'receive' channel. Allows us to determine if we should use a streaming request or not. """ message = await receive() body = message.get('body', b'') more_body = message.get('more_body', False) return (body, more_body)
async def stream_body(self, receive, initial_body): """ Async iterator returning bytes for the request body. """ yield initial_body while True: message = await receive() yield message.get('body', b'') if not message.get('more_body', False): break
app = GatewayServer('http://example.org')```
Run with...4 unmodified lines