From 60c225e1540c92972550f725575a91ccf7a20463 Mon Sep 17 00:00:00 2001 From: Pirulax Date: Sat, 17 Aug 2024 09:59:28 +0200 Subject: [PATCH] Fix deadlock for Sanic apps with `generate_schema=True` and > 1 workers (#1696) * Fix deadlock for Sanic apps with `generate_schema=True` * Add changelog entry * Fix linter errors * Run `make style` * Remove unused import --- CHANGELOG.rst | 1 + examples/fastapi/main.py | 2 +- tortoise/contrib/sanic/__init__.py | 18 ++++++++++++++---- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 9503962e1..d6f6a2d4c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -14,6 +14,7 @@ Changelog Fixed ^^^^^ - Fix bug in `pydantic_model_creator` when a foreign key is not included in `include` param. (#1430) +- Fix bug in `contrib.sanic.register_tortoise` causing a deadlock when using asyncpg and > 1 workers (#1696) 0.21.5 <../0.21.5>`_ - 2024-07-18 ------ diff --git a/examples/fastapi/main.py b/examples/fastapi/main.py index 8c0febbbb..4b686e731 100644 --- a/examples/fastapi/main.py +++ b/examples/fastapi/main.py @@ -4,9 +4,9 @@ from typing import AsyncGenerator from fastapi import FastAPI +from routers import router as users_router from examples.fastapi.config import register_orm -from routers import router as users_router from tortoise import Tortoise, generate_config from tortoise.contrib.fastapi import RegisterTortoise diff --git a/tortoise/contrib/sanic/__init__.py b/tortoise/contrib/sanic/__init__.py index b1ffb66a6..310603d22 100644 --- a/tortoise/contrib/sanic/__init__.py +++ b/tortoise/contrib/sanic/__init__.py @@ -77,14 +77,24 @@ def register_tortoise( For any configuration error """ - @app.listener("before_server_start") - async def init_orm(app, loop): # pylint: disable=W0612 + 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) - if generate_schemas: + logger.info( + "Tortoise-ORM started, %s, %s", connections._get_storage(), Tortoise.apps + ) # pylint: disable=W0212 + + if generate_schemas: + + @app.listener("main_process_start") + async def init_orm_main(app, loop): # pylint: disable=W0612 + await tortoise_init() logger.info("Tortoise-ORM generating schema") await Tortoise.generate_schemas() + @app.listener("before_server_start") + async def init_orm(app, loop): # pylint: disable=W0612 + await tortoise_init() + @app.listener("after_server_stop") async def close_orm(app, loop): # pylint: disable=W0612 await connections.close_all()