config.py 26 KB

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