Oslo Context Library
The `oslo.context` library is a core OpenStack component providing helpers to manage and maintain useful information about a request context. This context is typically populated within a WSGI pipeline and utilized by various modules, such as `oslo.log`, for consistent data access throughout a request's lifecycle. The library is currently at version 6.3.0 and follows the OpenStack release cadence.
Warnings
- breaking The `tenant` argument of `RequestContext` has been removed in version 6.x.x (specifically, from the Zed series). It was deprecated for a long time.
- deprecated Passing positional arguments to `RequestContext.__init__` has been deprecated since version 2.7.0. While it might still work, it can lead to unexpected behavior in future versions.
- gotcha The `get_logging_values` function (intended for logging) no longer outputs the `auth_token` directly but replaces it with `***` to prevent sensitive data leakage. If you rely on the `auth_token` for other purposes, retrieve it directly from the `RequestContext` object.
- gotcha The request context is stored in thread-local storage. If your application uses worker pools or asynchronous patterns that change the execution thread, the context might not be propagated automatically, leading to `None` being returned by `context.get_current()`.
Install
-
pip install oslo.context
Imports
- RequestContext
from oslo_context import context
- get_current
from oslo_context import context
Quickstart
from oslo_context import context
# Create a basic RequestContext
req_context = context.RequestContext(
auth_token='fake_auth_token',
user_id='fake_user_id',
project_id='fake_project_id',
is_admin=False
)
# Store the context for the current thread
req_context.make_current()
# Later in the application, retrieve the context
current_context = context.get_current()
if current_context:
print(f"Current User ID: {current_context.user_id}")
print(f"Is Admin: {current_context.is_admin}")
# Example of creating an admin context
admin_context = context.get_admin_context(show_deleted=True)
admin_context.make_current()
print(f"Admin Context User ID: {context.get_current().user_id}")
print(f"Admin Context is Admin: {context.get_current().is_admin}")
# Clean up the context (important in testing or if not in a WSGI app)
context.clear_current()