Skip to content

Instantly share code, notes, and snippets.

@vytas7

vytas7/proxy.py

Created Apr 25, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@vytas7 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