Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Created August 23, 2021 15:14
Show Gist options
  • Save kgriffs/71f2d77718f4634fa711f9c281fbfcfb to your computer and use it in GitHub Desktop.
Save kgriffs/71f2d77718f4634fa711f9c281fbfcfb to your computer and use it in GitHub Desktop.
Falcon - Stream httpx response example
# Courtesy of Vytautas Liuolia @vytas7
import falcon.asgi
import httpx
class Proxy(object):
UPSTREAM = 'https://falconframework.org'
def __init__(self):
self._client = httpx.AsyncClient()
async def handle(self, req, resp):
headers = dict(req.headers, Via='Falcon')
for name in ('host', 'connection', 'referer'):
headers.pop(name, None)
request = httpx.Request(
req.method, self.UPSTREAM + req.path, headers=headers)
response = await self._client.send(request, stream=True)
resp.stream = response.aiter_bytes()
resp.content_type = response.headers.get(
'Content-Type', falcon.MEDIA_HTML)
resp.status = response.status_code
# See also:
# https://www.python-httpx.org/async/#streaming-responses
resp.schedule(response.aclose)
app = falcon.asgi.App()
app.add_sink(Proxy().handle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment