From dab8d1b4a9991e71f4d885b1037e96bc956bffb3 Mon Sep 17 00:00:00 2001 From: -LAN- Date: Wed, 18 Dec 2024 00:29:27 +0800 Subject: [PATCH 1/2] feat(app_factory): speed up flask db migration Signed-off-by: -LAN- --- api/app.py | 20 +++++++++++++++----- api/app_factory.py | 11 +++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/api/app.py b/api/app.py index 996e2e890fdd10..ddae1e57b851d6 100644 --- a/api/app.py +++ b/api/app.py @@ -1,13 +1,23 @@ -from app_factory import create_app -from libs import threadings_utils, version_utils +import sys + +from libs import version_utils # preparation before creating app version_utils.check_supported_python_version() -threadings_utils.apply_gevent_threading_patch() # create app -app = create_app() -celery = app.extensions["celery"] +if "db" in sys.argv: + from app_factory import create_migrations_app + + app = create_migrations_app() +else: + from app_factory import create_app + from libs import threadings_utils + + threadings_utils.apply_gevent_threading_patch() + + app = create_app() + celery = app.extensions["celery"] if __name__ == "__main__": app.run(host="0.0.0.0", port=5001) diff --git a/api/app_factory.py b/api/app_factory.py index 7dc08c4d93960a..f6c6369e8fcda0 100644 --- a/api/app_factory.py +++ b/api/app_factory.py @@ -98,3 +98,14 @@ def initialize_extensions(app: DifyApp): end_time = time.perf_counter() if dify_config.DEBUG: logging.info(f"Loaded {short_name} ({round((end_time - start_time) * 1000, 2)} ms)") + + +def create_migrations_app(): + app = create_flask_app_with_configs() + from extensions import ext_database, ext_migrate + + # Initialize only required extensions + ext_database.init_app(app) + ext_migrate.init_app(app) + + return app From e9eb0909ceee4d1c35608185245477eaa2c7edc2 Mon Sep 17 00:00:00 2001 From: -LAN- Date: Wed, 18 Dec 2024 00:51:09 +0800 Subject: [PATCH 2/2] feat(app): refactor db command check into a separate function Signed-off-by: -LAN- --- api/app.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/api/app.py b/api/app.py index ddae1e57b851d6..c6a08290804a65 100644 --- a/api/app.py +++ b/api/app.py @@ -1,12 +1,19 @@ -import sys - from libs import version_utils # preparation before creating app version_utils.check_supported_python_version() + +def is_db_command(): + import sys + + if len(sys.argv) > 1 and sys.argv[0].endswith("flask") and sys.argv[1] == "db": + return True + return False + + # create app -if "db" in sys.argv: +if is_db_command(): from app_factory import create_migrations_app app = create_migrations_app()