Access context in Starlette
Project description
starlette context
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.
Resources:
- Source: https://github.com/tomwojcik/starlette-context
- Documentation: https://starlette-context.readthedocs.io/
- Changelog: https://starlette-context.readthedocs.io/en/latest/changelog.html
Installation
$ pip install starlette-context
Requirements
Python 3.7+
Dependencies
starlette
All other dependencies from requirements-dev.txt
are only needed to run tests or examples. Test/dev env is dockerized if you want to try them yourself.
Example
import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette_context import context, plugins
from starlette_context.middleware import RawContextMiddleware
middleware = [
Middleware(
RawContextMiddleware,
plugins=(
plugins.RequestIdPlugin(),
plugins.CorrelationIdPlugin()
)
)
]
app = Starlette(middleware=middleware)
@app.route("/")
async def index(request: Request):
return JSONResponse(context.data)
uvicorn.run(app, host="0.0.0.0")
In this example the response contains a json with
{
"X-Correlation-ID":"5ca2f0b43115461bad07ccae5976a990",
"X-Request-ID":"21f8d52208ec44948d152dc49a713fdd"
}
Context can be updated and accessed at anytime if it's created in the middleware.
Contribution
See the guide on read the docs.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for starlette_context-0.3.1-py37-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6704fa69e5d2c158060410bac0c860834367f49585e01498c4d5b4fa10eb8a89 |
|
MD5 | 0e628786c65f36ca304880d51e198d62 |
|
BLAKE2b-256 | d0bc02abd850180e32cd251b84ae9c282e9c8ea7bb0fbe27b3984076c4e2656b |