Created
August 17, 2021 16:32
-
-
Save vytas7/271d3fc4c05fb9ba20476dde405af0ec to your computer and use it in GitHub Desktop.
Proxying a website with Falcon ASGI + httpx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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