Skip to content

Instantly share code, notes, and snippets.

@vytas7
Last active May 29, 2022 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vytas7/7abce0dc841c7a6da45a0c3c0e72287c to your computer and use it in GitHub Desktop.
Save vytas7/7abce0dc841c7a6da45a0c3c0e72287c to your computer and use it in GitHub Desktop.
Falcon: inject params from async context managers
import logging
import aiohttp
import falcon
import falcon.asgi
# NOTE(vytas): Useful since ASGI otherwise has nothing like wsgierrors.
logging.basicConfig(
format='%(asctime)s [%(levelname)s] %(message)s', level=logging.INFO)
class ContextMiddleware:
def __init__(self, deps):
self._deps = deps
async def process_resource(self, req, resp, resource, params):
async def close_stuff():
for gen in gens:
async for _ in gen:
pass
gens = []
for name, dep in self._deps.items():
gens.append(gen := dep())
params[name] = await gen.asend(None)
resp.schedule(close_stuff)
class IPResource:
async def on_get(self, req, resp, session):
async with session.get('https://api.ipify.org') as ip_resp:
ip = await ip_resp.text()
resp.media = {'ip': ip}
async def aiohttp_session():
async with aiohttp.ClientSession() as session:
logging.info(f'instantiated {session}')
yield session
logging.info(f'tearing down {session}')
context_stack = ContextMiddleware({'session': aiohttp_session})
app = falcon.asgi.App(middleware=[context_stack])
app.add_route('/ip', IPResource())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment