1
0

config.py 35 KB

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