python-3.7sanictortoise-orm

How to init db for tortoise-orm in sanic app?


Is there a way to register databases in tortoise-orm from my Sanic app other than calling Tortoise.init?

from tortoise import Tortoise

await Tortoise.init(
        db_url='sqlite://db.sqlite3',
        modules={'models': ['app.models']}
    )
    # Generate the schema
    await Tortoise.generate_schemas()

Solution

  • Yes, you can use register_tortoise available from tortoise.contrib.sanic

    It registers before_server_start and after_server_stop hooks to set-up and tear-down Tortoise-ORM inside a Sanic webserver. Check out this sanic integration example from tortoise orm.

    you can use it like,

    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)
    

    models.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}"