【问题标题】:Not able to insert the record in to SQLITE3 DB with tortoise ORM in fastAPI APP无法在fastAPI APP中使用乌龟ORM将记录插入SQLITE3 DB
【发布时间】:2020-09-11 09:18:57
【问题描述】:
await room.save()    

显示以下错误 AttributeError: 'NoneType' 对象没有属性 'execute_insert'

启动代码

async def init():
    # Here we create a SQLite DB using file "db.sqlite3"
    #  also specify the app name of "models"
    #  which contain models from "app.models"
    await Tortoise.init(
        db_url='sqlite://db1',
        modules={'app1': ['app1.models']}
    )
    # Generate the schema
    #await Tortoise.generate_schemas()

@app.on_event("startup")
async def startup_event():
  nest_asyncio.apply()
  run_async(init())

创建了一个数据库结构,这就是为什么注释等待 Tortoise.generate_schemas()。 在下面找到我的发布方法代码

@app.post("/room/{room_id}")
async def post(request: Request, room_id):
      room = models.Room(id=room_id)
      await room.save()
      return {"message":"created successfully"}

【问题讨论】:

    标签: fastapi tortoise-orm


    【解决方案1】:

    @app.on_event("startup") 这是一个异步函数中,您正在调用 run_async(init()) 根据 documentation 自行清理,并且仅适用于小型脚本。 这意味着您正在创建然后破坏数据库连接。因此连接是None

    相反,只需等待它,然后像这样处理关闭事件:

    @app.on_event("startup")
    async def startup_event():
      nest_asyncio.apply()
      await init()
    
    @app.on_event("shutdown")
    async def close_orm():
        await Tortoise.close_connections()
    

    编辑:显然nest_asynciojust leaving it out makes things work better. 也存在问题

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 1970-01-01
      • 2021-07-12
      • 2020-05-11
      • 2021-01-15
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      相关资源
      最近更新 更多