falconry / falcon

The no-magic web data plane API and microservices framework for Python developers, with a focus on reliability, correctness, and performance at scale.
https://falcon.readthedocs.io/en/stable/
Apache License 2.0
9.51k stars 937 forks source link

Update request-id recipe to use `contextvars` instead of `threading.local()` #2260

Open vytas7 opened 1 month ago

vytas7 commented 1 month ago

contextvars is a newer module in the stdlib (3.7+) that is more advanced than theading.local() as it not only understand threads, but also asyncio coroutines, etc.

Update the Request ID Logging recipe to use contextvars.

Edit: also add tests for this recipe.

CaselIT commented 1 month ago

I don't think there is any need to use threadlocal or contextvar. just use req or resp context.

re-reading all that page it proposes several approaches. so yes, context var is better than threadlocal

vytas7 commented 1 month ago

Indeed, using global thread-locals is usually not a very bright idea and it leads to a spaghetti code base. But sometimes, particularly when working with a code base migrated from another framework that builds on this paradigm, or when very deep inside nested code, it might be a useful escape hatch.