experimental/cpu/: starlette-context-0.3.6 metadata and description

Homepage Simple index

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.

author Tom Wojcik
author_email starlette-context-pkg@tomwojcik.com
classifiers
  • Development Status :: 3 - Alpha
  • Intended Audience :: Developers
  • Intended Audience :: Information Technology
  • Intended Audience :: System Administrators
  • License :: OSI Approved :: MIT License
  • Programming Language :: Python :: 3
  • Programming Language :: Python :: 3.8
  • Programming Language :: Python :: 3.9
  • Programming Language :: Python :: 3.10
  • Programming Language :: Python :: 3.11
  • Programming Language :: Python :: 3.12
  • Topic :: Internet
description_content_type text/x-rst
keywords middleware,starlette,fastapi
license MIT
project_urls
  • Documentation, https://starlette-context.readthedocs.io/
  • Repository, https://github.com/tomwojcik/starlette-context
requires_dist
  • starlette
requires_python >=3.8,<4.0
File Tox results History
starlette_context-0.3.6-py3-none-any.whl
Size
12 KB
Type
Python Wheel
Python
3

Test Suite Python PyPI version codecov Docs Downloads

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:

Installation

$ pip install starlette-context

Requirements

Should be working fine on 3.7+. Official support starts at 3.8.

Dependencies

  • starlette

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.

Sponsorship

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

Contribution

See the guide on read the docs.