1
0
Эх сурвалжийг харах

prevent env api breaking change

Benedikt Bartscher 6 сар өмнө
parent
commit
0262143a4d

+ 5 - 11
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.core.upload import Upload, get_upload_dir
 from reflex.components.radix import themes
 from reflex.components.radix import themes
-from reflex.config import EnvironmentVariables, get_config
+from reflex.config import environment, get_config
 from reflex.event import (
 from reflex.event import (
     BASE_STATE,
     BASE_STATE,
     Event,
     Event,
@@ -503,10 +503,7 @@ class App(MiddlewareMixin, LifespanMixin):
         # Check if the route given is valid
         # Check if the route given is valid
         verify_route_validity(route)
         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
             # 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
             # the latest render function of a route.This applies typically to decorated pages
             # since they are only added when app._compile is called.
             # since they are only added when app._compile is called.
@@ -723,7 +720,7 @@ class App(MiddlewareMixin, LifespanMixin):
             Whether the app should be compiled.
             Whether the app should be compiled.
         """
         """
         # Check the environment variable.
         # Check the environment variable.
-        if EnvironmentVariables.REFLEX_SKIP_COMPILE.get():
+        if environment.REFLEX_SKIP_COMPILE.get():
             return False
             return False
 
 
         nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
         nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
@@ -945,10 +942,7 @@ class App(MiddlewareMixin, LifespanMixin):
         executor = None
         executor = None
         if (
         if (
             platform.system() in ("Linux", "Darwin")
             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
             is not None
         ):
         ):
             executor = concurrent.futures.ProcessPoolExecutor(
             executor = concurrent.futures.ProcessPoolExecutor(
@@ -957,7 +951,7 @@ class App(MiddlewareMixin, LifespanMixin):
             )
             )
         else:
         else:
             executor = concurrent.futures.ThreadPoolExecutor(
             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):
         for route, component in zip(self.pages, page_components):

+ 2 - 2
reflex/compiler/compiler.py

@@ -16,7 +16,7 @@ from reflex.components.component import (
     CustomComponent,
     CustomComponent,
     StatefulComponent,
     StatefulComponent,
 )
 )
-from reflex.config import EnvironmentVariables, get_config
+from reflex.config import environment, get_config
 from reflex.state import BaseState
 from reflex.state import BaseState
 from reflex.style import SYSTEM_COLOR_MODE
 from reflex.style import SYSTEM_COLOR_MODE
 from reflex.utils.exec import is_prod_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():
 def purge_web_pages_dir():
     """Empty out .web/pages directory."""
     """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.
         # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
         return
         return
 
 

+ 2 - 2
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.el.elements.forms import Input
 from reflex.components.radix.themes.layout.box import Box
 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 import Dirs
 from reflex.constants.compiler import Hooks, Imports
 from reflex.constants.compiler import Hooks, Imports
 from reflex.event import (
 from reflex.event import (
@@ -133,7 +133,7 @@ def get_upload_dir() -> Path:
     """
     """
     Upload.is_used = True
     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)
     uploaded_files_dir.mkdir(parents=True, exist_ok=True)
     return uploaded_files_dir
     return uploaded_files_dir
 
 

+ 4 - 2
reflex/config.py

@@ -591,11 +591,13 @@ class EnvironmentVariables:
 
 
     # Whether to minify state names. Default to true in prod mode and false otherwise.
     # Whether to minify state names. Default to true in prod mode and false otherwise.
     REFLEX_MINIFY_STATES: EnvVar[Optional[bool]] = env_var(
     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):
 class Config(Base):
     """The config defines runtime settings for the app.
     """The config defines runtime settings for the app.
 
 

+ 6 - 9
reflex/constants/base.py

@@ -123,10 +123,10 @@ class Templates(SimpleNamespace):
         Returns:
         Returns:
             The URL to redirect to reflex.build.
             The URL to redirect to reflex.build.
         """
         """
-        from reflex.config import EnvironmentVariables
+        from reflex.config import environment
 
 
         return (
         return (
-            EnvironmentVariables.REFLEX_BUILD_FRONTEND.get()
+            environment.REFLEX_BUILD_FRONTEND.get()
             + "/gen?reflex_init_token={reflex_init_token}"
             + "/gen?reflex_init_token={reflex_init_token}"
         )
         )
 
 
@@ -138,12 +138,9 @@ class Templates(SimpleNamespace):
         Returns:
         Returns:
             The URL to poll waiting for the user to select a generation.
             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
     @classproperty
     @classmethod
     @classmethod
@@ -153,10 +150,10 @@ class Templates(SimpleNamespace):
         Returns:
         Returns:
             The URL to fetch the generation's reflex code.
             The URL to fetch the generation's reflex code.
         """
         """
-        from reflex.config import EnvironmentVariables
+        from reflex.config import environment
 
 
         return (
         return (
-            EnvironmentVariables.REFLEX_BUILD_BACKEND.get()
+            environment.REFLEX_BUILD_BACKEND.get()
             + "/api/gen/{generation_hash}/refactored"
             + "/api/gen/{generation_hash}/refactored"
         )
         )
 
 

+ 4 - 4
reflex/constants/installer.py

@@ -61,9 +61,9 @@ class Bun(SimpleNamespace):
         Returns:
         Returns:
             The directory to store the bun.
             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
     @classproperty
     @classmethod
     @classmethod
@@ -103,9 +103,9 @@ class Fnm(SimpleNamespace):
         Returns:
         Returns:
             The directory to store fnm.
             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
     @classproperty
     @classmethod
     @classmethod

+ 3 - 3
reflex/custom_components/custom_components.py

@@ -17,7 +17,7 @@ import typer
 from tomlkit.exceptions import TOMLKitError
 from tomlkit.exceptions import TOMLKitError
 
 
 from reflex import constants
 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.constants import CustomComponents
 from reflex.utils import console
 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",
         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(
     username: Optional[str] = typer.Option(
-        EnvironmentVariables.TWINE_USERNAME.get(),
+        environment.TWINE_USERNAME.get(),
         "-u",
         "-u",
         "--username",
         "--username",
         show_default="TWINE_USERNAME environment variable value if set",
         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.",
         help="The username to use for authentication on python package repository. Username and password must both be provided.",
     ),
     ),
     password: Optional[str] = typer.Option(
     password: Optional[str] = typer.Option(
-        EnvironmentVariables.TWINE_PASSWORD.get(),
+        environment.TWINE_PASSWORD.get(),
         "-p",
         "-p",
         "--password",
         "--password",
         show_default="TWINE_PASSWORD environment variable value if set",
         show_default="TWINE_PASSWORD environment variable value if set",

+ 8 - 8
reflex/model.py

@@ -17,7 +17,7 @@ import sqlalchemy.exc
 import sqlalchemy.orm
 import sqlalchemy.orm
 
 
 from reflex.base import Base
 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 import console
 from reflex.utils.compat import sqlmodel, sqlmodel_field_has_primary_key
 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
     url = url or conf.db_url
     if url is None:
     if url is None:
         raise ValueError("No database url configured")
         raise ValueError("No database url configured")
-    if not EnvironmentVariables.ALEMBIC_CONFIG.get().exists():
+    if not environment.ALEMBIC_CONFIG.get().exists():
         console.warn(
         console.warn(
             "Database is not initialized, run [bold]reflex db init[/bold] first."
             "Database is not initialized, run [bold]reflex db init[/bold] first."
         )
         )
     # Print the SQL queries if the log level is INFO or lower.
     # 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.
     # Needed for the admin dash on sqlite.
     connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {}
     connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {}
     return sqlmodel.create_engine(url, echo=echo_db_query, connect_args=connect_args)
     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:
         Returns:
             tuple of (config, script_directory)
             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(
         return config, alembic.script.ScriptDirectory(
             config.get_main_option("script_location", default="version"),
             config.get_main_option("script_location", default="version"),
         )
         )
@@ -266,8 +266,8 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
     def alembic_init(cls):
     def alembic_init(cls):
         """Initialize alembic for the project."""
         """Initialize alembic for the project."""
         alembic.command.init(
         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
     @classmethod
@@ -287,7 +287,7 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
         Returns:
         Returns:
             True when changes have been detected.
             True when changes have been detected.
         """
         """
-        if not EnvironmentVariables.ALEMBIC_CONFIG.get().exists():
+        if not environment.ALEMBIC_CONFIG.get().exists():
             return False
             return False
 
 
         config, script_directory = cls._alembic_config()
         config, script_directory = cls._alembic_config()
@@ -388,7 +388,7 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
             True - indicating the process was successful.
             True - indicating the process was successful.
             None - indicating the process was skipped.
             None - indicating the process was skipped.
         """
         """
-        if not EnvironmentVariables.ALEMBIC_CONFIG.get().exists():
+        if not environment.ALEMBIC_CONFIG.get().exists():
             return
             return
 
 
         with cls.get_db_engine().connect() as connection:
         with cls.get_db_engine().connect() as connection:

+ 8 - 8
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_cli.v2.deployments import check_version, hosting_cli
 
 
 from reflex import constants
 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.custom_components.custom_components import custom_components_cli
 from reflex.utils import console, telemetry
 from reflex.utils import console, telemetry
 
 
@@ -136,7 +136,7 @@ def _run(
     """Run the app in the given directory."""
     """Run the app in the given directory."""
     # Set env mode in the environment
     # Set env mode in the environment
     # This must be set before importing modules that contain rx.State subclasses
     # 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.state import reset_disk_state_manager
     from reflex.utils import build, exec, prerequisites, processes
     from reflex.utils import build, exec, prerequisites, processes
@@ -259,13 +259,13 @@ def run(
         False,
         False,
         "--frontend-only",
         "--frontend-only",
         help="Execute only frontend.",
         help="Execute only frontend.",
-        envvar=EnvironmentVariables.REFLEX_FRONTEND_ONLY.name,
+        envvar=environment.REFLEX_FRONTEND_ONLY.name,
     ),
     ),
     backend: bool = typer.Option(
     backend: bool = typer.Option(
         False,
         False,
         "--backend-only",
         "--backend-only",
         help="Execute only backend.",
         help="Execute only backend.",
-        envvar=EnvironmentVariables.REFLEX_BACKEND_ONLY.name,
+        envvar=environment.REFLEX_BACKEND_ONLY.name,
     ),
     ),
     frontend_port: str = typer.Option(
     frontend_port: str = typer.Option(
         config.frontend_port, help="Specify a different frontend port."
         config.frontend_port, help="Specify a different frontend port."
@@ -284,8 +284,8 @@ def run(
     if frontend and backend:
     if frontend and backend:
         console.error("Cannot use both --frontend-only and --backend-only options.")
         console.error("Cannot use both --frontend-only and --backend-only options.")
         raise typer.Exit(1)
         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)
     _run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel)
 
 
@@ -415,7 +415,7 @@ script_cli = typer.Typer()
 
 
 def _skip_compile():
 def _skip_compile():
     """Skip the compile step."""
     """Skip the compile step."""
-    EnvironmentVariables.REFLEX_SKIP_COMPILE.set(True)
+    environment.REFLEX_SKIP_COMPILE.set(True)
 
 
 
 
 @db_cli.command(name="init")
 @db_cli.command(name="init")
@@ -430,7 +430,7 @@ def db_init():
         return
         return
 
 
     # Check the alembic config.
     # Check the alembic config.
-    if EnvironmentVariables.ALEMBIC_CONFIG.get().exists():
+    if environment.ALEMBIC_CONFIG.get().exists():
         console.error(
         console.error(
             "Database is already initialized. Use "
             "Database is already initialized. Use "
             "[bold]reflex db makemigrations[/bold] to create schema change "
             "[bold]reflex db makemigrations[/bold] to create schema change "

+ 8 - 10
reflex/state.py

@@ -76,7 +76,7 @@ from redis.exceptions import ResponseError
 import reflex.istate.dynamic
 import reflex.istate.dynamic
 from reflex import constants
 from reflex import constants
 from reflex.base import Base
 from reflex.base import Base
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 from reflex.event import (
 from reflex.event import (
     BACKGROUND_TASK_MARKER,
     BACKGROUND_TASK_MARKER,
     Event,
     Event,
@@ -118,11 +118,9 @@ Delta = Dict[str, Any]
 var = computed_var
 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.
     # 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.
     # Only warn about each state class size once.
     _WARNED_ABOUT_STATE_SIZE: Set[str] = set()
     _WARNED_ABOUT_STATE_SIZE: Set[str] = set()
 
 
@@ -954,7 +952,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
         """
         """
         module = cls.__module__.replace(".", "___")
         module = cls.__module__.replace(".", "___")
         state_name = format.to_snake_case(f"{module}___{cls.__name__}")
         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 get_minified_state_name(state_name)
         return 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 "
                 f"State {state_full_name} serializes to {pickle_state_size} bytes "
                 + "which may present performance issues. Consider reducing the size of this state."
                 + "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)
                 console.warn(msg)
-            elif EnvironmentVariables.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE:
+            elif environment.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE:
                 raise StateTooLargeError(msg)
                 raise StateTooLargeError(msg)
             _WARNED_ABOUT_STATE_SIZE.add(state_full_name)
             _WARNED_ABOUT_STATE_SIZE.add(state_full_name)
 
 
@@ -2233,7 +2231,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
         """
         """
         try:
         try:
             pickle_state = pickle.dumps((self._to_schema(), self))
             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))
                 self._check_state_size(len(pickle_state))
             return pickle_state
             return pickle_state
         except HANDLED_PICKLE_ERRORS as og_pickle_error:
         except HANDLED_PICKLE_ERRORS as og_pickle_error:
@@ -3516,7 +3514,7 @@ class StateManagerRedis(StateManager):
             )
             )
         except ResponseError:
         except ResponseError:
             # Some redis servers only allow out-of-band configuration, so ignore errors here.
             # 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
                 raise
         async with self.redis.pubsub() as pubsub:
         async with self.redis.pubsub() as pubsub:
             await pubsub.psubscribe(lock_key_channel)
             await pubsub.psubscribe(lock_key_channel)

+ 7 - 7
reflex/testing.py

@@ -43,7 +43,7 @@ import reflex.utils.exec
 import reflex.utils.format
 import reflex.utils.format
 import reflex.utils.prerequisites
 import reflex.utils.prerequisites
 import reflex.utils.processes
 import reflex.utils.processes
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 from reflex.state import (
 from reflex.state import (
     BaseState,
     BaseState,
     State,
     State,
@@ -198,7 +198,7 @@ class AppHarness:
         state_name = reflex.utils.format.to_snake_case(
         state_name = reflex.utils.format.to_snake_case(
             f"{self.app_name}___{self.app_name}___" + state_cls_name
             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 minified_state_names.get(state_name, state_name)
         return state_name
         return state_name
 
 
@@ -623,10 +623,10 @@ class AppHarness:
         if self.frontend_url is None:
         if self.frontend_url is None:
             raise RuntimeError("Frontend is not running.")
             raise RuntimeError("Frontend is not running.")
         want_headless = False
         want_headless = False
-        if EnvironmentVariables.APP_HARNESS_HEADLESS.get():
+        if environment.APP_HARNESS_HEADLESS.get():
             want_headless = True
             want_headless = True
         if driver_clz is None:
         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)
             driver_clz = getattr(webdriver, requested_driver)
             if driver_options is None:
             if driver_options is None:
                 driver_options = getattr(webdriver, f"{requested_driver}Options")()
                 driver_options = getattr(webdriver, f"{requested_driver}Options")()
@@ -648,7 +648,7 @@ class AppHarness:
                 driver_options.add_argument("headless")
                 driver_options.add_argument("headless")
         if driver_options is None:
         if driver_options is None:
             raise RuntimeError(f"Could not determine options for {driver_clz}")
             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(","):
             for arg in args.split(","):
                 driver_options.add_argument(arg)
                 driver_options.add_argument(arg)
         if driver_option_args is not None:
         if driver_option_args is not None:
@@ -955,7 +955,7 @@ class AppHarnessProd(AppHarness):
     def _start_backend(self):
     def _start_backend(self):
         if self.app_instance is None:
         if self.app_instance is None:
             raise RuntimeError("App was not initialized.")
             raise RuntimeError("App was not initialized.")
-        EnvironmentVariables.REFLEX_SKIP_COMPILE.set(True)
+        environment.REFLEX_SKIP_COMPILE.set(True)
         self.backend = uvicorn.Server(
         self.backend = uvicorn.Server(
             uvicorn.Config(
             uvicorn.Config(
                 app=self.app_instance,
                 app=self.app_instance,
@@ -973,7 +973,7 @@ class AppHarnessProd(AppHarness):
         try:
         try:
             return super()._poll_for_servers(timeout)
             return super()._poll_for_servers(timeout)
         finally:
         finally:
-            EnvironmentVariables.REFLEX_SKIP_COMPILE.set(None)
+            environment.REFLEX_SKIP_COMPILE.set(None)
 
 
     @override
     @override
     def stop(self):
     def stop(self):

+ 8 - 8
reflex/utils/exec.py

@@ -15,7 +15,7 @@ from urllib.parse import urljoin
 import psutil
 import psutil
 
 
 from reflex import constants
 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.constants.base import LogLevel
 from reflex.utils import console, path_ops
 from reflex.utils import console, path_ops
 from reflex.utils.prerequisites import get_web_dir
 from reflex.utils.prerequisites import get_web_dir
@@ -184,7 +184,7 @@ def should_use_granian():
     Returns:
     Returns:
         True if Granian should be used.
         True if Granian should be used.
     """
     """
-    return EnvironmentVariables.REFLEX_USE_GRANIAN.get()
+    return environment.REFLEX_USE_GRANIAN.get()
 
 
 
 
 def get_app_module():
 def get_app_module():
@@ -370,7 +370,7 @@ def run_uvicorn_backend_prod(host, port, loglevel):
         run=True,
         run=True,
         show_logs=True,
         show_logs=True,
         env={
         env={
-            EnvironmentVariables.REFLEX_SKIP_COMPILE.name: "true"
+            environment.REFLEX_SKIP_COMPILE.name: "true"
         },  # skip compile for prod backend
         },  # skip compile for prod backend
     )
     )
 
 
@@ -407,7 +407,7 @@ def run_granian_backend_prod(host, port, loglevel):
             run=True,
             run=True,
             show_logs=True,
             show_logs=True,
             env={
             env={
-                EnvironmentVariables.REFLEX_SKIP_COMPILE.name: "true"
+                environment.REFLEX_SKIP_COMPILE.name: "true"
             },  # skip compile for prod backend
             },  # skip compile for prod backend
         )
         )
     except ImportError:
     except ImportError:
@@ -493,7 +493,7 @@ def is_prod_mode() -> bool:
     Returns:
     Returns:
         True if the app is running in production mode or False if running in dev mode.
         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
     return current_mode == constants.Env.PROD
 
 
 
 
@@ -509,7 +509,7 @@ def is_frontend_only() -> bool:
         deprecation_version="0.6.5",
         deprecation_version="0.6.5",
         removal_version="0.7.0",
         removal_version="0.7.0",
     )
     )
-    return EnvironmentVariables.REFLEX_FRONTEND_ONLY.get()
+    return environment.REFLEX_FRONTEND_ONLY.get()
 
 
 
 
 def is_backend_only() -> bool:
 def is_backend_only() -> bool:
@@ -524,7 +524,7 @@ def is_backend_only() -> bool:
         deprecation_version="0.6.5",
         deprecation_version="0.6.5",
         removal_version="0.7.0",
         removal_version="0.7.0",
     )
     )
-    return EnvironmentVariables.REFLEX_BACKEND_ONLY.get()
+    return environment.REFLEX_BACKEND_ONLY.get()
 
 
 
 
 def should_skip_compile() -> bool:
 def should_skip_compile() -> bool:
@@ -539,4 +539,4 @@ def should_skip_compile() -> bool:
         deprecation_version="0.6.5",
         deprecation_version="0.6.5",
         removal_version="0.7.0",
         removal_version="0.7.0",
     )
     )
-    return EnvironmentVariables.REFLEX_SKIP_COMPILE.get()
+    return environment.REFLEX_SKIP_COMPILE.get()

+ 2 - 2
reflex/utils/net.py

@@ -2,7 +2,7 @@
 
 
 import httpx
 import httpx
 
 
-from ..config import EnvironmentVariables
+from ..config import environment
 from . import console
 from . import console
 
 
 
 
@@ -12,7 +12,7 @@ def _httpx_verify_kwarg() -> bool:
     Returns:
     Returns:
         True if SSL verification is enabled, False otherwise
         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:
 def get(url: str, **kwargs) -> httpx.Response:

+ 3 - 3
reflex/utils/path_ops.py

@@ -9,7 +9,7 @@ import shutil
 from pathlib import Path
 from pathlib import Path
 
 
 from reflex import constants
 from reflex import constants
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 
 
 # Shorthand for join.
 # Shorthand for join.
 join = os.linesep.join
 join = os.linesep.join
@@ -136,7 +136,7 @@ def use_system_node() -> bool:
     Returns:
     Returns:
         Whether the system node should be used.
         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:
 def use_system_bun() -> bool:
@@ -145,7 +145,7 @@ def use_system_bun() -> bool:
     Returns:
     Returns:
         Whether the system bun should be used.
         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:
 def get_node_bin_path() -> Path | None:

+ 10 - 13
reflex/utils/prerequisites.py

@@ -33,7 +33,7 @@ from redis.asyncio import Redis
 
 
 from reflex import constants, model
 from reflex import constants, model
 from reflex.compiler import templates
 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 import console, net, path_ops, processes, redir
 from reflex.utils.exceptions import (
 from reflex.utils.exceptions import (
     GeneratedCodeHasNoFunctionDefs,
     GeneratedCodeHasNoFunctionDefs,
@@ -72,7 +72,7 @@ def get_web_dir() -> Path:
     Returns:
     Returns:
         The working directory.
         The working directory.
     """
     """
-    return EnvironmentVariables.REFLEX_WEB_WORKDIR.get()
+    return environment.REFLEX_WEB_WORKDIR.get()
 
 
 
 
 def _python_version_check():
 def _python_version_check():
@@ -93,7 +93,7 @@ def check_latest_package_version(package_name: str):
     Args:
     Args:
         package_name: The name of the package.
         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
         return
     try:
     try:
         # Get the latest version from PyPI
         # Get the latest version from PyPI
@@ -265,7 +265,7 @@ def windows_npm_escape_hatch() -> bool:
     Returns:
     Returns:
         If the user has set REFLEX_USE_NPM.
         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:
 def get_app(reload: bool = False) -> ModuleType:
@@ -283,7 +283,7 @@ def get_app(reload: bool = False) -> ModuleType:
     from reflex.utils import telemetry
     from reflex.utils import telemetry
 
 
     try:
     try:
-        EnvironmentVariables.RELOAD_CONFIG.set(reload)
+        environment.RELOAD_CONFIG.set(reload)
         config = get_config()
         config = get_config()
         if not config.app_name:
         if not config.app_name:
             raise RuntimeError(
             raise RuntimeError(
@@ -1026,7 +1026,7 @@ def needs_reinit(frontend: bool = True) -> bool:
         return False
         return False
 
 
     # Make sure the .reflex directory exists.
     # Make sure the .reflex directory exists.
-    if not EnvironmentVariables.REFLEX_DIR.get().exists():
+    if not environment.REFLEX_DIR.get().exists():
         return True
         return True
 
 
     # Make sure the .web directory exists in frontend mode.
     # Make sure the .web directory exists in frontend mode.
@@ -1131,7 +1131,7 @@ def ensure_reflex_installation_id() -> Optional[int]:
     """
     """
     try:
     try:
         initialize_reflex_user_directory()
         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
         installation_id = None
         if installation_id_file.exists():
         if installation_id_file.exists():
@@ -1156,7 +1156,7 @@ def ensure_reflex_installation_id() -> Optional[int]:
 def initialize_reflex_user_directory():
 def initialize_reflex_user_directory():
     """Initialize the reflex user directory."""
     """Initialize the reflex user directory."""
     # Create the reflex directory.
     # Create the reflex directory.
-    path_ops.mkdir(EnvironmentVariables.REFLEX_DIR.get())
+    path_ops.mkdir(environment.REFLEX_DIR.get())
 
 
 
 
 def initialize_frontend_dependencies():
 def initialize_frontend_dependencies():
@@ -1181,7 +1181,7 @@ def check_db_initialized() -> bool:
     """
     """
     if (
     if (
         get_config().db_url is not None
         get_config().db_url is not None
-        and not EnvironmentVariables.ALEMBIC_CONFIG.get().exists()
+        and not environment.ALEMBIC_CONFIG.get().exists()
     ):
     ):
         console.error(
         console.error(
             "Database is not initialized. Run [bold]reflex db init[/bold] first."
             "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():
 def check_schema_up_to_date():
     """Check if the sqlmodel metadata matches the current database schema."""
     """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
         return
     with model.Model.get_db_engine().connect() as connection:
     with model.Model.get_db_engine().connect() as connection:
         try:
         try:

+ 2 - 2
reflex/utils/registry.py

@@ -2,7 +2,7 @@
 
 
 import httpx
 import httpx
 
 
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 from reflex.utils import console, net
 from reflex.utils import console, net
 
 
 
 
@@ -55,4 +55,4 @@ def _get_npm_registry() -> str:
     Returns:
     Returns:
         str:
         str:
     """
     """
-    return EnvironmentVariables.NPM_CONFIG_REGISTRY.get() or get_best_registry()
+    return environment.NPM_CONFIG_REGISTRY.get() or get_best_registry()

+ 2 - 2
reflex/utils/telemetry.py

@@ -8,7 +8,7 @@ import multiprocessing
 import platform
 import platform
 import warnings
 import warnings
 
 
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 
 
 try:
 try:
     from datetime import UTC, datetime
     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).
         False when compilation should be skipped (i.e. no .web directory is required).
         Otherwise return True.
         Otherwise return True.
     """
     """
