config.py 29 KB

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