config.py 34 KB

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