From 58256a2a713e335ca3cc010169fd92d118a55270 Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Wed, 14 Aug 2024 13:08:43 +0100 Subject: [PATCH] Add cleanup_ctx example for sharing resources across subapps (#8694) (cherry picked from commit d83804db6a77221c996dfa3710ba6cf6b58d08b9) --- docs/faq.rst | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/faq.rst b/docs/faq.rst index 2de70f97d7b..30803da3576 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -279,7 +279,18 @@ A subapplication is an isolated unit by design. If you need to share a database object, do it explicitly:: subapp[db_key] = mainapp[db_key] - mainapp.add_subapp('/prefix', subapp) + mainapp.add_subapp("/prefix", subapp) + +This can also be done from a :ref:`cleanup context`:: + + async def db_context(app: web.Application) -> AsyncIterator[None]: + async with create_db() as db: + mainapp[db_key] = mainapp[subapp_key][db_key] = db + yield + + mainapp[subapp_key] = subapp + mainapp.add_subapp("/prefix", subapp) + mainapp.cleanup_ctx.append(db_context) How do I perform operations in a request handler after sending the response?