WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

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.

License

Notifications You must be signed in to change notification settings

minddistrict/starlette-context

 
 

Repository files navigation

starlette-context

Test Suite Python PyPI version codecov Docs Downloads

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

Installation

# Python 3.9+
pip install starlette-context

Dependencies

  • starlette>=0.27.0

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.routing import Route

from starlette_context import context, plugins
from starlette_context.middleware import ContextMiddleware

async def index(request: Request):
    # Access and store data in context
    context["custom_value"] = "example"
    return JSONResponse(context.data)

# Define routes
routes = [
    Route("/", endpoint=index)
]

# Configure middleware
middleware = [
    Middleware(
        ContextMiddleware,
        plugins=(
            plugins.RequestIdPlugin(),
            plugins.CorrelationIdPlugin()
        )
    )
]

# Create application with routes and middleware
app = Starlette(
    routes=routes,
    middleware=middleware
)

if __name__ == "__main__":
    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",
  "custom_value": "example"
}

Context can be updated and accessed at anytime if it's created in the middleware.

Sponsorship

A huge thank you to Adverity for sponsoring the development of this OSS library.

Contribution

See the contributing guide.

About

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

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 96.4%
  • Shell 2.2%
  • Makefile 1.4%