Skip to content

Instantly share code, notes, and snippets.

@vytas7
Created April 25, 2019 17:13
Show Gist options
  • Save vytas7/cf49d061894bbff66e63b1dd9500e2cb to your computer and use it in GitHub Desktop.
Save vytas7/cf49d061894bbff66e63b1dd9500e2cb to your computer and use it in GitHub Desktop.
Falcon proxying example using a sink (tested with Falcon 2.0.0rc4 and CPython 3.7)
import io
import falcon
import requests
class Proxy(object):
"""Try, for instance ``/examples/forms1.html``."""
UPSTREAM = 'https://www.simplehtmlguide.com'
def __init__(self):
self.session = requests.Session()
def handle(self, req, resp):
headers = dict(req.headers, Via='Falcon')
for name in ('HOST', 'CONNECTION', 'REFERER'):
headers.pop(name, None)
request = requests.Request(req.method, self.UPSTREAM + req.path,
data=req.bounded_stream.read(),
headers=headers)
prepared = request.prepare()
from_upstream = self.session.send(prepared, stream=True)
resp.content_type = from_upstream.headers.get('Content-Type',
falcon.MEDIA_HTML)
resp.status = falcon.get_http_status(from_upstream.status_code)
resp.stream = from_upstream.iter_content(io.DEFAULT_BUFFER_SIZE)
api = falcon.API()
api.add_sink(Proxy().handle)
@vytas7
Copy link
Author

vytas7 commented Apr 25, 2019

Exercise for the reader: stream request directly from req.bounded_stream, do not buffer it in memory with .read().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment