From c17c973d7f3446f00532a46c05a08433c4ee1791 Mon Sep 17 00:00:00 2001 From: Masen Furer Date: Wed, 11 Dec 2024 10:14:29 -0800 Subject: [PATCH] implement get_config_safe to get config via subprocess It's honking SLOW --- reflex/config.py | 28 +++++++++++++++++++ reflex/custom_components/custom_components.py | 4 +-- reflex/reflex.py | 6 ++-- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/reflex/config.py b/reflex/config.py index a882ce9d2..72c23ef1a 100644 --- a/reflex/config.py +++ b/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) diff --git a/reflex/custom_components/custom_components.py b/reflex/custom_components/custom_components.py index 1406e37bc..92ee1a576 100644 --- a/reflex/custom_components/custom_components.py +++ b/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 = ( diff --git a/reflex/reflex.py b/reflex/reflex.py index 7b74071f3..3b5c561a5 100644 --- a/reflex/reflex.py +++ b/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):