Skip to content

Instantly share code, notes, and snippets.

@FND
Last active August 30, 2024 04:42
Show Gist options
  • Select an option

  • Save FND/b4ac63e471c92cf039c2 to your computer and use it in GitHub Desktop.

Select an option

Save FND/b4ac63e471c92cf039c2 to your computer and use it in GitHub Desktop.
Falcon WSGI application with asyncio

Getting Started

$ pip install falcon
$ python3 app.py

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):
res = Future()
responses = []
def conclude(response):
responses.append(response)
if len(responses) == len(uris):
res.set_result(responses)
for uri in uris:
task = Task(fetch(uri))
task.add_done_callback(lambda task: conclude(task.result()))
return res
@async
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" % (lag, uri)
@async
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):
service_requests = aggregator.retrieve("http://example.org/foo",
"http://example.org/bar", "http://example.org/baz")
loop = asyncio.get_event_loop()
loop.run_until_complete(service_requests)
results = service_requests.result()
res.body = "%s\n" % "\n".join(results)
app = falcon.API()
app.add_route("/", Frontpage())
if __name__ == "__main__":
server = simple_server.make_server("localhost", 8000, app)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment