config.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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. # Indicate the current command that was invoked in the reflex CLI.
  474. REFLEX_COMPILE_CONTEXT: EnvVar[constants.CompileContext] = env_var(
  475. constants.CompileContext.UNDEFINED, internal=True
  476. )
  477. # Whether to use npm over bun to install frontend packages.
  478. REFLEX_USE_NPM: EnvVar[bool] = env_var(False)
  479. # The npm registry to use.
  480. NPM_CONFIG_REGISTRY: EnvVar[Optional[str]] = env_var(None)
  481. # Whether to use Granian for the backend. Otherwise, use Uvicorn.
  482. REFLEX_USE_GRANIAN: EnvVar[bool] = env_var(False)
  483. # The username to use for authentication on python package repository. Username and password must both be provided.
  484. TWINE_USERNAME: EnvVar[Optional[str]] = env_var(None)
  485. # The password to use for authentication on python package repository. Username and password must both be provided.
  486. TWINE_PASSWORD: EnvVar[Optional[str]] = env_var(None)
  487. # Whether to use the system installed bun. If set to false, bun will be bundled with the app.
  488. REFLEX_USE_SYSTEM_BUN: EnvVar[bool] = env_var(False)
  489. # Whether to use the system installed node and npm. If set to false, node and npm will be bundled with the app.
  490. REFLEX_USE_SYSTEM_NODE: 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[Optional[ExecutorType]] = 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[Optional[int]] = 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[Optional[int]] = 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: Optional[str] = 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: Optional[str] = (
  602. f"http://localhost:{constants.DefaultPorts.FRONTEND_PORT}"
  603. )
  604. # The url the backend will be hosted on.
  605. backend_host: str = "0.0.0.0"
  606. # The database url used by rx.Model.
  607. db_url: Optional[str] = "sqlite:///reflex.db"
  608. # The async database url used by rx.Model.
  609. async_db_url: Optional[str] = None
  610. # The redis url
  611. redis_url: Optional[str] = None
  612. # Telemetry opt-in.
  613. telemetry_enabled: bool = True
  614. # The bun path
  615. bun_path: ExistingPath = constants.Bun.DEFAULT_PATH
  616. # Timeout to do a production build of a frontend page.
  617. static_page_generation_timeout: int = 60
  618. # List of origins that are allowed to connect to the backend API.
  619. cors_allowed_origins: List[str] = ["*"]
  620. # Tailwind config.
  621. tailwind: Optional[Dict[str, Any]] = {"plugins": ["@tailwindcss/typography"]}
  622. # Timeout when launching the gunicorn server. TODO(rename this to backend_timeout?)
  623. timeout: int = 120
  624. # Whether to enable or disable nextJS gzip compression.
  625. next_compression: bool = True
  626. # Whether to use React strict mode in nextJS
  627. react_strict_mode: bool = True
  628. # Additional frontend packages to install.
  629. frontend_packages: List[str] = []
  630. # The hosting service backend URL.
  631. cp_backend_url: str = Hosting.HOSTING_SERVICE
  632. # The hosting service frontend URL.
  633. cp_web_url: str = Hosting.HOSTING_SERVICE_UI
  634. # The worker class used in production mode
  635. gunicorn_worker_class: str = "uvicorn.workers.UvicornH11Worker"
  636. # Number of gunicorn workers from user
  637. gunicorn_workers: Optional[int] = None
  638. # Number of requests before a worker is restarted; set to 0 to disable
  639. gunicorn_max_requests: int = 100
  640. # Variance limit for max requests; gunicorn only
  641. gunicorn_max_requests_jitter: int = 25
  642. # Indicate which type of state manager to use
  643. state_manager_mode: constants.StateManagerMode = constants.StateManagerMode.DISK
  644. # Maximum expiration lock time for redis state manager
  645. redis_lock_expiration: int = constants.Expiration.LOCK
  646. # Maximum lock time before warning for redis state manager.
  647. redis_lock_warning_threshold: int = constants.Expiration.LOCK_WARNING_THRESHOLD
  648. # Token expiration time for redis state manager
  649. redis_token_expiration: int = constants.Expiration.TOKEN
  650. # Attributes that were explicitly set by the user.
  651. _non_default_attributes: Set[str] = pydantic.PrivateAttr(set())
  652. # Path to file containing key-values pairs to override in the environment; Dotenv format.
  653. env_file: Optional[str] = None
  654. # Whether to display the sticky "Built with Reflex" badge on all pages.
  655. show_built_with_reflex: Optional[bool] = None
  656. # Whether the app is running in the reflex cloud environment.
  657. is_reflex_cloud: bool = False
  658. # 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".
  659. extra_overlay_function: Optional[str] = None
  660. def __init__(self, *args, **kwargs):
  661. """Initialize the config values.
  662. Args:
  663. *args: The args to pass to the Pydantic init method.
  664. **kwargs: The kwargs to pass to the Pydantic init method.
  665. Raises:
  666. ConfigError: If some values in the config are invalid.
  667. """
  668. super().__init__(*args, **kwargs)
  669. # Update the config from environment variables.
  670. env_kwargs = self.update_from_env()
  671. for key, env_value in env_kwargs.items():
  672. setattr(self, key, env_value)
  673. # Update default URLs if ports were set
  674. kwargs.update(env_kwargs)
  675. self._non_default_attributes.update(kwargs)
  676. self._replace_defaults(**kwargs)
  677. # Set the log level for this process
  678. console.set_log_level(self.loglevel)
  679. if (
  680. self.state_manager_mode == constants.StateManagerMode.REDIS
  681. and not self.redis_url
  682. ):
  683. raise ConfigError(
  684. "REDIS_URL is required when using the redis state manager."
  685. )
  686. @property
  687. def app_module(self) -> ModuleType | None:
  688. """Return the app module if `app_module_import` is set.
  689. Returns:
  690. The app module.
  691. """
  692. return (
  693. importlib.import_module(self.app_module_import)
  694. if self.app_module_import
  695. else None
  696. )
  697. @property
  698. def module(self) -> str:
  699. """Get the module name of the app.
  700. Returns:
  701. The module name.
  702. """
  703. if self.app_module is not None:
  704. return self.app_module.__name__
  705. return ".".join([self.app_name, self.app_name])
  706. def update_from_env(self) -> dict[str, Any]:
  707. """Update the config values based on set environment variables.
  708. If there is a set env_file, it is loaded first.
  709. Returns:
  710. The updated config values.
  711. """
  712. env_file = self.env_file or os.environ.get("ENV_FILE", None)
  713. if env_file:
  714. if load_dotenv is None:
  715. console.error(
  716. """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`."""
  717. )
  718. else:
  719. # load env file if exists
  720. load_dotenv(env_file, override=True)
  721. updated_values = {}
  722. # Iterate over the fields.
  723. for key, field in self.__fields__.items():
  724. # The env var name is the key in uppercase.
  725. env_var = os.environ.get(key.upper())
  726. # If the env var is set, override the config value.
  727. if env_var is not None:
  728. # Interpret the value.
  729. value = interpret_env_var_value(env_var, field.outer_type_, field.name)
  730. # Set the value.
  731. updated_values[key] = value
  732. if key.upper() in _sensitive_env_vars:
  733. env_var = "***"
  734. console.info(
  735. f"Overriding config value {key} with env var {key.upper()}={env_var}",
  736. dedupe=True,
  737. )
  738. return updated_values
  739. def get_event_namespace(self) -> str:
  740. """Get the path that the backend Websocket server lists on.
  741. Returns:
  742. The namespace for websocket.
  743. """
  744. event_url = constants.Endpoint.EVENT.get_url()
  745. return urllib.parse.urlsplit(event_url).path
  746. def _replace_defaults(self, **kwargs):
  747. """Replace formatted defaults when the caller provides updates.
  748. Args:
  749. **kwargs: The kwargs passed to the config or from the env.
  750. """
  751. if "api_url" not in self._non_default_attributes and "backend_port" in kwargs:
  752. self.api_url = f"http://localhost:{kwargs['backend_port']}"
  753. if (
  754. "deploy_url" not in self._non_default_attributes
  755. and "frontend_port" in kwargs
  756. ):
  757. self.deploy_url = f"http://localhost:{kwargs['frontend_port']}"
  758. if "api_url" not in self._non_default_attributes:
  759. # If running in Github Codespaces, override API_URL
  760. codespace_name = os.getenv("CODESPACE_NAME")
  761. github_codespaces_port_forwarding_domain = os.getenv(
  762. "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
  763. )
  764. # If running on Replit.com interactively, override API_URL to ensure we maintain the backend_port
  765. replit_dev_domain = os.getenv("REPLIT_DEV_DOMAIN")
  766. backend_port = kwargs.get("backend_port", self.backend_port)
  767. if codespace_name and github_codespaces_port_forwarding_domain:
  768. self.api_url = (
  769. f"https://{codespace_name}-{kwargs.get('backend_port', self.backend_port)}"
  770. f".{github_codespaces_port_forwarding_domain}"
  771. )
  772. elif replit_dev_domain and backend_port:
  773. self.api_url = f"https://{replit_dev_domain}:{backend_port}"
  774. def _set_persistent(self, **kwargs):
  775. """Set values in this config and in the environment so they persist into subprocess.
  776. Args:
  777. **kwargs: The kwargs passed to the config.
  778. """
  779. for key, value in kwargs.items():
  780. if value is not None:
  781. os.environ[key.upper()] = str(value)
  782. setattr(self, key, value)
  783. self._non_default_attributes.update(kwargs)
  784. self._replace_defaults(**kwargs)
  785. def _get_config() -> Config:
  786. """Get the app config.
  787. Returns:
  788. The app config.
  789. """
  790. # only import the module if it exists. If a module spec exists then
  791. # the module exists.
  792. spec = find_spec(constants.Config.MODULE)
  793. if not spec:
  794. # we need this condition to ensure that a ModuleNotFound error is not thrown when
  795. # running unit/integration tests or during `reflex init`.
  796. return Config(app_name="")
  797. rxconfig = importlib.import_module(constants.Config.MODULE)
  798. return rxconfig.config
  799. # Protect sys.path from concurrent modification
  800. _config_lock = threading.RLock()
  801. def get_config(reload: bool = False) -> Config:
  802. """Get the app config.
  803. Args:
  804. reload: Re-import the rxconfig module from disk
  805. Returns:
  806. The app config.
  807. """
  808. cached_rxconfig = sys.modules.get(constants.Config.MODULE, None)
  809. if cached_rxconfig is not None:
  810. if reload:
  811. # Remove any cached module when `reload` is requested.
  812. del sys.modules[constants.Config.MODULE]
  813. else:
  814. return cached_rxconfig.config
  815. with _config_lock:
  816. orig_sys_path = sys.path.copy()
  817. sys.path.clear()
  818. sys.path.append(str(Path.cwd()))
  819. try:
  820. # Try to import the module with only the current directory in the path.
  821. return _get_config()
  822. except Exception:
  823. # If the module import fails, try to import with the original sys.path.
  824. sys.path.extend(orig_sys_path)
  825. return _get_config()
  826. finally:
  827. # Find any entries added to sys.path by rxconfig.py itself.
  828. extra_paths = [
  829. p for p in sys.path if p not in orig_sys_path and p != str(Path.cwd())
  830. ]
  831. # Restore the original sys.path.
  832. sys.path.clear()
  833. sys.path.extend(extra_paths)
  834. sys.path.extend(orig_sys_path)