forked from falconry/falcon
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: request-id to use contextvars
Migrate the request-id handling from threading.local() to contextvars to improve compatibility with async coroutines and avoid issues with threading. This change ensures that request-id is properly tracked in asynchronous environments, providing more robust handling in both sync and async contexts. Previously, threading.local() was used, which does not handle coroutines effectively. By using contextvars, we ensure that the request-id remains consistent across async calls. Closes falconry#2260
- Loading branch information
1 parent
9debc9e
commit 2727fef
Showing
2 changed files
with
7 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,19 @@ | ||
# context.py | ||
|
||
import threading | ||
import contextvars | ||
|
||
|
||
class _Context: | ||
def __init__(self): | ||
self._thread_local = threading.local() | ||
self._request_id_var = contextvars.ContextVar('request_id', default=None) | ||
|
||
@property | ||
def request_id(self): | ||
return getattr(self._thread_local, 'request_id', None) | ||
return self._request_id_var.get() | ||
|
||
@request_id.setter | ||
def request_id(self, value): | ||
self._thread_local.request_id = value | ||
self._request_id_var.set(value) | ||
|
||
|
||
ctx = _Context() |