From 9d44cd71a55cc88a538d9c8008c28ffe9091a723 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 31 Oct 2024 21:07:13 +0100 Subject: [PATCH] refactor EnvVar.get to be a method --- reflex/app.py | 6 +++--- reflex/compiler/compiler.py | 2 +- reflex/components/core/upload.py | 2 +- reflex/config.py | 4 +--- reflex/constants/base.py | 6 +++--- reflex/constants/installer.py | 4 ++-- reflex/custom_components/custom_components.py | 4 ++-- reflex/model.py | 14 +++++++------- reflex/reflex.py | 2 +- reflex/state.py | 2 +- reflex/testing.py | 6 +++--- reflex/utils/exec.py | 4 ++-- reflex/utils/net.py | 2 +- reflex/utils/path_ops.py | 4 ++-- reflex/utils/prerequisites.py | 17 ++++++++++------- reflex/utils/registry.py | 2 +- reflex/utils/telemetry.py | 2 +- tests/integration/conftest.py | 4 ++-- tests/units/test_config.py | 18 +++++++++--------- 19 files changed, 53 insertions(+), 52 deletions(-) diff --git a/reflex/app.py b/reflex/app.py index c4bbf8bf7..27bdd21ef 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -727,7 +727,7 @@ class App(MiddlewareMixin, LifespanMixin, Base): Whether the app should be compiled. """ # Check the environment variable. - if environment.REFLEX_SKIP_COMPILE.get: + if environment.REFLEX_SKIP_COMPILE.get(): return False nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE @@ -948,7 +948,7 @@ class App(MiddlewareMixin, LifespanMixin, Base): executor = None if ( platform.system() in ("Linux", "Darwin") - and (number_of_processes := environment.REFLEX_COMPILE_PROCESSES.get) + and (number_of_processes := environment.REFLEX_COMPILE_PROCESSES.get()) is not None ): executor = concurrent.futures.ProcessPoolExecutor( @@ -957,7 +957,7 @@ class App(MiddlewareMixin, LifespanMixin, Base): ) else: executor = concurrent.futures.ThreadPoolExecutor( - max_workers=environment.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 c34978026..9f81f319d 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -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 environment.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 01d0524eb..9487958c2 100644 --- a/reflex/components/core/upload.py +++ b/reflex/components/core/upload.py @@ -125,7 +125,7 @@ def get_upload_dir() -> Path: """ Upload.is_used = True - uploaded_files_dir = environment.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 53f5646ba..2fb2f7988 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -332,7 +332,6 @@ class EnvVar(Generic[T]): self.default = default self.type_ = type_ - @property def getenv(self) -> Optional[str]: """Get the environment variable from os.environ. @@ -341,14 +340,13 @@ class EnvVar(Generic[T]): """ return os.getenv(self.name, None) - @property def get(self) -> T: """Get the interpreted environment variable value. Returns: The interpreted value. """ - env_value = self.getenv + env_value = self.getenv() if env_value is not None: return interpret_env_var_value(env_value, self.type_, self.name) return self.default diff --git a/reflex/constants/base.py b/reflex/constants/base.py index 5319d872a..6ec73cdf0 100644 --- a/reflex/constants/base.py +++ b/reflex/constants/base.py @@ -112,7 +112,7 @@ class Templates(SimpleNamespace): from reflex.config import environment return ( - environment.REFLEX_BUILD_FRONTEND.get + environment.REFLEX_BUILD_FRONTEND.get() + "/gen?reflex_init_token={reflex_init_token}" ) @@ -126,7 +126,7 @@ class Templates(SimpleNamespace): """ from reflex.config import environment - return environment.REFLEX_BUILD_BACKEND.get + "/api/init/{reflex_init_token}" + return environment.REFLEX_BUILD_BACKEND.get() + "/api/init/{reflex_init_token}" @classproperty @classmethod @@ -139,7 +139,7 @@ class Templates(SimpleNamespace): from reflex.config import environment return ( - environment.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 9738ee52f..777eb23ba 100644 --- a/reflex/constants/installer.py +++ b/reflex/constants/installer.py @@ -63,7 +63,7 @@ class Bun(SimpleNamespace): """ from reflex.config import environment - return environment.REFLEX_DIR.get / "bun" + return environment.REFLEX_DIR.get() / "bun" @classproperty @classmethod @@ -100,7 +100,7 @@ class Fnm(SimpleNamespace): """ from reflex.config import environment - return environment.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 ddda3de56..7681caebc 100644 --- a/reflex/custom_components/custom_components.py +++ b/reflex/custom_components/custom_components.py @@ -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( - environment.TWINE_USERNAME, + 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( - environment.TWINE_PASSWORD, + 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 563eccfcb..4b070ec67 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -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 environment.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 = environment.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(environment.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(environment.ALEMBIC_CONFIG.get), - directory=str(environment.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 environment.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 environment.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 6a3e825ae..6ccba01d3 100644 --- a/reflex/reflex.py +++ b/reflex/reflex.py @@ -420,7 +420,7 @@ def db_init(): return # Check the alembic config. - if environment.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 2b9c86285..025eb7d8d 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -3353,7 +3353,7 @@ class StateManagerRedis(StateManager): ) except ResponseError: # Some redis servers only allow out-of-band configuration, so ignore errors here. - if not environment.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 3a88fb595..bb7ead2d9 100644 --- a/reflex/testing.py +++ b/reflex/testing.py @@ -617,10 +617,10 @@ class AppHarness: if self.frontend_url is None: raise RuntimeError("Frontend is not running.") want_headless = False - if environment.APP_HARNESS_HEADLESS.get: + if environment.APP_HARNESS_HEADLESS.get(): want_headless = True if driver_clz is None: - requested_driver = environment.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")() @@ -642,7 +642,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 := environment.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: diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index e7917aa46..fe4aeb741 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -184,7 +184,7 @@ def should_use_granian(): Returns: True if Granian should be used. """ - return environment.REFLEX_USE_GRANIAN.get + return environment.REFLEX_USE_GRANIAN.get() def get_app_module(): @@ -491,5 +491,5 @@ def is_prod_mode() -> bool: Returns: True if the app is running in production mode or False if running in dev mode. """ - current_mode = environment.REFLEX_ENV_MODE.get + current_mode = environment.REFLEX_ENV_MODE.get() return current_mode == constants.Env.PROD diff --git a/reflex/utils/net.py b/reflex/utils/net.py index c293e9fc3..acc202912 100644 --- a/reflex/utils/net.py +++ b/reflex/utils/net.py @@ -12,7 +12,7 @@ def _httpx_verify_kwarg() -> bool: Returns: True if SSL verification is enabled, False otherwise """ - return not environment.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 66968d0e1..a2ba2b151 100644 --- a/reflex/utils/path_ops.py +++ b/reflex/utils/path_ops.py @@ -136,7 +136,7 @@ def use_system_node() -> bool: Returns: Whether the system node should be used. """ - return environment.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 environment.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 a47505483..7569d591e 100644 --- a/reflex/utils/prerequisites.py +++ b/reflex/utils/prerequisites.py @@ -69,7 +69,7 @@ def get_web_dir() -> Path: Returns: The working directory. """ - return environment.REFLEX_WEB_WORKDIR.get + return environment.REFLEX_WEB_WORKDIR.get() def _python_version_check(): @@ -249,7 +249,7 @@ def windows_npm_escape_hatch() -> bool: Returns: If the user has set REFLEX_USE_NPM. """ - return environment.REFLEX_USE_NPM.get + return environment.REFLEX_USE_NPM.get() def get_app(reload: bool = False) -> ModuleType: @@ -991,7 +991,7 @@ def needs_reinit(frontend: bool = True) -> bool: return False # Make sure the .reflex directory exists. - if not environment.REFLEX_DIR.get.exists(): + if not environment.REFLEX_DIR.get().exists(): return True # Make sure the .web directory exists in frontend mode. @@ -1096,7 +1096,7 @@ def ensure_reflex_installation_id() -> Optional[int]: """ try: initialize_reflex_user_directory() - installation_id_file = environment.REFLEX_DIR.get / "installation_id" + installation_id_file = environment.REFLEX_DIR.get() / "installation_id" installation_id = None if installation_id_file.exists(): @@ -1121,7 +1121,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(environment.REFLEX_DIR.get) + path_ops.mkdir(environment.REFLEX_DIR.get()) def initialize_frontend_dependencies(): @@ -1144,7 +1144,10 @@ def check_db_initialized() -> bool: Returns: True if alembic is initialized (or if database is not used). """ - if get_config().db_url is not None and not environment.ALEMBIC_CONFIG.get.exists(): + if ( + get_config().db_url is not None + and not environment.ALEMBIC_CONFIG.get().exists() + ): console.error( "Database is not initialized. Run [bold]reflex db init[/bold] first." ) @@ -1154,7 +1157,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 environment.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 179e0be4c..d98178c61 100644 --- a/reflex/utils/registry.py +++ b/reflex/utils/registry.py @@ -55,4 +55,4 @@ def _get_npm_registry() -> str: Returns: str: """ - return environment.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 1d10d25e4..806b916fc 100644 --- a/reflex/utils/telemetry.py +++ b/reflex/utils/telemetry.py @@ -95,7 +95,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 environment.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 2d0febe00..f7b825f16 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -22,7 +22,7 @@ def xvfb(): Yields: the pyvirtualdisplay object that the browser will be open on """ - if os.environ.get("GITHUB_ACTIONS") and not environment.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, ) @@ -43,7 +43,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 = environment.SCREENSHOT_DIR.get + screenshot_dir = environment.SCREENSHOT_DIR.get() if DISPLAY is None or screenshot_dir is None: return diff --git a/tests/units/test_config.py b/tests/units/test_config.py index e420c73be..e5d4622bd 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -216,7 +216,7 @@ def test_replace_defaults( def reflex_dir_constant() -> Path: - return environment.REFLEX_DIR.get + return environment.REFLEX_DIR.get() def test_reflex_dir_env_var(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: @@ -253,30 +253,30 @@ def test_env_var(): INTERNAL: EnvVar[str] = env_var("default", internal=True) BOOLEAN: EnvVar[bool] = env_var(False) - assert TestEnv.BLUBB.get == "default" + assert TestEnv.BLUBB.get() == "default" assert TestEnv.BLUBB.name == "BLUBB" TestEnv.BLUBB.set("new") assert os.environ.get("BLUBB") == "new" - assert TestEnv.BLUBB.get == "new" + assert TestEnv.BLUBB.get() == "new" TestEnv.BLUBB.set(None) assert "BLUBB" not in os.environ - assert TestEnv.INTERNAL.get == "default" + assert TestEnv.INTERNAL.get() == "default" assert TestEnv.INTERNAL.name == "__INTERNAL" TestEnv.INTERNAL.set("new") assert os.environ.get("__INTERNAL") == "new" - assert TestEnv.INTERNAL.get == "new" - assert TestEnv.INTERNAL.getenv == "new" + assert TestEnv.INTERNAL.get() == "new" + assert TestEnv.INTERNAL.getenv() == "new" TestEnv.INTERNAL.set(None) assert "__INTERNAL" not in os.environ - assert TestEnv.BOOLEAN.get is False + assert TestEnv.BOOLEAN.get() is False assert TestEnv.BOOLEAN.name == "BOOLEAN" TestEnv.BOOLEAN.set(True) assert os.environ.get("BOOLEAN") == "True" - assert TestEnv.BOOLEAN.get is True + assert TestEnv.BOOLEAN.get() is True TestEnv.BOOLEAN.set(False) assert os.environ.get("BOOLEAN") == "False" - assert TestEnv.BOOLEAN.get is False + assert TestEnv.BOOLEAN.get() is False TestEnv.BOOLEAN.set(None) assert "BOOLEAN" not in os.environ