Procházet zdrojové kódy

implement get_config_safe to get config via subprocess

It's honking SLOW
Masen Furer před 5 měsíci
rodič
revize
c17c973d7f

+ 28 - 0
reflex/config.py

@@ -6,9 +6,12 @@ import enum
 import importlib
 import inspect
 import os
+import subprocess
 import sys
+import tempfile
 import threading
 import urllib.parse
+from functools import lru_cache
 from importlib.util import find_spec
 from pathlib import Path
 from typing import (
@@ -900,3 +903,28 @@ def get_config(reload: bool = False) -> Config:
             # Restore the original sys.path.
             sys.path.clear()
             sys.path.extend(sys_path)
+
+
+@lru_cache
+def get_config_safe() -> Config:
+    """Get the app config without introducing import side-effects.
+
+    Returns:
+        The app config.
+    """
+    with (
+        tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as script,
+        tempfile.NamedTemporaryFile() as config_json,
+    ):
+        script.write(f"""
+from pathlib import Path
+from reflex.config import get_config
+
+Path({config_json.name!r}).write_text(get_config().json())
+""")
+        script.flush()
+
+        subprocess.run(
+            [sys.executable, script.name],
+        )
+        return Config.parse_file(config_json.name)

+ 2 - 2
reflex/custom_components/custom_components.py

@@ -17,11 +17,11 @@ import typer
 from tomlkit.exceptions import TOMLKitError
 
 from reflex import constants
-from reflex.config import environment, get_config
+from reflex.config import environment, get_config_safe
 from reflex.constants import CustomComponents
 from reflex.utils import console
 
-config = get_config()
+config = get_config_safe()
 custom_components_cli = typer.Typer()
 
 POST_CUSTOM_COMPONENTS_GALLERY_ENDPOINT = (

+ 3 - 3
reflex/reflex.py

@@ -15,7 +15,7 @@ from reflex_cli.utils import dependency
 from reflex_cli.v2.deployments import check_version, hosting_cli
 
 from reflex import constants
-from reflex.config import environment, get_config
+from reflex.config import environment, get_config, get_config_safe
 from reflex.custom_components.custom_components import custom_components_cli
 from reflex.utils import console, telemetry
 
@@ -29,8 +29,8 @@ except TypeError:
     # Fallback for older typer versions.
     cli = typer.Typer(add_completion=False)
 
-# Get the config.
-config = get_config()
+# Get the config via subprocess without triggering import side-effects.
+config = get_config_safe()
 
 
 def version(value: bool):