Created
April 25, 2019 17:13
-
-
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)
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exercise for the reader: stream request directly from
req.bounded_stream
, do not buffer it in memory with.read()
.