-    return not EnvironmentVariables.REFLEX_SKIP_COMPILE.get()
+    return not environment.REFLEX_SKIP_COMPILE.get()
 
 
 
 
 def _prepare_event(event: str, **kwargs) -> dict:
 def _prepare_event(event: str, **kwargs) -> dict:

+ 5 - 8
tests/integration/conftest.py

@@ -8,7 +8,7 @@ from typing import Generator, Type
 import pytest
 import pytest
 
 
 import reflex.constants
 import reflex.constants
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 from reflex.constants.base import Env
 from reflex.constants.base import Env
 from reflex.testing import AppHarness, AppHarnessProd
 from reflex.testing import AppHarness, AppHarnessProd
 
 
@@ -25,10 +25,7 @@ def xvfb():
     Yields:
     Yields:
         the pyvirtualdisplay object that the browser will be open on
         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]
         from pyvirtualdisplay.smartdisplay import (  # pyright: ignore [reportMissingImports]
             SmartDisplay,
             SmartDisplay,
         )
         )
@@ -49,7 +46,7 @@ def pytest_exception_interact(node, call, report):
         call: The pytest call describing when/where the test was invoked.
         call: The pytest call describing when/where the test was invoked.
         report: The pytest log report object.
         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:
     if DISPLAY is None or screenshot_dir is None:
         return
         return
 
 
