LifespanΒΆ
You can define logic that runs before an application starts up, and run it only once, as well as logic that runs when the application shuts down, and run it only once.
This code covers the lifespan of the application, this can be useful to setup resources such as database connections, and gracefully shut them down.
Lifespan can be passed as a context manager to the application, with either side of the context manager being startup, and shutdown.
This is an example below, which will cleanly close the Redis connection:
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from dataclasses import asdict
from dataclasses import dataclass
from typing import Annotated
import redis.asyncio as redis
from asyncfast import AsyncFast
from asyncfast.bindings import KafkaKey
client = redis.Redis()
@asynccontextmanager
async def redis_lifespan(app: AsyncFast) -> AsyncGenerator[None, None]:
yield
await client.aclose()
app = AsyncFast(lifespan=redis_lifespan)
@dataclass
class Item:
sku_id: str
amount: int
@dataclass
class Order:
items: list[Item]
status: str
@app.channel("order")
async def handle_order(order_id: Annotated[str, KafkaKey()], order: Order) -> None:
await client.json().set(f"order:{order_id}", "$", asdict(order))
{
"asyncapi": "3.0.0",
"info": {
"title": "AsyncFast",
"version": "0.1.0"
},
"channels": {
"HandleOrder": {
"address": "order",
"messages": {
"HandleOrderMessage": {
"$ref": "#/components/messages/HandleOrderMessage"
}
}
}
},
"operations": {
"receiveHandleOrder": {
"action": "receive",
"channel": {
"$ref": "#/channels/HandleOrder"
}
}
},
"components": {
"messages": {
"HandleOrderMessage": {
"payload": {
"$ref": "#/components/schemas/Order"
},
"bindings": {
"kafka": {
"key": {
"type": "string"
}
}
}
}
},
"schemas": {
"Item": {
"properties": {
"sku_id": {
"title": "Sku Id",
"type": "string"
},
"amount": {
"title": "Amount",
"type": "integer"
}
},
"required": [
"sku_id",
"amount"
],
"title": "Item",
"type": "object"
},
"Order": {
"properties": {
"items": {
"items": {
"$ref": "#/components/schemas/Item"
},
"title": "Items",
"type": "array"
},
"status": {
"title": "Status",
"type": "string"
}
},
"required": [
"items",
"status"
],
"title": "Order",
"type": "object"
}
}
}
}