Hook context managers
Context managers are an expressive way to do something with cleanup. Many libraries provide functionality via context managers (for example tracing with some_lib.start_span(...) as span: ...), and users probably want to (or at least should want to) write things using context managers as much as possible.
Currently, hooks only support disconnected before/after events. The docs suggest using request.context to pass information between them, which does work, but look at the following:
@contextmanager
def do_something(req, resp, resource, params) -> None:
yield
def do_before_wrapper(req, resp, resource, params): -> None:
req.context._do_something_cm = do_something(req, resp, resource, params)
req.context._do_something_cm.__enter__()
def do_after_wrapper(req, resp, resource, params): -> None:
cm = req.context._do_something_cm
cm.__aexit__(None, None, None)
@falcon.before(do_before_wrapper)
@falcon.after(do_after_wrapper)And you still need to figure out error handling (maybe adding an error handler that checks for req.context._do_something_cm? Maybe this can be cleaned up using an ExitStack? Still messy).
Please let me know if there is a better way to do this, but as far as I can tell there is not.
I would propose that you implement the following:
@contextmanager
def do_something(req, resp, resource, params) -> None:
yield
@falcon.hook(do_something)Which takes care of all of the above boilerplate, does error handling (by letting the cm handle the error), etc.
Source: falconry/falcon