refactor EnvVar.get to be a method

This commit is contained in:
Benedikt Bartscher 2024-10-31 21:07:13 +01:00
parent 9e7e1084e0
commit 9d44cd71a5
No known key found for this signature in database
19 changed files with 53 additions and 52 deletions

View File

@ -727,7 +727,7 @@ class App(MiddlewareMixin, LifespanMixin, Base):
Whether the app should be compiled. Whether the app should be compiled.
""" """
# Check the environment variable. # Check the environment variable.
if environment.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
@ -948,7 +948,7 @@ class App(MiddlewareMixin, LifespanMixin, Base):
executor = None executor = None
if ( if (
platform.system() in ("Linux", "Darwin") 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 is not None
): ):
executor = concurrent.futures.ProcessPoolExecutor( executor = concurrent.futures.ProcessPoolExecutor(
@ -957,7 +957,7 @@ class App(MiddlewareMixin, LifespanMixin, Base):
) )
else: else:
executor = concurrent.futures.ThreadPoolExecutor( 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): for route, component in zip(self.pages, page_components):

View File

@ -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 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. # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
return return

View File

@ -125,7 +125,7 @@ def get_upload_dir() -> Path:
""" """
Upload.is_used = True 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) uploaded_files_dir.mkdir(parents=True, exist_ok=True)
return uploaded_files_dir return uploaded_files_dir

View File

@ -332,7 +332,6 @@ class EnvVar(Generic[T]):
self.default = default self.default = default
self.type_ = type_ self.type_ = type_
@property
def getenv(self) -> Optional[str]: def getenv(self) -> Optional[str]:
"""Get the environment variable from os.environ. """Get the environment variable from os.environ.
@ -341,14 +340,13 @@ class EnvVar(Generic[T]):
""" """
return os.getenv(self.name, None) return os.getenv(self.name, None)
@property
def get(self) -> T: def get(self) -> T:
"""Get the interpreted environment variable value. """Get the interpreted environment variable value.
Returns: Returns:
The interpreted value. The interpreted value.
""" """
env_value = self.getenv env_value = self.getenv()
if env_value is not None: if env_value is not None:
return interpret_env_var_value(env_value, self.type_, self.name) return interpret_env_var_value(env_value, self.type_, self.name)
return self.default return self.default

View File

@ -112,7 +112,7 @@ class Templates(SimpleNamespace):
from reflex.config import environment from reflex.config import environment
return ( return (
environment.REFLEX_BUILD_FRONTEND.get environment.REFLEX_BUILD_FRONTEND.get()
+ "/gen?reflex_init_token={reflex_init_token}" + "/gen?reflex_init_token={reflex_init_token}"
) )
@ -126,7 +126,7 @@ class Templates(SimpleNamespace):
""" """
from reflex.config import environment 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 @classproperty
@classmethod @classmethod
@ -139,7 +139,7 @@ class Templates(SimpleNamespace):
from reflex.config import environment from reflex.config import environment
return ( return (
environment.REFLEX_BUILD_BACKEND.get environment.REFLEX_BUILD_BACKEND.get()
+ "/api/gen/{generation_hash}/refactored" + "/api/gen/{generation_hash}/refactored"
) )

View File

@ -63,7 +63,7 @@ class Bun(SimpleNamespace):
""" """
from reflex.config import environment from reflex.config import environment
return environment.REFLEX_DIR.get / "bun" return environment.REFLEX_DIR.get() / "bun"
@classproperty @classproperty
@classmethod @classmethod
@ -100,7 +100,7 @@ class Fnm(SimpleNamespace):
""" """
from reflex.config import environment from reflex.config import environment
return environment.REFLEX_DIR.get / "fnm" return environment.REFLEX_DIR.get() / "fnm"
@classproperty @classproperty
@classmethod @classmethod

View File

