2024-11-29 09:01:19 +00:00
|
|
|
from contextlib import asynccontextmanager
|
2024-11-29 09:09:32 +00:00
|
|
|
from random import randint
|
2024-11-29 09:01:19 +00:00
|
|
|
from typing import AsyncGenerator
|
2024-11-29 08:09:42 +00:00
|
|
|
|
2024-11-29 09:01:19 +00:00
|
|
|
from fastapi import FastAPI
|
|
|
|
|
from tortoise import Tortoise, generate_config
|
|
|
|
|
from tortoise.contrib.fastapi import RegisterTortoise
|
2024-11-29 08:09:42 +00:00
|
|
|
|
2024-11-29 09:01:19 +00:00
|
|
|
from models import RawData
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan_test(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
|
|
|
config = generate_config(
|
|
|
|
|
"sqlite://:memory:",
|
|
|
|
|
app_modules={"models": ["models"]},
|
|
|
|
|
testing=True,
|
|
|
|
|
connection_label="models",
|
|
|
|
|
)
|
|
|
|
|
async with RegisterTortoise(
|
|
|
|
|
app=app,
|
|
|
|
|
config=config,
|
|
|
|
|
generate_schemas=True,
|
|
|
|
|
add_exception_handlers=True,
|
|
|
|
|
_create_db=True,
|
|
|
|
|
):
|
|
|
|
|
# db connected
|
|
|
|
|
yield
|
|
|
|
|
# app teardown
|
|
|
|
|
# db connections closed
|
|
|
|
|
await Tortoise._drop_databases()
|
2024-11-29 08:09:42 +00:00
|
|
|
|
|
|
|
|
|
2024-11-29 09:01:19 +00:00
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
2024-12-28 13:01:29 +00:00
|
|
|
config = generate_config(
|
|
|
|
|
"sqlite://db.sqlite3",
|
|
|
|
|
app_modules={"models": ["models"]},
|
|
|
|
|
connection_label="models",
|
|
|
|
|
)
|
|
|
|
|
async with RegisterTortoise(
|
|
|
|
|
app=app,
|
|
|
|
|
config=config
|
|
|
|
|
):
|
|
|
|
|
# db connected
|
|
|
|
|
yield
|
|
|
|
|
# app teardown
|
|
|
|
|
# db connections closed
|
|
|
|
|
await Tortoise.close_connections()
|
2024-11-29 09:01:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/")
|
|
|
|
|
async def root():
|
|
|
|
|
cnt = await RawData.all().count()
|
|
|
|
|
# 生成一个范围内的随机整数,随机返回一篇文章
|
|
|
|
|
r = randint(1, cnt)
|
|
|
|
|
record = await RawData.get(id=r)
|
|
|
|
|
return {"title": record.title, "content": record.content}
|