Skip to content

Instantly share code, notes, and snippets.

Last active May 4, 2021
What would you like to do?
Falcon WSGI application with asyncio

Getting Started

$ pip install falcon
$ python3

alternatively with Gunicorn (for HTTP/1.1):

$ pip install gunicorn
$ gunicorn app:app
from asyncio import Future, Task, coroutine as async, sleep
from random import randint
def retrieve(*uris, callback=None):
res = Future()
responses = []
def conclude(response):
if callback:
if len(responses) == len(uris):
for uri in uris:
task = Task(fetch(uri))
task.add_done_callback(lambda task: conclude(task.result()))
return res
def fetch(uri):
print("retrieving %s..." % uri)
lag = yield from _http()
lag = lag * 1000
print("downloaded %s in %d ms" % (uri, lag))
return "[%d ms] %s\n" % (lag, uri)
def _http():
lag = randint(2, 9) * 0.1
yield from sleep(lag)
return lag
import asyncio
import falcon
import aggregator
from wsgiref import simple_server
class Frontpage:
def on_get(self, req, res):
uris = ("", "",
"") = ResponseStream(
service_requests = aggregator.retrieve(*uris, # XXX: race condition? `write` vs. `__iter__`
loop = asyncio.get_event_loop()
class ResponseStream:
def __init__(self, output_stream):
self.output_stream = output_stream
self.chunks = []
def write(self, chunk):
def __iter__(self, *args, **kwargs):
while True:
chunk = self.chunks.pop(0) # XXX: inefficient?
yield chunk.encode("utf8")
except IndexError:
app = falcon.API()
app.add_route("/", Frontpage())
if __name__ == "__main__":
server = simple_server.make_server("localhost", 8000, app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment