Using Extra Arguments Middlewares

Example

from typing import Any

from apidaora import Middlewares, Request, Response, appdaora, route, text


def request_extra_args(request: Request) -> None:
    request.ctx['extra'] = 'You'


def response_extra_args(request: Request, response: Response) -> None:
    if request.ctx and response.ctx:
        response.body = response.body.replace(
            'You', f"{request.ctx['extra']} and {response.ctx['name']}"
        )


@route.get(
    '/middlewares-ctx',
    middlewares=Middlewares(
        pre_execution=request_extra_args, post_execution=response_extra_args,
    ),
)
async def extra_args_controller(name: str, **kwargs: Any) -> Response:
    return text(hello(kwargs['extra']), name=name)


def hello(name: str) -> str:
    return f'Hello {name}!'


app = appdaora(extra_args_controller)

Running

Running the server:

uvicorn myapp:app
INFO: Started server process [16220]
INFO: Waiting for application startup.
INFO: ASGI 'lifespan' protocol appears unsupported.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Quering the server

curl -i localhost:8000/middlewares-ctx?name=Me
HTTP/1.1 200 OK
date: Thu, 1st January 1970 00:00:00 GMT
server: uvicorn
content-type: text/plain
content-length: 17

Hello You and Me!