1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
import logging
from typing import Dict
from litestar import Litestar, Response, get
from litestar.background_tasks import BackgroundTask, BackgroundTasks
logger = logging.getLogger(__name__)
greeted = set()
async def logging_task(name: str) -> None:
logger.info("%s was greeted", name)
async def saving_task(name: str) -> None:
greeted.add(name)
@get("/", sync_to_thread=False)
def greeter(name: str) -> Response[Dict[str, str]]:
return Response(
{"hello": name},
background=BackgroundTasks(
[
BackgroundTask(logging_task, name),
BackgroundTask(saving_task, name),
]
),
)
app = Litestar(route_handlers=[greeter])
|