@@ -93,7 +90,7 @@ def app_harness_env(
     """
     """
     harness: Type[AppHarness] = request.param
     harness: Type[AppHarness] = request.param
     if issubclass(harness, AppHarnessProd):
     if issubclass(harness, AppHarnessProd):
-        EnvironmentVariables.REFLEX_ENV_MODE.set(Env.PROD)
+        environment.REFLEX_ENV_MODE.set(Env.PROD)
     yield harness
     yield harness
     if isinstance(harness, AppHarnessProd):
     if isinstance(harness, AppHarnessProd):
-        EnvironmentVariables.REFLEX_ENV_MODE.set(None)
+        environment.REFLEX_ENV_MODE.set(None)

+ 3 - 3
tests/integration/test_minified_states.py

@@ -9,7 +9,7 @@ import pytest
 from selenium.webdriver.common.by import By
 from selenium.webdriver.common.by import By
 from selenium.webdriver.remote.webdriver import WebDriver
 from selenium.webdriver.remote.webdriver import WebDriver
 
 
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 from reflex.testing import AppHarness, AppHarnessProd
 from reflex.testing import AppHarness, AppHarnessProd
 
 
 
 
@@ -62,9 +62,9 @@ def minify_state_env(
         minify_states: whether to minify state names
         minify_states: whether to minify state names
     """
     """
     minify_states: Optional[bool] = request.param
     minify_states: Optional[bool] = request.param
-    EnvironmentVariables.REFLEX_MINIFY_STATES.set(minify_states)
+    environment.REFLEX_MINIFY_STATES.set(minify_states)
     yield minify_states
     yield minify_states
-    EnvironmentVariables.REFLEX_MINIFY_STATES.set(None)
+    environment.REFLEX_MINIFY_STATES.set(None)
 
 
 
 
 @pytest.fixture
 @pytest.fixture

+ 2 - 2
tests/units/test_config.py

@@ -8,9 +8,9 @@ import pytest
 import reflex as rx
 import reflex as rx
 import reflex.config
 import reflex.config
 from reflex.config import (
 from reflex.config import (
-    EnvironmentVariables,
     EnvVar,
     EnvVar,
     env_var,
     env_var,
+    environment,
     interpret_boolean_env,
     interpret_boolean_env,
     interpret_enum_env,
     interpret_enum_env,
     interpret_int_env,
     interpret_int_env,
@@ -216,7 +216,7 @@ def test_replace_defaults(
 
 
 
 
 def reflex_dir_constant() -> Path:
 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:
 def test_reflex_dir_env_var(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:

+ 4 - 4
tests/units/utils/test_utils.py

@@ -10,7 +10,7 @@ from packaging import version
 
 
 from reflex import constants
 from reflex import constants
 from reflex.base import Base
 from reflex.base import Base
-from reflex.config import EnvironmentVariables
+from reflex.config import environment
 from reflex.event import EventHandler
 from reflex.event import EventHandler
 from reflex.state import BaseState
 from reflex.state import BaseState
 from reflex.utils import build, prerequisites, types
 from reflex.utils import build, prerequisites, types
@@ -600,7 +600,7 @@ def cleanup_reflex_env_mode():
         None
         None
     """
     """
     yield
     yield
-    EnvironmentVariables.REFLEX_ENV_MODE.set(None)
+    environment.REFLEX_ENV_MODE.set(None)
 
 
 
 
 def test_is_prod_mode(cleanup_reflex_env_mode: None) -> 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:
     Args:
         cleanup_reflex_env_mode: Fixture to cleanup the reflex env mode.
         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()
     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()
     assert not utils_exec.is_prod_mode()