meadsteve/lagom

Add request scoped context manager based resources for the fastapi integration

meadsteve opened this issue · 2 comments

Similar to: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/

See conversation on this issue: #179 (comment)

Stretch goal: make this generic enough to use for all lagom usages.

@rowanbarrie this was slightly easier to hook into than I thought.
I'm currently experimenting with an interface like this:

# Define a contextmanager for the dependency. The __exit__ (finally in this case) will happen after the request has loaded.
@dependency_definition(container)
@contextmanager
def _load_then_clean() -> Iterator[SomeThing]:
    try:
        yield SomeThing()
    finally:
        SomeThing.do_some_cleanup()

# This type then needs to be registered as a managed singleton:
deps = FastApiIntegration(
    container, request_context_singletons=[SomeThing]
)

Based around defining a ContextManager for the thing required and then the framework integration handles calling exit at the end of the request handling.

released in lagom 1.7.0