@ -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(
environment.TWINE_USERNAME, 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(
environment.TWINE_PASSWORD, 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",

View File

@ -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 environment.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 = environment.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(environment.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(environment.ALEMBIC_CONFIG.get), config=alembic.config.Config(environment.ALEMBIC_CONFIG.get()),
directory=str(environment.ALEMBIC_CONFIG.get.parent / "alembic"), 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 environment.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 environment.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:

View File

@ -420,7 +420,7 @@ def db_init():
return return
# Check the alembic config. # Check the alembic config.
if environment.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 "

View File

@ -3353,7 +3353,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 environment.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)

View File

@ -617,10 +617,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 environment.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 = environment.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")()
@ -642,7 +642,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 := environment.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:

View File

@ -184,7 +184,7 @@ def should_use_granian():
Returns: Returns:
True if Granian should be used. True if Granian should be used.
""" """
return environment.REFLEX_USE_GRANIAN.get return environment.REFLEX_USE_GRANIAN.get()
def get_app_module(): def get_app_module():
@ -491,5 +491,5 @@ 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 = environment.REFLEX_ENV_MODE.get current_mode = environment.REFLEX_ENV_MODE.get()
return current_mode == constants.Env.PROD return current_mode == constants.Env.PROD

View File

@ -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 environment.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:

View File

@ -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 environment.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 environment.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:

View File

@ -69,7 +69,7 @@ def get_web_dir() -> Path:
Returns: Returns:
The working directory. The working directory.
""" """
return environment.REFLEX_WEB_WORKDIR.get return environment.REFLEX_WEB_WORKDIR.get()
def _python_version_check(): def _python_version_check():
@ -249,7 +249,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 environment.REFLEX_USE_NPM.get return environment.REFLEX_USE_NPM.get()
def get_app(reload: bool = False) -> ModuleType: def get_app(reload: bool = False) -> ModuleType:
@ -991,7 +991,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 environment.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.
@ -1096,7 +1096,7 @@ def ensure_reflex_installation_id() -> Optional[int]:
""" """
try: try:
initialize_reflex_user_directory() 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 installation_id = None
if installation_id_file.exists(): if installation_id_file.exists():
@ -1121,7 +1121,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(environment.REFLEX_DIR.get) path_ops.mkdir(environment.REFLEX_DIR.get())
def initialize_frontend_dependencies(): def initialize_frontend_dependencies():
@ -1144,7 +1144,10 @@ def check_db_initialized() -> bool:
Returns: Returns:
True if alembic is initialized (or if database is not used). 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( console.error(
"Database is not initialized. Run [bold]reflex db init[/bold] first." "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(): 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 environment.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:

View File

@ -55,4 +55,4 @@ def _get_npm_registry() -> str:
Returns: Returns:
str: str:
""" """
return environment.NPM_CONFIG_REGISTRY.get or get_best_registry() return environment.NPM_CONFIG_REGISTRY.get() or get_best_registry()

View File

@ -95,7 +95,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 environment.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:

View File

@ -22,7 +22,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 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] from pyvirtualdisplay.smartdisplay import ( # pyright: ignore [reportMissingImports]
SmartDisplay, SmartDisplay,
) )
@ -43,7 +43,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 = environment.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

View File

@ -216,7 +216,7 @@ def test_replace_defaults(
def reflex_dir_constant() -> Path: 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: 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) INTERNAL: EnvVar[str] = env_var("default", internal=True)
BOOLEAN: EnvVar[bool] = env_var(False) BOOLEAN: EnvVar[bool] = env_var(False)
assert TestEnv.BLUBB.get == "default" assert TestEnv.BLUBB.get() == "default"
assert TestEnv.BLUBB.name == "BLUBB" assert TestEnv.BLUBB.name == "BLUBB"
TestEnv.BLUBB.set("new") TestEnv.BLUBB.set("new")
assert os.environ.get("BLUBB") == "new" assert os.environ.get("BLUBB") == "new"
assert TestEnv.BLUBB.get == "new" assert TestEnv.BLUBB.get() == "new"
TestEnv.BLUBB.set(None) TestEnv.BLUBB.set(None)
assert "BLUBB" not in os.environ assert "BLUBB" not in os.environ
assert TestEnv.INTERNAL.get == "default" assert TestEnv.INTERNAL.get() == "default"
assert TestEnv.INTERNAL.name == "__INTERNAL" assert TestEnv.INTERNAL.name == "__INTERNAL"
TestEnv.INTERNAL.set("new") TestEnv.INTERNAL.set("new")
assert os.environ.get("__INTERNAL") == "new" assert os.environ.get("__INTERNAL") == "new"
assert TestEnv.INTERNAL.get == "new" assert TestEnv.INTERNAL.get() == "new"
assert TestEnv.INTERNAL.getenv == "new" assert TestEnv.INTERNAL.getenv() == "new"
TestEnv.INTERNAL.set(None) TestEnv.INTERNAL.set(None)
assert "__INTERNAL" not in os.environ assert "__INTERNAL" not in os.environ
assert TestEnv.BOOLEAN.get is False assert TestEnv.BOOLEAN.get() is False
assert TestEnv.BOOLEAN.name == "BOOLEAN" assert TestEnv.BOOLEAN.name == "BOOLEAN"
TestEnv.BOOLEAN.set(True) TestEnv.BOOLEAN.set(True)
assert os.environ.get("BOOLEAN") == "True" assert os.environ.get("BOOLEAN") == "True"
assert TestEnv.BOOLEAN.get is True assert TestEnv.BOOLEAN.get() is True
TestEnv.BOOLEAN.set(False) TestEnv.BOOLEAN.set(False)
assert os.environ.get("BOOLEAN") == "False" assert os.environ.get("BOOLEAN") == "False"
assert TestEnv.BOOLEAN.get is False assert TestEnv.BOOLEAN.get() is False
TestEnv.BOOLEAN.set(None) TestEnv.BOOLEAN.set(None)
assert "BOOLEAN" not in os.environ assert "BOOLEAN" not in os.environ