Skip to content

Instantly share code, notes, and snippets.

@vytas7
Created August 17, 2021 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vytas7/271d3fc4c05fb9ba20476dde405af0ec to your computer and use it in GitHub Desktop.
Save vytas7/271d3fc4c05fb9ba20476dde405af0ec to your computer and use it in GitHub Desktop.
Proxying a website with Falcon ASGI + httpx
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