Using Background Tasks Middleware

Example

from apidaora import (
    BackgroundTaskMiddleware,
    Middlewares,
    Response,
    appdaora,
    route,
    text,
)


class HelloCounter:
    counter = 1

    @classmethod
    async def count(cls) -> None:
        cls.counter += 1


@route.get('/background-tasks')
async def background_tasks_controller(name: str) -> Response:
    return text(
        f'Hello {name}!\n{name} are the #{HelloCounter.counter}!',
        background_tasks=HelloCounter.count,
    )


app = appdaora(
    background_tasks_controller,
    middlewares=Middlewares(post_execution=BackgroundTaskMiddleware()),
)

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/background-tasks?name=Me
echo && echo
curl -i localhost:8000/background-tasks?name=You
HTTP/1.1 200 OK
date: Thu, 1st January 1970 00:00:00 GMT
server: uvicorn
content-type: text/plain
content-length: 24

Hello Me!
Me are the #1!

HTTP/1.1 200 OK
date: Thu, 1st January 1970 00:00:00 GMT
server: uvicorn
content-type: text/plain
content-length: 26

Hello You!
You are the #2!