config.py 35 KB

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