当前位置:   article > 正文

FastAPI + tortoise-orm基础使用

tortoise-orm

更改sqlite为mysql

  1. from tortoise import Tortoise
  2. import asyncio
  3. async def init():
  4. user = 'root'
  5. password = '123456'
  6. db_name = 'test'
  7. await Tortoise.init(
  8. #指定mysql信息
  9. db_url=f'mysql://{user}:{password}@127.0.0.1:3306/{db_name}',
  10. #指定models
  11. modules={'models': ['sanic_bp.models']}
  12. )
  13. #按照模型生成表
  14. # await Tortoise.generate_schemas()
  15. asyncio.run(init())

在sanic中使用:

  1. from sanic import Sanic
  2. from tortoise import Tortoise
  3. app = Sanic(__name__)
  4. @app.listener('after_server_start')
  5. async def notify_server_started(app, loop):
  6. print('sanic sanic服务启动后建立mysql连接')
  7. #实例化mysql连接
  8. await Tortoise.init(
  9. db_url='mysql://root:123456@127.0.0.1:3306/test?maxsize=50&minsize=3',
  10. modules={'models': ['sanic_bp.models']}
  11. )

基础使用

  1. from tortoise.contrib.sanic import register_tortoise
  2. register_tortoise(
  3. app, db_url="sqlite://:memory:", modules={"models": ["models"]}, generate_schemas=True
  4. )

sanic 和 fastapi中使用
tortoise-orm 连接多个库

  1. async def run():
  2. await Tortoise.init(
  3. {
  4. #这里面指定两个不同的数据库,虽然它填写的都是一样的
  5. "connections": {
  6. "first": {
  7. "engine": "tortoise.backends.sqlite",
  8. "credentials": {"file_path": "example.sqlite3"},
  9. },
  10. "second": {
  11. "engine": "tortoise.backends.sqlite",
  12. "credentials": {"file_path": "example1.sqlite3"},
  13. },
  14. },
  15. #可以指定多个不同的models, 嗯,它指定的也是一样的
  16. "apps": {
  17. "tournaments": {"models": ["__main__"], "default_connection": "first"},
  18. "events": {"models": ["__main__"], "default_connection": "second"},
  19. },
  20. }
  21. )
  22. #await Tortoise.generate_schemas()
  23. #选取数据库
  24. client = Tortoise.get_connection("first")
  25. #选取 models
  26. second_client = Tortoise.get_connection("second")
  27. #然后这下面就可以进行orm操作了

增删改查

  1. from typing import List
  2. from fastapi import APIRouter, HTTPException
  3. from tortoise.contrib.fastapi import HTTPNotFoundError
  4. from schemas.MaintainedData import MaintainedData_Pydantic, MaintainedDataIn_Pydantic
  5. from models.MaintainedData import MaintainedData
  6. from schemas.basic import Response404, Response200
  7. data = APIRouter(tags=['数据模块'])
  8. @data.get("/", summary="数据列表", response_model=List[MaintainedData_Pydantic])
  9. async def data_list(order:str,limit: int = 10, page: int = 1):
  10. # limit 是显示的条数 ,page是页数
  11. skip = (page - 1) * limit
  12. # select * from movie limit offset,limit
  13. # select * from movie limit 0,10
  14. return await MaintainedData_Pydantic.from_queryset(MaintainedData.all().offset(skip).limit(limit))
  15. @data.post("/data", summary="新增数据", )
  16. async def add_data(md_data: MaintainedData_Pydantic):
  17. movie_obj = await MaintainedData.create(**md_data.dict(exclude_unset=True))
  18. # movie_obj = await Movie.create(name="",year="",xx="")
  19. return await MaintainedData_Pydantic.from_tortoise_orm(movie_obj)
  20. @data.put("/data/{data_id}", summary="编辑数据", responses={404: {"model": HTTPNotFoundError}})
  21. async def update_data(site_id: str, md_data: MaintainedDataIn_Pydantic):
  22. updated_count = await MaintainedData.filter(site_id=site_id).update(**md_data.dict(exclude_unset=True))
  23. print(updated_count)
  24. if not updated_count:
  25. return Response404(msg=f"data {site_id} not found")
  26. return Response200(data=await MaintainedData_Pydantic.from_queryset_single(MaintainedData.get(site_id=site_id)))
  27. @data.get("/data/{data_id}", summary="查找数据", response_model=MaintainedData_Pydantic,
  28. responses={404: {"model": HTTPNotFoundError}})
  29. async def get_user(site_id: str):
  30. return await MaintainedData_Pydantic.from_queryset_single(MaintainedData.get(site_id=site_id))
  31. @data.delete("/data/{data_id}", summary="删除数据", responses={404: {"model": HTTPNotFoundError}})
  32. async def del_movie(site_id: str):
  33. deleted_count = await MaintainedData.filter(site_id=site_id).delete()
  34. if not deleted_count:
  35. raise HTTPException(status_code=404, detail=f"data {site_id} not found")
  36. return HTTPException(status_code=200, detail=f"Deleted Movie {site_id}")

models.py

  1. from datetime import datetime
  2. from typing import Optional, Iterable
  3. from tortoise import fields, models, BaseDBAsyncClient
  4. class MaintainedData(models.Model):
  5. """
  6. The User model
  7. """
  8. id = fields.SmallIntField(pk=True, index=True, description="ID", )
  9. site_id = fields.CharField(max_length=20, unique=True, description="网站ID")
  10. site_name = fields.CharField(max_length=128, null=False, description="网站名称")
  11. site_type = fields.CharField(max_length=16, null=False, description="网站类型")
  12. description = fields.CharField(max_length=255, default="",description="网站备注", )
  13. site_path_name = fields.CharField(max_length=128, null=True, description="目录名称")
  14. site_path_url = fields.CharField(max_length=128, null=True, description="目录链接")
  15. status = fields.CharField(max_length=128, null=True, description="脚本状态")
  16. run_computer = fields.CharField(max_length=255, null=True, description="运行电脑")
  17. run_directory = fields.CharField(max_length=255, null=True, description="运行目录")
  18. crawling_time :Optional[datetime]= fields.DatetimeField(auto_add=True, description="运行时间")
  19. err_message = fields.CharField(max_length=255, null=True, description="错误信息")

order by

db_Secc = MaintainedData.all().order_by("crawling_time")

Eum 枚举

  1. class order_byEnum(str, Enum):
  2. pear = ""
  3. banana = '-'
  4. @data.get("/", summary="数据列表", response_model=List[MaintainedData_Pydantic])
  5. async def data_list(
  6. order_by: order_byEnum = "",
  7. limit: int = 10,
  8. page: int = 1):
  9. # limit 是显示的条数 ,page是页数
  10. skip = (page - 1) * limit
  11. return await MaintainedData_Pydantic.from_queryset(MaintainedData.all().offset(
  12. skip).limit(
  13. limit).order_by(
  14. f"{order_by}crawling_time"))
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/137019
推荐阅读
相关标签
  

闽ICP备14008679号