tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.68k stars 392 forks source link

Robyn registe tortoise, but unable to close the robyn program properl #1744

Open JiaLiangChen99 opened 3 weeks ago

JiaLiangChen99 commented 3 weeks ago

I tried using tortoise_orm with the Robyn. I referenced the registration method from Sanic. When I didn't remove the '@app.shutdown_handler' function, I couldn't properly close the Robyn program using Ctrl+C. After I removed the '@app.shutdown_handler' function, it closed normally

from tortoise import Tortoise, connections
from tortoise.log import logger

from models import Users

from typing import Optional, Dict, Iterable, Union
from types import ModuleType, FunctionType

def register_tortoise(
    app: Robyn,
    config: Optional[dict] = None,
    config_file: Optional[str] = None,
    db_url: Optional[str] = None,
    modules: Optional[Dict[str, Iterable[Union[str, ModuleType]]]] = None,
    generate_schemas: bool = False,
    startu_up_function: FunctionType = None
):
    async def tortoise_init() -> None:
        await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules)
        logger.info(
            "Tortoise-ORM started, %s, %s", connections._get_storage(), Tortoise.apps
        )  # pylint: disable=W0212

    @app.startup_handler
    async def init_orm():  # pylint: disable=W0612
        if startu_up_function:
            await startu_up_function()
        await tortoise_init()
        if generate_schemas:
            logger.info("Tortoise-ORM generating schema")
            await Tortoise.generate_schemas()

    @app.shutdown_handler
    async def shutdown_orm():  # pylint: disable=W0612
        await Tortoise.close_connections()
        logger.info("Tortoise-ORM connections closed")

app = Robyn(__file__)

@app.get("/")
async def h(request):
    users = await Users.all()
    return jsonify({"users": [str(user) for user in users]})

@app.get("/user")
async def add_user(request):
    user = await Users.create(name="New User")
    return jsonify({"user": str(user)})

async def my_startup_function():
    print("Starting up my app")

register_tortoise(
    app, db_url="sqlite://:memory:", modules={"models": ["models"]}, generate_schemas=True,
    other_startu_up_function=my_startup_function
)

app.start(port=8080)

Although we can forcefully close the program in other ways, I would like to understand what is happening here.

waketzheng commented 3 weeks ago

Can not reproduce in Windows+Python3.11

With @app.shutdown_handler, the Robyn program was able to close by click Ctrl+C twice, so does without shutdown function.