Using Middlewares

Example

from jsondaora import jsondaora

from apidaora import (
    CorsMiddleware,
    Header,
    Middlewares,
    Request,
    Response,
    appdaora,
    route,
    text,
)


def pre_execution_middleware(request: Request) -> None:
    if request.body:
        request.body.name = request.body.name.replace('Me', 'You')


def post_execution_middleware(request: Request, response: Response) -> None:
    response.headers = [
        PostExecutionHeader(
            len(response.body.replace('Hello ', '').replace('!', ''))
        )
    ]


# The route middlewares takes precedence over general middlewares


@jsondaora
class PreExecutionBody:
    name: str


@route.post(
    '/hello-pre-execution/',
    middlewares=Middlewares(pre_execution=[pre_execution_middleware]),
)
async def pre_execution_middleware_controller(body: PreExecutionBody) -> str:
    return hello(body.name)


class PostExecutionHeader(Header, type=int, http_name='x-name-len'):
    ...


@route.get(
    '/hello-post-execution',
    middlewares=Middlewares(post_execution=[post_execution_middleware]),
)
async def post_execution_middleware_controller(name: str) -> Response:
    return text(body=hello(name))


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


app = appdaora(
    [
        pre_execution_middleware_controller,
        post_execution_middleware_controller,
    ],
    middlewares=Middlewares(
        post_execution=[CorsMiddleware(servers_all='my-server.domain')]
    ),
)

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 Pre Executition Middleware

curl -i localhost:8000/hello-pre-execution -X POST -d '{"name": "Me"}'
HTTP/1.1 200 OK
date: Thu, 1st January 1970 00:00:00 GMT
server: uvicorn
content-type: application/json
content-length: 12
access-control-allow-origin: my-server.domain
access-control-expose-headers: my-server.domain
access-control-allow-headers: my-server.domain
access-control-allow-methods: my-server.domain

"Hello You!"

Quering the Post Executition Middleware

curl -i 'localhost:8000/hello-post-execution?name=Me'
HTTP/1.1 200 OK
date: Thu, 1st January 1970 00:00:00 GMT
server: uvicorn
content-type: text/plain
content-length: 9
x-name-len: 2
access-control-allow-origin: my-server.domain
access-control-expose-headers: my-server.domain
access-control-allow-headers: my-server.domain
access-control-allow-methods: my-server.domain

Hello Me!