From 0262143a4d5624c90b09071c5367e2f533c4c96b Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Fri, 22 Nov 2024 21:21:57 +0100 Subject: [PATCH] prevent env api breaking change --- reflex/app.py | 16 ++++--------- reflex/compiler/compiler.py | 4 ++-- reflex/components/core/upload.py | 4 ++-- reflex/config.py | 6 +++-- reflex/constants/base.py | 15 +++++------- reflex/constants/installer.py | 8 +++---- reflex/custom_components/custom_components.py | 6 ++--- reflex/model.py | 16 ++++++------- reflex/reflex.py | 16 ++++++------- reflex/state.py | 18 +++++++-------- reflex/testing.py | 14 +++++------ reflex/utils/exec.py | 16 ++++++------- reflex/utils/net.py | 4 ++-- reflex/utils/path_ops.py | 6 ++--- reflex/utils/prerequisites.py | 23 ++++++++----------- reflex/utils/registry.py | 4 ++-- reflex/utils/telemetry.py | 4 ++-- tests/integration/conftest.py | 13 ++++------- tests/integration/test_minified_states.py | 6 ++--- tests/units/test_config.py | 4 ++-- tests/units/utils/test_utils.py | 8 +++---- 21 files changed, 98 insertions(+), 113 deletions(-) diff --git a/reflex/app.py b/reflex/app.py index 678868fbb..afc40e3b8 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -65,7 +65,7 @@ from reflex.components.core.client_side_routing import ( ) from reflex.components.core.upload import Upload, get_upload_dir from reflex.components.radix import themes -from reflex.config import EnvironmentVariables, get_config +from reflex.config import environment, get_config from reflex.event import ( BASE_STATE, Event, @@ -503,10 +503,7 @@ class App(MiddlewareMixin, LifespanMixin): # Check if the route given is valid verify_route_validity(route) - if ( - route in self.unevaluated_pages - and EnvironmentVariables.RELOAD_CONFIG.is_set() - ): + if route in self.unevaluated_pages and environment.RELOAD_CONFIG.is_set(): # when the app is reloaded(typically for app harness tests), we should maintain # the latest render function of a route.This applies typically to decorated pages # since they are only added when app._compile is called. @@ -723,7 +720,7 @@ class App(MiddlewareMixin, LifespanMixin): Whether the app should be compiled. """ # Check the environment variable. - if EnvironmentVariables.REFLEX_SKIP_COMPILE.get(): + if environment.REFLEX_SKIP_COMPILE.get(): return False nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE @@ -945,10 +942,7 @@ class App(MiddlewareMixin, LifespanMixin): executor = None if ( platform.system() in ("Linux", "Darwin") - and ( - number_of_processes - := EnvironmentVariables.REFLEX_COMPILE_PROCESSES.get() - ) + and (number_of_processes := environment.REFLEX_COMPILE_PROCESSES.get()) is not None ): executor = concurrent.futures.ProcessPoolExecutor( @@ -957,7 +951,7 @@ class App(MiddlewareMixin, LifespanMixin): ) else: executor = concurrent.futures.ThreadPoolExecutor( - max_workers=EnvironmentVariables.REFLEX_COMPILE_THREADS.get() + max_workers=environment.REFLEX_COMPILE_THREADS.get() ) for route, component in zip(self.pages, page_components): diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index d6bc533ca..4122a0938 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -16,7 +16,7 @@ from reflex.components.component import ( CustomComponent, StatefulComponent, ) -from reflex.config import EnvironmentVariables, get_config +from reflex.config import environment, get_config from reflex.state import BaseState from reflex.style import SYSTEM_COLOR_MODE from reflex.utils.exec import is_prod_mode @@ -527,7 +527,7 @@ def remove_tailwind_from_postcss() -> tuple[str, str]: def purge_web_pages_dir(): """Empty out .web/pages directory.""" - if not is_prod_mode() and EnvironmentVariables.REFLEX_PERSIST_WEB_DIR.get(): + if not is_prod_mode() and environment.REFLEX_PERSIST_WEB_DIR.get(): # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set. return diff --git a/reflex/components/core/upload.py b/reflex/components/core/upload.py index c4f2ec0e2..33dfae40f 100644 --- a/reflex/components/core/upload.py +++ b/reflex/components/core/upload.py @@ -14,7 +14,7 @@ from reflex.components.component import ( ) from reflex.components.el.elements.forms import Input from reflex.components.radix.themes.layout.box import Box -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.constants import Dirs from reflex.constants.compiler import Hooks, Imports from reflex.event import ( @@ -133,7 +133,7 @@ def get_upload_dir() -> Path: """ Upload.is_used = True - uploaded_files_dir = EnvironmentVariables.REFLEX_UPLOADED_FILES_DIR.get() + uploaded_files_dir = environment.REFLEX_UPLOADED_FILES_DIR.get() uploaded_files_dir.mkdir(parents=True, exist_ok=True) return uploaded_files_dir diff --git a/reflex/config.py b/reflex/config.py index 7ce6d2d7d..a882ce9d2 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -591,11 +591,13 @@ class EnvironmentVariables: # Whether to minify state names. Default to true in prod mode and false otherwise. REFLEX_MINIFY_STATES: EnvVar[Optional[bool]] = env_var( - default_factory=lambda: EnvironmentVariables.REFLEX_ENV_MODE.get() - == constants.Env.PROD + default_factory=lambda: environment.REFLEX_ENV_MODE.get() == constants.Env.PROD ) +environment = EnvironmentVariables + + class Config(Base): """The config defines runtime settings for the app. diff --git a/reflex/constants/base.py b/reflex/constants/base.py index 48d2593dc..3266043c5 100644 --- a/reflex/constants/base.py +++ b/reflex/constants/base.py @@ -123,10 +123,10 @@ class Templates(SimpleNamespace): Returns: The URL to redirect to reflex.build. """ - from reflex.config import EnvironmentVariables + from reflex.config import environment return ( - EnvironmentVariables.REFLEX_BUILD_FRONTEND.get() + environment.REFLEX_BUILD_FRONTEND.get() + "/gen?reflex_init_token={reflex_init_token}" ) @@ -138,12 +138,9 @@ class Templates(SimpleNamespace): Returns: The URL to poll waiting for the user to select a generation. """ - from reflex.config import EnvironmentVariables + from reflex.config import environment - return ( - EnvironmentVariables.REFLEX_BUILD_BACKEND.get() - + "/api/init/{reflex_init_token}" - ) + return environment.REFLEX_BUILD_BACKEND.get() + "/api/init/{reflex_init_token}" @classproperty @classmethod @@ -153,10 +150,10 @@ class Templates(SimpleNamespace): Returns: The URL to fetch the generation's reflex code. """ - from reflex.config import EnvironmentVariables + from reflex.config import environment return ( - EnvironmentVariables.REFLEX_BUILD_BACKEND.get() + environment.REFLEX_BUILD_BACKEND.get() + "/api/gen/{generation_hash}/refactored" ) diff --git a/reflex/constants/installer.py b/reflex/constants/installer.py index 0b91aa7ac..0b45586dd 100644 --- a/reflex/constants/installer.py +++ b/reflex/constants/installer.py @@ -61,9 +61,9 @@ class Bun(SimpleNamespace): Returns: The directory to store the bun. """ - from reflex.config import EnvironmentVariables + from reflex.config import environment - return EnvironmentVariables.REFLEX_DIR.get() / "bun" + return environment.REFLEX_DIR.get() / "bun" @classproperty @classmethod @@ -103,9 +103,9 @@ class Fnm(SimpleNamespace): Returns: The directory to store fnm. """ - from reflex.config import EnvironmentVariables + from reflex.config import environment - return EnvironmentVariables.REFLEX_DIR.get() / "fnm" + return environment.REFLEX_DIR.get() / "fnm" @classproperty @classmethod diff --git a/reflex/custom_components/custom_components.py b/reflex/custom_components/custom_components.py index acd550af4..1406e37bc 100644 --- a/reflex/custom_components/custom_components.py +++ b/reflex/custom_components/custom_components.py @@ -17,7 +17,7 @@ import typer from tomlkit.exceptions import TOMLKitError from reflex import constants -from reflex.config import EnvironmentVariables, get_config +from reflex.config import environment, get_config from reflex.constants import CustomComponents from reflex.utils import console @@ -609,14 +609,14 @@ def publish( help="The API token to use for authentication on python package repository. If token is provided, no username/password should be provided at the same time", ), username: Optional[str] = typer.Option( - EnvironmentVariables.TWINE_USERNAME.get(), + environment.TWINE_USERNAME.get(), "-u", "--username", show_default="TWINE_USERNAME environment variable value if set", help="The username to use for authentication on python package repository. Username and password must both be provided.", ), password: Optional[str] = typer.Option( - EnvironmentVariables.TWINE_PASSWORD.get(), + environment.TWINE_PASSWORD.get(), "-p", "--password", show_default="TWINE_PASSWORD environment variable value if set", diff --git a/reflex/model.py b/reflex/model.py index 9252b3a5c..4b070ec67 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -17,7 +17,7 @@ import sqlalchemy.exc import sqlalchemy.orm from reflex.base import Base -from reflex.config import EnvironmentVariables, get_config +from reflex.config import environment, get_config from reflex.utils import console from reflex.utils.compat import sqlmodel, sqlmodel_field_has_primary_key @@ -38,12 +38,12 @@ def get_engine(url: str | None = None) -> sqlalchemy.engine.Engine: url = url or conf.db_url if url is None: raise ValueError("No database url configured") - if not EnvironmentVariables.ALEMBIC_CONFIG.get().exists(): + if not environment.ALEMBIC_CONFIG.get().exists(): console.warn( "Database is not initialized, run [bold]reflex db init[/bold] first." ) # Print the SQL queries if the log level is INFO or lower. - echo_db_query = EnvironmentVariables.SQLALCHEMY_ECHO.get() + echo_db_query = environment.SQLALCHEMY_ECHO.get() # Needed for the admin dash on sqlite. connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {} return sqlmodel.create_engine(url, echo=echo_db_query, connect_args=connect_args) @@ -231,7 +231,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue Returns: tuple of (config, script_directory) """ - config = alembic.config.Config(EnvironmentVariables.ALEMBIC_CONFIG.get()) + config = alembic.config.Config(environment.ALEMBIC_CONFIG.get()) return config, alembic.script.ScriptDirectory( config.get_main_option("script_location", default="version"), ) @@ -266,8 +266,8 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue def alembic_init(cls): """Initialize alembic for the project.""" alembic.command.init( - config=alembic.config.Config(EnvironmentVariables.ALEMBIC_CONFIG.get()), - directory=str(EnvironmentVariables.ALEMBIC_CONFIG.get().parent / "alembic"), + config=alembic.config.Config(environment.ALEMBIC_CONFIG.get()), + directory=str(environment.ALEMBIC_CONFIG.get().parent / "alembic"), ) @classmethod @@ -287,7 +287,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue Returns: True when changes have been detected. """ - if not EnvironmentVariables.ALEMBIC_CONFIG.get().exists(): + if not environment.ALEMBIC_CONFIG.get().exists(): return False config, script_directory = cls._alembic_config() @@ -388,7 +388,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue True - indicating the process was successful. None - indicating the process was skipped. """ - if not EnvironmentVariables.ALEMBIC_CONFIG.get().exists(): + if not environment.ALEMBIC_CONFIG.get().exists(): return with cls.get_db_engine().connect() as connection: diff --git a/reflex/reflex.py b/reflex/reflex.py index 1b5db81bf..9c3a96c89 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 EnvironmentVariables, get_config +from reflex.config import environment, get_config from reflex.custom_components.custom_components import custom_components_cli from reflex.utils import console, telemetry @@ -136,7 +136,7 @@ def _run( """Run the app in the given directory.""" # Set env mode in the environment # This must be set before importing modules that contain rx.State subclasses - EnvironmentVariables.REFLEX_ENV_MODE.set(env) + environment.REFLEX_ENV_MODE.set(env) from reflex.state import reset_disk_state_manager from reflex.utils import build, exec, prerequisites, processes @@ -259,13 +259,13 @@ def run( False, "--frontend-only", help="Execute only frontend.", - envvar=EnvironmentVariables.REFLEX_FRONTEND_ONLY.name, + envvar=environment.REFLEX_FRONTEND_ONLY.name, ), backend: bool = typer.Option( False, "--backend-only", help="Execute only backend.", - envvar=EnvironmentVariables.REFLEX_BACKEND_ONLY.name, + envvar=environment.REFLEX_BACKEND_ONLY.name, ), frontend_port: str = typer.Option( config.frontend_port, help="Specify a different frontend port." @@ -284,8 +284,8 @@ def run( if frontend and backend: console.error("Cannot use both --frontend-only and --backend-only options.") raise typer.Exit(1) - EnvironmentVariables.REFLEX_BACKEND_ONLY.set(backend) - EnvironmentVariables.REFLEX_FRONTEND_ONLY.set(frontend) + environment.REFLEX_BACKEND_ONLY.set(backend) + environment.REFLEX_FRONTEND_ONLY.set(frontend) _run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel) @@ -415,7 +415,7 @@ script_cli = typer.Typer() def _skip_compile(): """Skip the compile step.""" - EnvironmentVariables.REFLEX_SKIP_COMPILE.set(True) + environment.REFLEX_SKIP_COMPILE.set(True) @db_cli.command(name="init") @@ -430,7 +430,7 @@ def db_init(): return # Check the alembic config. - if EnvironmentVariables.ALEMBIC_CONFIG.get().exists(): + if environment.ALEMBIC_CONFIG.get().exists(): console.error( "Database is already initialized. Use " "[bold]reflex db makemigrations[/bold] to create schema change " diff --git a/reflex/state.py b/reflex/state.py index 9fe877089..4c2fb8f59 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -76,7 +76,7 @@ from redis.exceptions import ResponseError import reflex.istate.dynamic from reflex import constants from reflex.base import Base -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.event import ( BACKGROUND_TASK_MARKER, Event, @@ -118,11 +118,9 @@ Delta = Dict[str, Any] var = computed_var -if EnvironmentVariables.REFLEX_PERF_MODE.get() != PerformanceMode.OFF: +if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF: # If the state is this large, it's considered a performance issue. - TOO_LARGE_SERIALIZED_STATE = ( - EnvironmentVariables.REFLEX_STATE_SIZE_LIMIT.get() * 1024 - ) + TOO_LARGE_SERIALIZED_STATE = environment.REFLEX_STATE_SIZE_LIMIT.get() * 1024 # Only warn about each state class size once. _WARNED_ABOUT_STATE_SIZE: Set[str] = set() @@ -954,7 +952,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """ module = cls.__module__.replace(".", "___") state_name = format.to_snake_case(f"{module}___{cls.__name__}") - if EnvironmentVariables.REFLEX_MINIFY_STATES.get(): + if environment.REFLEX_MINIFY_STATES.get(): return get_minified_state_name(state_name) return state_name @@ -2188,9 +2186,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): f"State {state_full_name} serializes to {pickle_state_size} bytes " + "which may present performance issues. Consider reducing the size of this state." ) - if EnvironmentVariables.REFLEX_PERF_MODE.get() == PerformanceMode.WARN: + if environment.REFLEX_PERF_MODE.get() == PerformanceMode.WARN: console.warn(msg) - elif EnvironmentVariables.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE: + elif environment.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE: raise StateTooLargeError(msg) _WARNED_ABOUT_STATE_SIZE.add(state_full_name) @@ -2233,7 +2231,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """ try: pickle_state = pickle.dumps((self._to_schema(), self)) - if EnvironmentVariables.REFLEX_PERF_MODE.get() != PerformanceMode.OFF: + if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF: self._check_state_size(len(pickle_state)) return pickle_state except HANDLED_PICKLE_ERRORS as og_pickle_error: @@ -3516,7 +3514,7 @@ class StateManagerRedis(StateManager): ) except ResponseError: # Some redis servers only allow out-of-band configuration, so ignore errors here. - if not EnvironmentVariables.REFLEX_IGNORE_REDIS_CONFIG_ERROR.get(): + if not environment.REFLEX_IGNORE_REDIS_CONFIG_ERROR.get(): raise async with self.redis.pubsub() as pubsub: await pubsub.psubscribe(lock_key_channel) diff --git a/reflex/testing.py b/reflex/testing.py index 036cf219a..ac0b563fd 100644 --- a/reflex/testing.py +++ b/reflex/testing.py @@ -43,7 +43,7 @@ import reflex.utils.exec import reflex.utils.format import reflex.utils.prerequisites import reflex.utils.processes -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.state import ( BaseState, State, @@ -198,7 +198,7 @@ class AppHarness: state_name = reflex.utils.format.to_snake_case( f"{self.app_name}___{self.app_name}___" + state_cls_name ) - if EnvironmentVariables.REFLEX_MINIFY_STATES.get(): + if environment.REFLEX_MINIFY_STATES.get(): return minified_state_names.get(state_name, state_name) return state_name @@ -623,10 +623,10 @@ class AppHarness: if self.frontend_url is None: raise RuntimeError("Frontend is not running.") want_headless = False - if EnvironmentVariables.APP_HARNESS_HEADLESS.get(): + if environment.APP_HARNESS_HEADLESS.get(): want_headless = True if driver_clz is None: - requested_driver = EnvironmentVariables.APP_HARNESS_DRIVER.get() + requested_driver = environment.APP_HARNESS_DRIVER.get() driver_clz = getattr(webdriver, requested_driver) if driver_options is None: driver_options = getattr(webdriver, f"{requested_driver}Options")() @@ -648,7 +648,7 @@ class AppHarness: driver_options.add_argument("headless") if driver_options is None: raise RuntimeError(f"Could not determine options for {driver_clz}") - if args := EnvironmentVariables.APP_HARNESS_DRIVER_ARGS.get(): + if args := environment.APP_HARNESS_DRIVER_ARGS.get(): for arg in args.split(","): driver_options.add_argument(arg) if driver_option_args is not None: @@ -955,7 +955,7 @@ class AppHarnessProd(AppHarness): def _start_backend(self): if self.app_instance is None: raise RuntimeError("App was not initialized.") - EnvironmentVariables.REFLEX_SKIP_COMPILE.set(True) + environment.REFLEX_SKIP_COMPILE.set(True) self.backend = uvicorn.Server( uvicorn.Config( app=self.app_instance, @@ -973,7 +973,7 @@ class AppHarnessProd(AppHarness): try: return super()._poll_for_servers(timeout) finally: - EnvironmentVariables.REFLEX_SKIP_COMPILE.set(None) + environment.REFLEX_SKIP_COMPILE.set(None) @override def stop(self): diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index aae877368..5291de095 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -15,7 +15,7 @@ from urllib.parse import urljoin import psutil from reflex import constants -from reflex.config import EnvironmentVariables, get_config +from reflex.config import environment, get_config from reflex.constants.base import LogLevel from reflex.utils import console, path_ops from reflex.utils.prerequisites import get_web_dir @@ -184,7 +184,7 @@ def should_use_granian(): Returns: True if Granian should be used. """ - return EnvironmentVariables.REFLEX_USE_GRANIAN.get() + return environment.REFLEX_USE_GRANIAN.get() def get_app_module(): @@ -370,7 +370,7 @@ def run_uvicorn_backend_prod(host, port, loglevel): run=True, show_logs=True, env={ - EnvironmentVariables.REFLEX_SKIP_COMPILE.name: "true" + environment.REFLEX_SKIP_COMPILE.name: "true" }, # skip compile for prod backend ) @@ -407,7 +407,7 @@ def run_granian_backend_prod(host, port, loglevel): run=True, show_logs=True, env={ - EnvironmentVariables.REFLEX_SKIP_COMPILE.name: "true" + environment.REFLEX_SKIP_COMPILE.name: "true" }, # skip compile for prod backend ) except ImportError: @@ -493,7 +493,7 @@ def is_prod_mode() -> bool: Returns: True if the app is running in production mode or False if running in dev mode. """ - current_mode = EnvironmentVariables.REFLEX_ENV_MODE.get() + current_mode = environment.REFLEX_ENV_MODE.get() return current_mode == constants.Env.PROD @@ -509,7 +509,7 @@ def is_frontend_only() -> bool: deprecation_version="0.6.5", removal_version="0.7.0", ) - return EnvironmentVariables.REFLEX_FRONTEND_ONLY.get() + return environment.REFLEX_FRONTEND_ONLY.get() def is_backend_only() -> bool: @@ -524,7 +524,7 @@ def is_backend_only() -> bool: deprecation_version="0.6.5", removal_version="0.7.0", ) - return EnvironmentVariables.REFLEX_BACKEND_ONLY.get() + return environment.REFLEX_BACKEND_ONLY.get() def should_skip_compile() -> bool: @@ -539,4 +539,4 @@ def should_skip_compile() -> bool: deprecation_version="0.6.5", removal_version="0.7.0", ) - return EnvironmentVariables.REFLEX_SKIP_COMPILE.get() + return environment.REFLEX_SKIP_COMPILE.get() diff --git a/reflex/utils/net.py b/reflex/utils/net.py index f664bf9b6..acc202912 100644 --- a/reflex/utils/net.py +++ b/reflex/utils/net.py @@ -2,7 +2,7 @@ import httpx -from ..config import EnvironmentVariables +from ..config import environment from . import console @@ -12,7 +12,7 @@ def _httpx_verify_kwarg() -> bool: Returns: True if SSL verification is enabled, False otherwise """ - return not EnvironmentVariables.SSL_NO_VERIFY.get() + return not environment.SSL_NO_VERIFY.get() def get(url: str, **kwargs) -> httpx.Response: diff --git a/reflex/utils/path_ops.py b/reflex/utils/path_ops.py index de3dbe32c..a2ba2b151 100644 --- a/reflex/utils/path_ops.py +++ b/reflex/utils/path_ops.py @@ -9,7 +9,7 @@ import shutil from pathlib import Path from reflex import constants -from reflex.config import EnvironmentVariables +from reflex.config import environment # Shorthand for join. join = os.linesep.join @@ -136,7 +136,7 @@ def use_system_node() -> bool: Returns: Whether the system node should be used. """ - return EnvironmentVariables.REFLEX_USE_SYSTEM_NODE.get() + return environment.REFLEX_USE_SYSTEM_NODE.get() def use_system_bun() -> bool: @@ -145,7 +145,7 @@ def use_system_bun() -> bool: Returns: Whether the system bun should be used. """ - return EnvironmentVariables.REFLEX_USE_SYSTEM_BUN.get() + return environment.REFLEX_USE_SYSTEM_BUN.get() def get_node_bin_path() -> Path | None: diff --git a/reflex/utils/prerequisites.py b/reflex/utils/prerequisites.py index d06d7215f..35eb3234f 100644 --- a/reflex/utils/prerequisites.py +++ b/reflex/utils/prerequisites.py @@ -33,7 +33,7 @@ from redis.asyncio import Redis from reflex import constants, model from reflex.compiler import templates -from reflex.config import Config, EnvironmentVariables, get_config +from reflex.config import Config, environment, get_config from reflex.utils import console, net, path_ops, processes, redir from reflex.utils.exceptions import ( GeneratedCodeHasNoFunctionDefs, @@ -72,7 +72,7 @@ def get_web_dir() -> Path: Returns: The working directory. """ - return EnvironmentVariables.REFLEX_WEB_WORKDIR.get() + return environment.REFLEX_WEB_WORKDIR.get() def _python_version_check(): @@ -93,7 +93,7 @@ def check_latest_package_version(package_name: str): Args: package_name: The name of the package. """ - if EnvironmentVariables.REFLEX_CHECK_LATEST_VERSION.get() is False: + if environment.REFLEX_CHECK_LATEST_VERSION.get() is False: return try: # Get the latest version from PyPI @@ -265,7 +265,7 @@ def windows_npm_escape_hatch() -> bool: Returns: If the user has set REFLEX_USE_NPM. """ - return EnvironmentVariables.REFLEX_USE_NPM.get() + return environment.REFLEX_USE_NPM.get() def get_app(reload: bool = False) -> ModuleType: @@ -283,7 +283,7 @@ def get_app(reload: bool = False) -> ModuleType: from reflex.utils import telemetry try: - EnvironmentVariables.RELOAD_CONFIG.set(reload) + environment.RELOAD_CONFIG.set(reload) config = get_config() if not config.app_name: raise RuntimeError( @@ -1026,7 +1026,7 @@ def needs_reinit(frontend: bool = True) -> bool: return False # Make sure the .reflex directory exists. - if not EnvironmentVariables.REFLEX_DIR.get().exists(): + if not environment.REFLEX_DIR.get().exists(): return True # Make sure the .web directory exists in frontend mode. @@ -1131,7 +1131,7 @@ def ensure_reflex_installation_id() -> Optional[int]: """ try: initialize_reflex_user_directory() - installation_id_file = EnvironmentVariables.REFLEX_DIR.get() / "installation_id" + installation_id_file = environment.REFLEX_DIR.get() / "installation_id" installation_id = None if installation_id_file.exists(): @@ -1156,7 +1156,7 @@ def ensure_reflex_installation_id() -> Optional[int]: def initialize_reflex_user_directory(): """Initialize the reflex user directory.""" # Create the reflex directory. - path_ops.mkdir(EnvironmentVariables.REFLEX_DIR.get()) + path_ops.mkdir(environment.REFLEX_DIR.get()) def initialize_frontend_dependencies(): @@ -1181,7 +1181,7 @@ def check_db_initialized() -> bool: """ if ( get_config().db_url is not None - and not EnvironmentVariables.ALEMBIC_CONFIG.get().exists() + and not environment.ALEMBIC_CONFIG.get().exists() ): console.error( "Database is not initialized. Run [bold]reflex db init[/bold] first." @@ -1192,10 +1192,7 @@ def check_db_initialized() -> bool: def check_schema_up_to_date(): """Check if the sqlmodel metadata matches the current database schema.""" - if ( - get_config().db_url is None - or not EnvironmentVariables.ALEMBIC_CONFIG.get().exists() - ): + if get_config().db_url is None or not environment.ALEMBIC_CONFIG.get().exists(): return with model.Model.get_db_engine().connect() as connection: try: diff --git a/reflex/utils/registry.py b/reflex/utils/registry.py index 988186aa1..d98178c61 100644 --- a/reflex/utils/registry.py +++ b/reflex/utils/registry.py @@ -2,7 +2,7 @@ import httpx -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.utils import console, net @@ -55,4 +55,4 @@ def _get_npm_registry() -> str: Returns: str: """ - return EnvironmentVariables.NPM_CONFIG_REGISTRY.get() or get_best_registry() + return environment.NPM_CONFIG_REGISTRY.get() or get_best_registry() diff --git a/reflex/utils/telemetry.py b/reflex/utils/telemetry.py index 2a596ea5c..815d37a1b 100644 --- a/reflex/utils/telemetry.py +++ b/reflex/utils/telemetry.py @@ -8,7 +8,7 @@ import multiprocessing import platform import warnings -from reflex.config import EnvironmentVariables +from reflex.config import environment try: from datetime import UTC, datetime @@ -96,7 +96,7 @@ def _raise_on_missing_project_hash() -> bool: False when compilation should be skipped (i.e. no .web directory is required). Otherwise return True. """ - return not EnvironmentVariables.REFLEX_SKIP_COMPILE.get() + return not environment.REFLEX_SKIP_COMPILE.get() def _prepare_event(event: str, **kwargs) -> dict: diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index aaae9faeb..75dbd7f77 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -8,7 +8,7 @@ from typing import Generator, Type import pytest import reflex.constants -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.constants.base import Env from reflex.testing import AppHarness, AppHarnessProd @@ -25,10 +25,7 @@ def xvfb(): Yields: the pyvirtualdisplay object that the browser will be open on """ - if ( - os.environ.get("GITHUB_ACTIONS") - and not EnvironmentVariables.APP_HARNESS_HEADLESS.get() - ): + if os.environ.get("GITHUB_ACTIONS") and not environment.APP_HARNESS_HEADLESS.get(): from pyvirtualdisplay.smartdisplay import ( # pyright: ignore [reportMissingImports] SmartDisplay, ) @@ -49,7 +46,7 @@ def pytest_exception_interact(node, call, report): call: The pytest call describing when/where the test was invoked. report: The pytest log report object. """ - screenshot_dir = EnvironmentVariables.SCREENSHOT_DIR.get() + screenshot_dir = environment.SCREENSHOT_DIR.get() if DISPLAY is None or screenshot_dir is None: return @@ -93,7 +90,7 @@ def app_harness_env( """ harness: Type[AppHarness] = request.param if issubclass(harness, AppHarnessProd): - EnvironmentVariables.REFLEX_ENV_MODE.set(Env.PROD) + environment.REFLEX_ENV_MODE.set(Env.PROD) yield harness if isinstance(harness, AppHarnessProd): - EnvironmentVariables.REFLEX_ENV_MODE.set(None) + environment.REFLEX_ENV_MODE.set(None) diff --git a/tests/integration/test_minified_states.py b/tests/integration/test_minified_states.py index 37c5c8a0f..da63b6f7c 100644 --- a/tests/integration/test_minified_states.py +++ b/tests/integration/test_minified_states.py @@ -9,7 +9,7 @@ import pytest from selenium.webdriver.common.by import By from selenium.webdriver.remote.webdriver import WebDriver -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.testing import AppHarness, AppHarnessProd @@ -62,9 +62,9 @@ def minify_state_env( minify_states: whether to minify state names """ minify_states: Optional[bool] = request.param - EnvironmentVariables.REFLEX_MINIFY_STATES.set(minify_states) + environment.REFLEX_MINIFY_STATES.set(minify_states) yield minify_states - EnvironmentVariables.REFLEX_MINIFY_STATES.set(None) + environment.REFLEX_MINIFY_STATES.set(None) @pytest.fixture diff --git a/tests/units/test_config.py b/tests/units/test_config.py index b0603aec6..308c83946 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -8,9 +8,9 @@ import pytest import reflex as rx import reflex.config from reflex.config import ( - EnvironmentVariables, EnvVar, env_var, + environment, interpret_boolean_env, interpret_enum_env, interpret_int_env, @@ -216,7 +216,7 @@ def test_replace_defaults( def reflex_dir_constant() -> Path: - return EnvironmentVariables.REFLEX_DIR.get() + return environment.REFLEX_DIR.get() def test_reflex_dir_env_var(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: diff --git a/tests/units/utils/test_utils.py b/tests/units/utils/test_utils.py index 29c6f8fb7..e3dae7a2b 100644 --- a/tests/units/utils/test_utils.py +++ b/tests/units/utils/test_utils.py @@ -10,7 +10,7 @@ from packaging import version from reflex import constants from reflex.base import Base -from reflex.config import EnvironmentVariables +from reflex.config import environment from reflex.event import EventHandler from reflex.state import BaseState from reflex.utils import build, prerequisites, types @@ -600,7 +600,7 @@ def cleanup_reflex_env_mode(): None """ yield - EnvironmentVariables.REFLEX_ENV_MODE.set(None) + environment.REFLEX_ENV_MODE.set(None) def test_is_prod_mode(cleanup_reflex_env_mode: None) -> None: @@ -609,7 +609,7 @@ def test_is_prod_mode(cleanup_reflex_env_mode: None) -> None: Args: cleanup_reflex_env_mode: Fixture to cleanup the reflex env mode. """ - EnvironmentVariables.REFLEX_ENV_MODE.set(constants.Env.PROD) + environment.REFLEX_ENV_MODE.set(constants.Env.PROD) assert utils_exec.is_prod_mode() - EnvironmentVariables.REFLEX_ENV_MODE.set(None) + environment.REFLEX_ENV_MODE.set(None) assert not utils_exec.is_prod_mode()