config.py 33 KB

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