https://tortoise.github.io/examples.html
xpip install tortoise-orm fastapi pydantic
xxxxxxxxxx
.
├── main.py
└── models.py
xxxxxxxxxx
import typing
import pydantic
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise import Tortoise, BaseDBAsyncClient
from models import UserModel
app = FastAPI(title="Tortoise ORM FastAPI example")
register_tortoise(
app,
db_url="sqlite://:memory:",
modules={"models": ["models"]},
generate_schemas=True,
add_exception_handlers=True,
)
User: typing.Type[pydantic.BaseModel] = pydantic_model_creator(UserModel)
post("/user") .
async def add_user(user: User):
await UserModel(**user.dict()).save()
get("/users") .
async def get_all_user():
return [User.from_orm(user).dict() for user in await UserModel.filter()]
get("/users/raw", description="get all users using raw SQL") .
async def get_all_user_raw():
connection: BaseDBAsyncClient = Tortoise.get_connection("default")
users: typing.List[typing.Dict[str, typing.Any]] = await connection.execute_query_dict(
"SELECT * FROM user"
)
return users
if __name__ == '__main__':
import uvicorn
uvicorn.run("main:app", host='0.0.0.0', port=8080)
xxxxxxxxxx
from tortoise import fields
from tortoise.models import Model
class TimeMixin:
created_at = fields.DatetimeField(null=True, auto_now_add=True)
modified_at = fields.DatetimeField(null=True, auto_now=True)
class AbstractBaseModel(Model):
id = fields.IntField(pk=True)
class Meta:
abstract = True
class UserModel(TimeMixin, AbstractBaseModel):
# 新增字段
name = fields.CharField(200, null=False)
class Meta:
table = "user"