是的,您可以register_tortoise
使用tortoise.contrib.sanic
它注册before_server_start
并after_server_stop
挂钩以在 Sanic 网络服务器中设置和拆除 Tortoise-ORM。查看来自 tortoise orm的这个 sanic 集成示例。
你可以像这样使用它,
from sanic import Sanic, response
from models import Users
from tortoise.contrib.sanic import register_tortoise
app = Sanic(__name__)
@app.route("/")
async def list_all(request):
users = await Users.all()
return response.json({"users": [str(user) for user in users]})
register_tortoise(
app, db_url="sqlite://:memory:", modules={"models": ["models"]}, generate_schemas=True
)
if __name__ == "__main__":
app.run(port=5000)
模型.py
from tortoise import Model, fields
class Users(Model):
id = fields.IntField(pk=True)
name = fields.CharField(50)
def __str__(self):
return f"User {self.id}: {self.name}"