当前位置:   article > 正文

Tortoise-orm 使用 (四) FastAPI示例_tortoise-orm文档

tortoise-orm文档

官方文档研究 FastAPI Examples - Tortoise ORM v0.20.0 Documentation

网上好多教程都是手动封装Pydantic,不仅代码繁琐,后期改动也很麻烦,还是推荐使用ORM的模块,虽然会费事研究,但是后续提高开发效率。

对官方代码做了适当的改动,否则程序会报错

models.py

  1. from tortoise import fields, models
  2. from tortoise.contrib.pydantic import pydantic_model_creator
  3. class Users(models.Model):
  4. """
  5. The User model
  6. """
  7. id = fields.IntField(pk=True)
  8. #: This is a username
  9. username = fields.CharField(max_length=20, unique=True)
  10. name = fields.CharField(max_length=50, null=True)
  11. family_name = fields.CharField(max_length=50, null=True)
  12. category = fields.CharField(max_length=30, default="misc")
  13. password_hash = fields.CharField(max_length=128, null=True)
  14. created_at = fields.DatetimeField(auto_now_add=True)
  15. modified_at = fields.DatetimeField(auto_now=True)
  16. def full_name(self) -> str:
  17. """
  18. Returns the best name
  19. """
  20. if self.name or self.family_name:
  21. return f"{self.name or ''} {self.family_name or ''}".strip()
  22. return self.username
  23. # 这块要认真研究
  24. class PydanticMeta:
  25. computed = ["full_name"]
  26. exclude = ["password_hash"]
  27. User_Pydantic = pydantic_model_creator(Users, name="User")
  28. UserIn_Pydantic = pydantic_model_creator(Users, name="UserIn", exclude=("id", "created_at", "modified_at"))
  29. # 原始代码没有参数exclude=("id", "created_at", "modified_at")
  30. # 执行添加报错

main.py

  1. from typing import List
  2. from fastapi import FastAPI
  3. from models import User_Pydantic, UserIn_Pydantic, Users
  4. from pydantic import BaseModel
  5. from starlette.exceptions import HTTPException
  6. from tortoise.contrib.fastapi import register_tortoise
  7. app = FastAPI(title="Tortoise ORM FastAPI example")
  8. class Status(BaseModel):
  9. message: str
  10. @app.get("/users", response_model=List[User_Pydantic])
  11. async def get_users():
  12. return await User_Pydantic.from_queryset(Users.all())
  13. @app.post("/users", response_model=User_Pydantic)
  14. async def create_user(user: UserIn_Pydantic):
  15. user_obj = await Users.create(**user.model_dump(exclude_unset=True))
  16. return await User_Pydantic.from_tortoise_orm(user_obj)
  17. @app.get("/user/{user_id}", response_model=User_Pydantic)
  18. async def get_user(user_id: int):
  19. return await User_Pydantic.from_queryset_single(Users.get(id=user_id))
  20. @app.put("/user/{user_id}", response_model=User_Pydantic)
  21. async def update_user(user_id: int, user: UserIn_Pydantic):
  22. await Users.filter(id=user_id).update(
  23. **user.model_dump(exclude_unset=False, exclude='full_name'))
  24. return await User_Pydantic.from_queryset_single(Users.get(id=user_id))
  25. @app.delete("/user/{user_id}", response_model=Status)
  26. async def delete_user(user_id: int):
  27. deleted_count = await Users.filter(id=user_id).delete()
  28. if not deleted_count:
  29. raise HTTPException(status_code=404, detail=f"User {user_id} not found")
  30. return Status(message=f"Deleted user {user_id}")
  31. register_tortoise(
  32. app,
  33. db_url="sqlite://:memory:",
  34. modules={"models": ["models"]},
  35. generate_schemas=True,
  36. add_exception_handlers=True,
  37. )

项目启动后就可以任意测试了,后期再慢慢优化 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号