From 71033413a1f84141d1396019f5384208b9011c42 Mon Sep 17 00:00:00 2001 From: Khaleel Al-Adhami Date: Wed, 16 Oct 2024 18:53:01 -0700 Subject: [PATCH] put things somewhere else --- reflex/compiler/compiler.py | 5 ++- reflex/config.py | 15 +++++++++ reflex/constants/base.py | 59 +++++++++++++++++++++++++---------- reflex/constants/installer.py | 30 +----------------- reflex/constants/utils.py | 32 +++++++++++++++++++ reflex/model.py | 3 +- reflex/state.py | 8 ++--- 7 files changed, 95 insertions(+), 57 deletions(-) create mode 100644 reflex/constants/utils.py diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 0c29f941d..909299635 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -2,7 +2,6 @@ from __future__ import annotations -import os from datetime import datetime from pathlib import Path from typing import Dict, Iterable, Optional, Type, Union @@ -16,7 +15,7 @@ from reflex.components.component import ( CustomComponent, StatefulComponent, ) -from reflex.config import 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 +526,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 os.environ.get("REFLEX_PERSIST_WEB_DIR"): + if not is_prod_mode() and environment.REFLEX_PERSIST_WEB_DIR: # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set. return diff --git a/reflex/config.py b/reflex/config.py index a16418fef..c3ee3f9a1 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -286,6 +286,21 @@ class EnvironmentVariables: # The directory to store reflex dependencies. REFLEX_DIR: Path = Path(constants.Reflex.DIR) + # Whether to print the SQL queries if the log level is INFO or lower. + SQLALCHEMY_ECHO: bool = False + + # Whether to ignore the redis config error. Some redis servers only allow out-of-band configuration. + REFLEX_IGNORE_REDIS_CONFIG_ERROR: bool = False + + # Whether to skip purging the web directory in dev mode. + REFLEX_PERSIST_WEB_DIR: bool = False + + # The reflex.build frontend host. + REFLEX_BUILD_FRONTEND: str = constants.Templates.REFLEX_BUILD_FRONTEND + + # The reflex.build backend host. + REFLEX_BUILD_BACKEND: str = constants.Templates.REFLEX_BUILD_BACKEND + def __init__(self): """Initialize the environment variables.""" type_hints = get_type_hints(type(self)) diff --git a/reflex/constants/base.py b/reflex/constants/base.py index 63edbfbe9..789d31cd4 100644 --- a/reflex/constants/base.py +++ b/reflex/constants/base.py @@ -2,7 +2,6 @@ from __future__ import annotations -import os import platform from enum import Enum from importlib import metadata @@ -11,6 +10,8 @@ from types import SimpleNamespace from platformdirs import PlatformDirs +from .utils import classproperty + IS_WINDOWS = platform.system() == "Windows" @@ -95,27 +96,51 @@ class Templates(SimpleNamespace): DEFAULT = "blank" # The reflex.build frontend host - REFLEX_BUILD_FRONTEND = os.environ.get( - "REFLEX_BUILD_FRONTEND", "https://flexgen.reflex.run" - ) + REFLEX_BUILD_FRONTEND = "https://flexgen.reflex.run" # The reflex.build backend host - REFLEX_BUILD_BACKEND = os.environ.get( - "REFLEX_BUILD_BACKEND", "https://flexgen-prod-flexgen.fly.dev" - ) + REFLEX_BUILD_BACKEND = "https://flexgen-prod-flexgen.fly.dev" - # The URL to redirect to reflex.build - REFLEX_BUILD_URL = ( - REFLEX_BUILD_FRONTEND + "/gen?reflex_init_token={reflex_init_token}" - ) + @classproperty + @classmethod + def REFLEX_BUILD_URL(cls): + """The URL to redirect to reflex.build. - # The URL to poll waiting for the user to select a generation. - REFLEX_BUILD_POLL_URL = REFLEX_BUILD_BACKEND + "/api/init/{reflex_init_token}" + Returns: + The URL to redirect to reflex.build. + """ + from reflex.config import environment - # The URL to fetch the generation's reflex code - REFLEX_BUILD_CODE_URL = ( - REFLEX_BUILD_BACKEND + "/api/gen/{generation_hash}/refactored" - ) + return ( + environment.REFLEX_BUILD_FRONTEND + + "/gen?reflex_init_token={reflex_init_token}" + ) + + @classproperty + @classmethod + def REFLEX_BUILD_POLL_URL(cls): + """The URL to poll waiting for the user to select a generation. + + Returns: + The URL to poll waiting for the user to select a generation. + """ + from reflex.config import environment + + return environment.REFLEX_BUILD_BACKEND + "/api/init/{reflex_init_token}" + + @classproperty + @classmethod + def REFLEX_BUILD_CODE_URL(cls): + """The URL to fetch the generation's reflex code. + + Returns: + The URL to fetch the generation's reflex code. + """ + from reflex.config import environment + + return ( + environment.REFLEX_BUILD_BACKEND + "/api/gen/{generation_hash}/refactored" + ) class Dirs(SimpleNamespace): """Folders used by the template system of Reflex.""" diff --git a/reflex/constants/installer.py b/reflex/constants/installer.py index a30808b9f..a6756cbd4 100644 --- a/reflex/constants/installer.py +++ b/reflex/constants/installer.py @@ -5,9 +5,9 @@ from __future__ import annotations import platform from pathlib import Path from types import SimpleNamespace -from typing import Any, Callable, Generic, Type, TypeVar from .base import IS_WINDOWS +from .utils import classproperty def get_fnm_name() -> str | None: @@ -32,34 +32,6 @@ def get_fnm_name() -> str | None: return None -T = TypeVar("T") -V = TypeVar("V") - - -class classproperty(Generic[T, V]): - """A class property decorator.""" - - def __init__(self, getter: Callable[[Type[T]], V]) -> None: - """Initialize the class property. - - Args: - getter: The getter function. - """ - self.getter = getattr(getter, "__func__", getter) - - def __get__(self, instance: Any, owner: Type[T]) -> V: - """Get the value of the class property. - - Args: - instance: The instance of the class. - owner: The class itself. - - Returns: - The value of the class property. - """ - return self.getter(owner) - - # Bun config. class Bun(SimpleNamespace): """Bun constants.""" diff --git a/reflex/constants/utils.py b/reflex/constants/utils.py new file mode 100644 index 000000000..48797afbf --- /dev/null +++ b/reflex/constants/utils.py @@ -0,0 +1,32 @@ +"""Utility functions for constants.""" + +from typing import Any, Callable, Generic, Type + +from typing_extensions import TypeVar + +T = TypeVar("T") +V = TypeVar("V") + + +class classproperty(Generic[T, V]): + """A class property decorator.""" + + def __init__(self, getter: Callable[[Type[T]], V]) -> None: + """Initialize the class property. + + Args: + getter: The getter function. + """ + self.getter = getattr(getter, "__func__", getter) + + def __get__(self, instance: Any, owner: Type[T]) -> V: + """Get the value of the class property. + + Args: + instance: The instance of the class. + owner: The class itself. + + Returns: + The value of the class property. + """ + return self.getter(owner) diff --git a/reflex/model.py b/reflex/model.py index d1fc91587..b269044c5 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -2,7 +2,6 @@ from __future__ import annotations -import os from collections import defaultdict from typing import Any, ClassVar, Optional, Type, Union @@ -44,7 +43,7 @@ def get_engine(url: str | None = None) -> sqlalchemy.engine.Engine: "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 = os.environ.get("SQLALCHEMY_ECHO") == "True" + echo_db_query = environment.SQLALCHEMY_ECHO # 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) diff --git a/reflex/state.py b/reflex/state.py index 0d6eed0ed..0f8df189e 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -8,7 +8,6 @@ import copy import dataclasses import functools import inspect -import os import pickle import sys import uuid @@ -64,6 +63,7 @@ from redis.exceptions import ResponseError import reflex.istate.dynamic from reflex import constants from reflex.base import Base +from reflex.config import environment from reflex.event import ( BACKGROUND_TASK_MARKER, Event, @@ -3272,11 +3272,7 @@ class StateManagerRedis(StateManager): ) except ResponseError: # Some redis servers only allow out-of-band configuration, so ignore errors here. - ignore_config_error = os.environ.get( - "REFLEX_IGNORE_REDIS_CONFIG_ERROR", - None, - ) - if not ignore_config_error: + if not environment.REFLEX_IGNORE_REDIS_CONFIG_ERROR: raise async with self.redis.pubsub() as pubsub: await pubsub.psubscribe(lock_key_channel)