0
await room.save()    

显示以下错误 AttributeError: 'NoneType' object has no attribute '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"}
4

1 回答 1

0

@app.on_event("startup")which 是一个异步函数中,您正在调用run_async(init())which 根据文档自行清理,并且仅适用于小型脚本。这意味着您正在创建然后破坏数据库连接。因此连接是一个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_asyncio只是将其排除在外会使事情变得更好。

于 2020-05-26T08:31:33.307 回答