config.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. """The Reflex config."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import enum
  5. import importlib
  6. import inspect
  7. import os
  8. import sys
  9. import threading
  10. import urllib.parse
  11. from importlib.util import find_spec
  12. from pathlib import Path
  13. from types import ModuleType
  14. from typing import (
  15. TYPE_CHECKING,
  16. Any,
  17. Dict,
  18. Generic,
  19. List,
  20. Optional,
  21. Set,
  22. TypeVar,
  23. get_args,
  24. )
  25. from typing_extensions import Annotated, get_type_hints
  26. from reflex.utils.exceptions import ConfigError, EnvironmentVarValueError
  27. from reflex.utils.types import GenericType, is_union, value_inside_optional
  28. try:
  29. import pydantic.v1 as pydantic
  30. except ModuleNotFoundError:
  31. import pydantic
  32. from reflex_cli.constants.hosting import Hosting
  33. from reflex import constants
  34. from reflex.base import Base
  35. from reflex.utils import console
  36. class DBConfig(Base):
  37. """Database config."""
  38. engine: str
  39. username: Optional[str] = ""
  40. password: Optional[str] = ""
  41. host: Optional[str] = ""
  42. port: Optional[int] = None
  43. database: str
  44. @classmethod
  45. def postgresql(
  46. cls,
  47. database: str,
  48. username: str,
  49. password: str | None = None,
  50. host: str | None = None,
  51. port: int | None = 5432,
  52. ) -> DBConfig:
  53. """Create an instance with postgresql engine.
  54. Args:
  55. database: Database name.
  56. username: Database username.
  57. password: Database password.
  58. host: Database host.
  59. port: Database port.
  60. Returns:
  61. DBConfig instance.
  62. """
  63. return cls(
  64. engine="postgresql",
  65. username=username,
  66. password=password,
  67. host=host,
  68. port=port,
  69. database=database,
  70. )
  71. @classmethod
  72. def postgresql_psycopg(
  73. cls,
  74. database: str,
  75. username: str,
  76. password: str | None = None,
  77. host: str | None = None,
  78. port: int | None = 5432,
  79. ) -> DBConfig:
  80. """Create an instance with postgresql+psycopg engine.
  81. Args:
  82. database: Database name.
  83. username: Database username.
  84. password: Database password.
  85. host: Database host.
  86. port: Database port.
  87. Returns:
  88. DBConfig instance.
  89. """
  90. return cls(
  91. engine="postgresql+psycopg",
  92. username=username,
  93. password=password,
  94. host=host,
  95. port=port,
  96. database=database,
  97. )
  98. @classmethod
  99. def sqlite(
  100. cls,
  101. database: str,
  102. ) -> DBConfig:
  103. """Create an instance with sqlite engine.
  104. Args:
  105. database: Database name.
  106. Returns:
  107. DBConfig instance.
  108. """
  109. return cls(
  110. engine="sqlite",
  111. database=database,
  112. )
  113. def get_url(self) -> str:
  114. """Get database URL.
  115. Returns:
  116. The database URL.
  117. """
  118. host = (
  119. f"{self.host}:{self.port}" if self.host and self.port else self.host or ""
  120. )
  121. username = urllib.parse.quote_plus(self.username) if self.username else ""
  122. password = urllib.parse.quote_plus(self.password) if self.password else ""
  123. if username:
  124. path = f"{username}:{password}@{host}" if password else f"{username}@{host}"
  125. else:
  126. path = f"{host}"
  127. return f"{self.engine}://{path}/{self.database}"
  128. def get_default_value_for_field(field: dataclasses.Field) -> Any:
  129. """Get the default value for a field.
  130. Args:
  131. field: The field.
  132. Returns:
  133. The default value.
  134. Raises:
  135. ValueError: If no default value is found.
  136. """
  137. if field.default != dataclasses.MISSING:
  138. return field.default
  139. elif field.default_factory != dataclasses.MISSING:
  140. return field.default_factory()
  141. else:
  142. raise ValueError(
  143. f"Missing value for environment variable {field.name} and no default value found"
  144. )
  145. # TODO: Change all interpret_.* signatures to value: str, field: dataclasses.Field once we migrate rx.Config to dataclasses
  146. def interpret_boolean_env(value: str, field_name: str) -> bool:
  147. """Interpret a boolean environment variable value.
  148. Args:
  149. value: The environment variable value.
  150. field_name: The field name.
  151. Returns:
  152. The interpreted value.
  153. Raises:
  154. EnvironmentVarValueError: If the value is invalid.
  155. """
  156. true_values = ["true", "1", "yes", "y"]
  157. false_values = ["false", "0", "no", "n"]
  158. if value.lower() in true_values:
  159. return True
  160. elif value.lower() in false_values:
  161. return False
  162. raise EnvironmentVarValueError(f"Invalid boolean value: {value} for {field_name}")
  163. def interpret_int_env(value: str, field_name: str) -> int:
  164. """Interpret an integer environment variable value.
  165. Args:
  166. value: The environment variable value.
  167. field_name: The field name.
  168. Returns:
  169. The interpreted value.
  170. Raises:
  171. EnvironmentVarValueError: If the value is invalid.
  172. """
  173. try:
  174. return int(value)
  175. except ValueError as ve:
  176. raise EnvironmentVarValueError(
  177. f"Invalid integer value: {value} for {field_name}"
  178. ) from ve
  179. def interpret_existing_path_env(value: str, field_name: str) -> ExistingPath:
  180. """Interpret a path environment variable value as an existing path.
  181. Args:
  182. value: The environment variable value.
  183. field_name: The field name.
  184. Returns:
  185. The interpreted value.
  186. Raises:
  187. EnvironmentVarValueError: If the path does not exist.
  188. """
  189. path = Path(value)
  190. if not path.exists():
  191. raise EnvironmentVarValueError(f"Path does not exist: {path} for {field_name}")
  192. return path
  193. def interpret_path_env(value: str, field_name: str) -> Path:
  194. """Interpret a path environment variable value.
  195. Args:
  196. value: The environment variable value.
  197. field_name: The field name.
  198. Returns:
  199. The interpreted value.
  200. """
  201. return Path(value)
  202. def interpret_enum_env(value: str, field_type: GenericType, field_name: str) -> Any:
  203. """Interpret an enum environment variable value.
  204. Args:
  205. value: The environment variable value.
  206. field_type: The field type.
  207. field_name: The field name.
  208. Returns:
  209. The interpreted value.
  210. Raises:
  211. EnvironmentVarValueError: If the value is invalid.
  212. """
  213. try:
  214. return field_type(value)
  215. except ValueError as ve:
  216. raise EnvironmentVarValueError(
  217. f"Invalid enum value: {value} for {field_name}"
  218. ) from ve
  219. def interpret_env_var_value(
  220. value: str, field_type: GenericType, field_name: str
  221. ) -> Any:
  222. """Interpret an environment variable value based on the field type.
  223. Args:
  224. value: The environment variable value.
  225. field_type: The field type.
  226. field_name: The field name.
  227. Returns:
  228. The interpreted value.
  229. Raises:
  230. ValueError: If the value is invalid.
  231. """
  232. field_type = value_inside_optional(field_type)
  233. if is_union(field_type):
  234. raise ValueError(
  235. f"Union types are not supported for environment variables: {field_name}."
  236. )
  237. if field_type is bool:
  238. return interpret_boolean_env(value, field_name)
  239. elif field_type is str:
  240. return value
  241. elif field_type is int:
  242. return interpret_int_env(value, field_name)
  243. elif field_type is Path:
  244. return interpret_path_env(value, field_name)
  245. elif field_type is ExistingPath:
  246. return interpret_existing_path_env(value, field_name)
  247. elif inspect.isclass(field_type) and issubclass(field_type, enum.Enum):
  248. return interpret_enum_env(value, field_type, field_name)
  249. else:
  250. raise ValueError(
  251. f"Invalid type for environment variable {field_name}: {field_type}. This is probably an issue in Reflex."
  252. )
  253. T = TypeVar("T")
  254. class EnvVar(Generic[T]):
  255. """Environment variable."""
  256. name: str
  257. default: Any
  258. type_: T
  259. def __init__(self, name: str, default: Any, type_: T) -> None:
  260. """Initialize the environment variable.
  261. Args:
  262. name: The environment variable name.
  263. default: The default value.
  264. type_: The type of the value.
  265. """
  266. self.name = name
  267. self.default = default
  268. self.type_ = type_
  269. def interpret(self, value: str) -> T:
  270. """Interpret the environment variable value.
  271. Args:
  272. value: The environment variable value.
  273. Returns:
  274. The interpreted value.
  275. """
  276. return interpret_env_var_value(value, self.type_, self.name)
  277. def getenv(self) -> Optional[T]:
  278. """Get the interpreted environment variable value.
  279. Returns:
  280. The environment variable value.
  281. """
  282. env_value = os.getenv(self.name, None)
  283. if env_value is not None:
  284. return self.interpret(env_value)
  285. return None
  286. def is_set(self) -> bool:
  287. """Check if the environment variable is set.
  288. Returns:
  289. True if the environment variable is set.
  290. """
  291. return self.name in os.environ
  292. def get(self) -> T:
  293. """Get the interpreted environment variable value or the default value if not set.
  294. Returns:
  295. The interpreted value.
  296. """
  297. env_value = self.getenv()
  298. if env_value is not None:
  299. return env_value
  300. return self.default
  301. def set(self, value: T | None) -> None:
  302. """Set the environment variable. None unsets the variable.
  303. Args:
  304. value: The value to set.
  305. """
  306. if value is None:
  307. _ = os.environ.pop(self.name, None)
  308. else:
  309. if isinstance(value, enum.Enum):
  310. value = value.value
  311. os.environ[self.name] = str(value)
  312. class env_var: # type: ignore # noqa: N801
  313. """Descriptor for environment variables."""
  314. name: str
  315. default: Any
  316. internal: bool = False
  317. def __init__(self, default: Any, internal: bool = False) -> None:
  318. """Initialize the descriptor.
  319. Args:
  320. default: The default value.
  321. internal: Whether the environment variable is reflex internal.
  322. """
  323. self.default = default
  324. self.internal = internal
  325. def __set_name__(self, owner, name):
  326. """Set the name of the descriptor.
  327. Args:
  328. owner: The owner class.
  329. name: The name of the descriptor.
  330. """
  331. self.name = name
  332. def __get__(self, instance, owner):
  333. """Get the EnvVar instance.
  334. Args:
  335. instance: The instance.
  336. owner: The owner class.
  337. Returns:
  338. The EnvVar instance.
  339. """
  340. type_ = get_args(get_type_hints(owner)[self.name])[0]
  341. env_name = self.name
  342. if self.internal:
  343. env_name = f"__{env_name}"
  344. return EnvVar(name=env_name, default=self.default, type_=type_)
  345. if TYPE_CHECKING:
  346. def env_var(default, internal=False) -> EnvVar:
  347. """Typing helper for the env_var descriptor.
  348. Args:
  349. default: The default value.
  350. internal: Whether the environment variable is reflex internal.
  351. Returns:
  352. The EnvVar instance.
  353. """
  354. return default
  355. class PathExistsFlag:
  356. """Flag to indicate that a path must exist."""
  357. ExistingPath = Annotated[Path, PathExistsFlag]
  358. class PerformanceMode(enum.Enum):
  359. """Performance mode for the app."""
  360. WARN = "warn"
  361. RAISE = "raise"
  362. OFF = "off"
  363. class EnvironmentVariables:
  364. """Environment variables class to instantiate environment variables."""
  365. # Whether to use npm over bun to install frontend packages.
  366. REFLEX_USE_NPM: EnvVar[bool] = env_var(False)
  367. # The npm registry to use.
  368. NPM_CONFIG_REGISTRY: EnvVar[Optional[str]] = env_var(None)
  369. # Whether to use Granian for the backend. Otherwise, use Uvicorn.
  370. REFLEX_USE_GRANIAN: EnvVar[bool] = env_var(False)
  371. # The username to use for authentication on python package repository. Username and password must both be provided.
  372. TWINE_USERNAME: EnvVar[Optional[str]] = env_var(None)
  373. # The password to use for authentication on python package repository. Username and password must both be provided.
  374. TWINE_PASSWORD: EnvVar[Optional[str]] = env_var(None)
  375. # Whether to use the system installed bun. If set to false, bun will be bundled with the app.
  376. REFLEX_USE_SYSTEM_BUN: EnvVar[bool] = env_var(False)
  377. # Whether to use the system installed node and npm. If set to false, node and npm will be bundled with the app.
  378. REFLEX_USE_SYSTEM_NODE: EnvVar[bool] = env_var(False)
  379. # The working directory for the next.js commands.
  380. REFLEX_WEB_WORKDIR: EnvVar[Path] = env_var(Path(constants.Dirs.WEB))
  381. # Path to the alembic config file
  382. ALEMBIC_CONFIG: EnvVar[ExistingPath] = env_var(Path(constants.ALEMBIC_CONFIG))
  383. # Disable SSL verification for HTTPX requests.
  384. SSL_NO_VERIFY: EnvVar[bool] = env_var(False)
  385. # The directory to store uploaded files.
  386. REFLEX_UPLOADED_FILES_DIR: EnvVar[Path] = env_var(
  387. Path(constants.Dirs.UPLOADED_FILES)
  388. )
  389. # Whether to use separate processes to compile the frontend and how many. If not set, defaults to thread executor.
  390. REFLEX_COMPILE_PROCESSES: EnvVar[Optional[int]] = env_var(None)
  391. # Whether to use separate threads to compile the frontend and how many. Defaults to `min(32, os.cpu_count() + 4)`.
  392. REFLEX_COMPILE_THREADS: EnvVar[Optional[int]] = env_var(None)
  393. # The directory to store reflex dependencies.
  394. REFLEX_DIR: EnvVar[Path] = env_var(Path(constants.Reflex.DIR))
  395. # Whether to print the SQL queries if the log level is INFO or lower.
  396. SQLALCHEMY_ECHO: EnvVar[bool] = env_var(False)
  397. # Whether to check db connections before using them.
  398. SQLALCHEMY_POOL_PRE_PING: EnvVar[bool] = env_var(True)
  399. # Whether to ignore the redis config error. Some redis servers only allow out-of-band configuration.
  400. REFLEX_IGNORE_REDIS_CONFIG_ERROR: EnvVar[bool] = env_var(False)
  401. # Whether to skip purging the web directory in dev mode.
  402. REFLEX_PERSIST_WEB_DIR: EnvVar[bool] = env_var(False)
  403. # The reflex.build frontend host.
  404. REFLEX_BUILD_FRONTEND: EnvVar[str] = env_var(
  405. constants.Templates.REFLEX_BUILD_FRONTEND
  406. )
  407. # The reflex.build backend host.
  408. REFLEX_BUILD_BACKEND: EnvVar[str] = env_var(
  409. constants.Templates.REFLEX_BUILD_BACKEND
  410. )
  411. # This env var stores the execution mode of the app
  412. REFLEX_ENV_MODE: EnvVar[constants.Env] = env_var(constants.Env.DEV)
  413. # Whether to run the backend only. Exclusive with REFLEX_FRONTEND_ONLY.
  414. REFLEX_BACKEND_ONLY: EnvVar[bool] = env_var(False)
  415. # Whether to run the frontend only. Exclusive with REFLEX_BACKEND_ONLY.
  416. REFLEX_FRONTEND_ONLY: EnvVar[bool] = env_var(False)
  417. # Reflex internal env to reload the config.
  418. RELOAD_CONFIG: EnvVar[bool] = env_var(False, internal=True)
  419. # If this env var is set to "yes", App.compile will be a no-op
  420. REFLEX_SKIP_COMPILE: EnvVar[bool] = env_var(False, internal=True)
  421. # Whether to run app harness tests in headless mode.
  422. APP_HARNESS_HEADLESS: EnvVar[bool] = env_var(False)
  423. # Which app harness driver to use.
  424. APP_HARNESS_DRIVER: EnvVar[str] = env_var("Chrome")
  425. # Arguments to pass to the app harness driver.
  426. APP_HARNESS_DRIVER_ARGS: EnvVar[str] = env_var("")
  427. # Whether to check for outdated package versions.
  428. REFLEX_CHECK_LATEST_VERSION: EnvVar[bool] = env_var(True)
  429. # In which performance mode to run the app.
  430. REFLEX_PERF_MODE: EnvVar[Optional[PerformanceMode]] = env_var(PerformanceMode.WARN)
  431. # The maximum size of the reflex state in kilobytes.
  432. REFLEX_STATE_SIZE_LIMIT: EnvVar[int] = env_var(1000)
  433. # Whether to use the turbopack bundler.
  434. REFLEX_USE_TURBOPACK: EnvVar[bool] = env_var(True)
  435. environment = EnvironmentVariables()
  436. # These vars are not logged because they may contain sensitive information.
  437. _sensitive_env_vars = {"DB_URL", "ASYNC_DB_URL", "REDIS_URL"}
  438. class Config(Base):
  439. """The config defines runtime settings for the app.
  440. By default, the config is defined in an `rxconfig.py` file in the root of the app.
  441. ```python
  442. # rxconfig.py
  443. import reflex as rx
  444. config = rx.Config(
  445. app_name="myapp",
  446. api_url="http://localhost:8000",
  447. )
  448. ```
  449. Every config value can be overridden by an environment variable with the same name in uppercase.
  450. For example, `db_url` can be overridden by setting the `DB_URL` environment variable.
  451. See the [configuration](https://reflex.dev/docs/getting-started/configuration/) docs for more info.
  452. """
  453. class Config:
  454. """Pydantic config for the config."""
  455. validate_assignment = True
  456. # The name of the app (should match the name of the app directory).
  457. app_name: str
  458. # The path to the app module.
  459. app_module_import: Optional[str] = None
  460. # The log level to use.
  461. loglevel: constants.LogLevel = constants.LogLevel.DEFAULT
  462. # The port to run the frontend on. NOTE: When running in dev mode, the next available port will be used if this is taken.
  463. frontend_port: int = constants.DefaultPorts.FRONTEND_PORT
  464. # The path to run the frontend on. For example, "/app" will run the frontend on http://localhost:3000/app
  465. frontend_path: str = ""
  466. # The port to run the backend on. NOTE: When running in dev mode, the next available port will be used if this is taken.
  467. backend_port: int = constants.DefaultPorts.BACKEND_PORT
  468. # The backend url the frontend will connect to. This must be updated if the backend is hosted elsewhere, or in production.
  469. api_url: str = f"http://localhost:{backend_port}"
  470. # The url the frontend will be hosted on.
  471. deploy_url: Optional[str] = f"http://localhost:{frontend_port}"
  472. # The url the backend will be hosted on.
  473. backend_host: str = "0.0.0.0"
  474. # The database url used by rx.Model.
  475. db_url: Optional[str] = "sqlite:///reflex.db"
  476. # The async database url used by rx.Model.
  477. async_db_url: Optional[str] = None
  478. # The redis url
  479. redis_url: Optional[str] = None
  480. # Telemetry opt-in.
  481. telemetry_enabled: bool = True
  482. # The bun path
  483. bun_path: ExistingPath = constants.Bun.DEFAULT_PATH
  484. # Timeout to do a production build of a frontend page.
  485. static_page_generation_timeout: int = 60
  486. # List of origins that are allowed to connect to the backend API.
  487. cors_allowed_origins: List[str] = ["*"]
  488. # Tailwind config.
  489. tailwind: Optional[Dict[str, Any]] = {"plugins": ["@tailwindcss/typography"]}
  490. # Timeout when launching the gunicorn server. TODO(rename this to backend_timeout?)
  491. timeout: int = 120
  492. # Whether to enable or disable nextJS gzip compression.
  493. next_compression: bool = True
  494. # Whether to use React strict mode in nextJS
  495. react_strict_mode: bool = True
  496. # Additional frontend packages to install.
  497. frontend_packages: List[str] = []
  498. # The hosting service backend URL.
  499. cp_backend_url: str = Hosting.HOSTING_SERVICE
  500. # The hosting service frontend URL.
  501. cp_web_url: str = Hosting.HOSTING_SERVICE_UI
  502. # The worker class used in production mode
  503. gunicorn_worker_class: str = "uvicorn.workers.UvicornH11Worker"
  504. # Number of gunicorn workers from user
  505. gunicorn_workers: Optional[int] = None
  506. # Number of requests before a worker is restarted
  507. gunicorn_max_requests: int = 100
  508. # Variance limit for max requests; gunicorn only
  509. gunicorn_max_requests_jitter: int = 25
  510. # Indicate which type of state manager to use
  511. state_manager_mode: constants.StateManagerMode = constants.StateManagerMode.DISK
  512. # Maximum expiration lock time for redis state manager
  513. redis_lock_expiration: int = constants.Expiration.LOCK
  514. # Maximum lock time before warning for redis state manager.
  515. redis_lock_warning_threshold: int = constants.Expiration.LOCK_WARNING_THRESHOLD
  516. # Token expiration time for redis state manager
  517. redis_token_expiration: int = constants.Expiration.TOKEN
  518. # Attributes that were explicitly set by the user.
  519. _non_default_attributes: Set[str] = pydantic.PrivateAttr(set())
  520. # Path to file containing key-values pairs to override in the environment; Dotenv format.
  521. env_file: Optional[str] = None
  522. def __init__(self, *args, **kwargs):
  523. """Initialize the config values.
  524. Args:
  525. *args: The args to pass to the Pydantic init method.
  526. **kwargs: The kwargs to pass to the Pydantic init method.
  527. Raises:
  528. ConfigError: If some values in the config are invalid.
  529. """
  530. super().__init__(*args, **kwargs)
  531. # Update the config from environment variables.
  532. env_kwargs = self.update_from_env()
  533. for key, env_value in env_kwargs.items():
  534. setattr(self, key, env_value)
  535. # Update default URLs if ports were set
  536. kwargs.update(env_kwargs)
  537. self._non_default_attributes.update(kwargs)
  538. self._replace_defaults(**kwargs)
  539. if (
  540. self.state_manager_mode == constants.StateManagerMode.REDIS
  541. and not self.redis_url
  542. ):
  543. raise ConfigError(
  544. "REDIS_URL is required when using the redis state manager."
  545. )
  546. @property
  547. def app_module(self) -> ModuleType | None:
  548. """Return the app module if `app_module_import` is set.
  549. Returns:
  550. The app module.
  551. """
  552. return (
  553. importlib.import_module(self.app_module_import)
  554. if self.app_module_import
  555. else None
  556. )
  557. @property
  558. def module(self) -> str:
  559. """Get the module name of the app.
  560. Returns:
  561. The module name.
  562. """
  563. if self.app_module is not None:
  564. return self.app_module.__name__
  565. return ".".join([self.app_name, self.app_name])
  566. def update_from_env(self) -> dict[str, Any]:
  567. """Update the config values based on set environment variables.
  568. If there is a set env_file, it is loaded first.
  569. Returns:
  570. The updated config values.
  571. """
  572. if self.env_file:
  573. try:
  574. from dotenv import load_dotenv # type: ignore
  575. # load env file if exists
  576. load_dotenv(self.env_file, override=True)
  577. except ImportError:
  578. console.error(
  579. """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`."""
  580. )
  581. updated_values = {}
  582. # Iterate over the fields.
  583. for key, field in self.__fields__.items():
  584. # The env var name is the key in uppercase.
  585. env_var = os.environ.get(key.upper())
  586. # If the env var is set, override the config value.
  587. if env_var is not None:
  588. # Interpret the value.
  589. value = interpret_env_var_value(env_var, field.outer_type_, field.name)
  590. # Set the value.
  591. updated_values[key] = value
  592. if key.upper() in _sensitive_env_vars:
  593. env_var = "***"
  594. console.info(
  595. f"Overriding config value {key} with env var {key.upper()}={env_var}",
  596. dedupe=True,
  597. )
  598. return updated_values
  599. def get_event_namespace(self) -> str:
  600. """Get the path that the backend Websocket server lists on.
  601. Returns:
  602. The namespace for websocket.
  603. """
  604. event_url = constants.Endpoint.EVENT.get_url()
  605. return urllib.parse.urlsplit(event_url).path
  606. def _replace_defaults(self, **kwargs):
  607. """Replace formatted defaults when the caller provides updates.
  608. Args:
  609. **kwargs: The kwargs passed to the config or from the env.
  610. """
  611. if "api_url" not in self._non_default_attributes and "backend_port" in kwargs:
  612. self.api_url = f"http://localhost:{kwargs['backend_port']}"
  613. if (
  614. "deploy_url" not in self._non_default_attributes
  615. and "frontend_port" in kwargs
  616. ):
  617. self.deploy_url = f"http://localhost:{kwargs['frontend_port']}"
  618. if "api_url" not in self._non_default_attributes:
  619. # If running in Github Codespaces, override API_URL
  620. codespace_name = os.getenv("CODESPACE_NAME")
  621. github_codespaces_port_forwarding_domain = os.getenv(
  622. "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
  623. )
  624. # If running on Replit.com interactively, override API_URL to ensure we maintain the backend_port
  625. replit_dev_domain = os.getenv("REPLIT_DEV_DOMAIN")
  626. backend_port = kwargs.get("backend_port", self.backend_port)
  627. if codespace_name and github_codespaces_port_forwarding_domain:
  628. self.api_url = (
  629. f"https://{codespace_name}-{kwargs.get('backend_port', self.backend_port)}"
  630. f".{github_codespaces_port_forwarding_domain}"
  631. )
  632. elif replit_dev_domain and backend_port:
  633. self.api_url = f"https://{replit_dev_domain}:{backend_port}"
  634. def _set_persistent(self, **kwargs):
  635. """Set values in this config and in the environment so they persist into subprocess.
  636. Args:
  637. **kwargs: The kwargs passed to the config.
  638. """
  639. for key, value in kwargs.items():
  640. if value is not None:
  641. os.environ[key.upper()] = str(value)
  642. setattr(self, key, value)
  643. self._non_default_attributes.update(kwargs)
  644. self._replace_defaults(**kwargs)
  645. def _get_config() -> Config:
  646. """Get the app config.
  647. Returns:
  648. The app config.
  649. """
  650. # only import the module if it exists. If a module spec exists then
  651. # the module exists.
  652. spec = find_spec(constants.Config.MODULE)
  653. if not spec:
  654. # we need this condition to ensure that a ModuleNotFound error is not thrown when
  655. # running unit/integration tests or during `reflex init`.
  656. return Config(app_name="")
  657. rxconfig = importlib.import_module(constants.Config.MODULE)
  658. return rxconfig.config
  659. # Protect sys.path from concurrent modification
  660. _config_lock = threading.RLock()
  661. def get_config(reload: bool = False) -> Config:
  662. """Get the app config.
  663. Args:
  664. reload: Re-import the rxconfig module from disk
  665. Returns:
  666. The app config.
  667. """
  668. cached_rxconfig = sys.modules.get(constants.Config.MODULE, None)
  669. if cached_rxconfig is not None:
  670. if reload:
  671. # Remove any cached module when `reload` is requested.
  672. del sys.modules[constants.Config.MODULE]
  673. else:
  674. return cached_rxconfig.config
  675. with _config_lock:
  676. orig_sys_path = sys.path.copy()
  677. sys.path.clear()
  678. sys.path.append(str(Path.cwd()))
  679. try:
  680. # Try to import the module with only the current directory in the path.
  681. return _get_config()
  682. except Exception:
  683. # If the module import fails, try to import with the original sys.path.
  684. sys.path.extend(orig_sys_path)
  685. return _get_config()
  686. finally:
  687. # Find any entries added to sys.path by rxconfig.py itself.
  688. extra_paths = [
  689. p for p in sys.path if p not in orig_sys_path and p != str(Path.cwd())
  690. ]
  691. # Restore the original sys.path.
  692. sys.path.clear()
  693. sys.path.extend(extra_paths)
  694. sys.path.extend(orig_sys_path)