config.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. """The Reflex config."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import enum
  5. import importlib
  6. import inspect
  7. import os
  8. import sys
  9. import urllib.parse
  10. from pathlib import Path
  11. from typing import (
  12. TYPE_CHECKING,
  13. Any,
  14. Dict,
  15. Generic,
  16. List,
  17. Optional,
  18. Set,
  19. TypeVar,
  20. get_args,
  21. )
  22. from typing_extensions import Annotated, get_type_hints
  23. from reflex.utils.exceptions import ConfigError, EnvironmentVarValueError
  24. from reflex.utils.types import GenericType, is_union, value_inside_optional
  25. try:
  26. import pydantic.v1 as pydantic
  27. except ModuleNotFoundError:
  28. import pydantic
  29. from reflex_cli.constants.hosting import Hosting
  30. from reflex import constants
  31. from reflex.base import Base
  32. from reflex.utils import console
  33. class DBConfig(Base):
  34. """Database config."""
  35. engine: str
  36. username: Optional[str] = ""
  37. password: Optional[str] = ""
  38. host: Optional[str] = ""
  39. port: Optional[int] = None
  40. database: str
  41. @classmethod
  42. def postgresql(
  43. cls,
  44. database: str,
  45. username: str,
  46. password: str | None = None,
  47. host: str | None = None,
  48. port: int | None = 5432,
  49. ) -> DBConfig:
  50. """Create an instance with postgresql engine.
  51. Args:
  52. database: Database name.
  53. username: Database username.
  54. password: Database password.
  55. host: Database host.
  56. port: Database port.
  57. Returns:
  58. DBConfig instance.
  59. """
  60. return cls(
  61. engine="postgresql",
  62. username=username,
  63. password=password,
  64. host=host,
  65. port=port,
  66. database=database,
  67. )
  68. @classmethod
  69. def postgresql_psycopg2(
  70. cls,
  71. database: str,
  72. username: str,
  73. password: str | None = None,
  74. host: str | None = None,
  75. port: int | None = 5432,
  76. ) -> DBConfig:
  77. """Create an instance with postgresql+psycopg2 engine.
  78. Args:
  79. database: Database name.
  80. username: Database username.
  81. password: Database password.
  82. host: Database host.
  83. port: Database port.
  84. Returns:
  85. DBConfig instance.
  86. """
  87. return cls(
  88. engine="postgresql+psycopg2",
  89. username=username,
  90. password=password,
  91. host=host,
  92. port=port,
  93. database=database,
  94. )
  95. @classmethod
  96. def sqlite(
  97. cls,
  98. database: str,
  99. ) -> DBConfig:
  100. """Create an instance with sqlite engine.
  101. Args:
  102. database: Database name.
  103. Returns:
  104. DBConfig instance.
  105. """
  106. return cls(
  107. engine="sqlite",
  108. database=database,
  109. )
  110. def get_url(self) -> str:
  111. """Get database URL.
  112. Returns:
  113. The database URL.
  114. """
  115. host = (
  116. f"{self.host}:{self.port}" if self.host and self.port else self.host or ""
  117. )
  118. username = urllib.parse.quote_plus(self.username) if self.username else ""
  119. password = urllib.parse.quote_plus(self.password) if self.password else ""
  120. if username:
  121. path = f"{username}:{password}@{host}" if password else f"{username}@{host}"
  122. else:
  123. path = f"{host}"
  124. return f"{self.engine}://{path}/{self.database}"
  125. def get_default_value_for_field(field: dataclasses.Field) -> Any:
  126. """Get the default value for a field.
  127. Args:
  128. field: The field.
  129. Returns:
  130. The default value.
  131. Raises:
  132. ValueError: If no default value is found.
  133. """
  134. if field.default != dataclasses.MISSING:
  135. return field.default
  136. elif field.default_factory != dataclasses.MISSING:
  137. return field.default_factory()
  138. else:
  139. raise ValueError(
  140. f"Missing value for environment variable {field.name} and no default value found"
  141. )
  142. # TODO: Change all interpret_.* signatures to value: str, field: dataclasses.Field once we migrate rx.Config to dataclasses
  143. def interpret_boolean_env(value: str, field_name: str) -> bool:
  144. """Interpret a boolean environment variable value.
  145. Args:
  146. value: The environment variable value.
  147. field_name: The field name.
  148. Returns:
  149. The interpreted value.
  150. Raises:
  151. EnvironmentVarValueError: If the value is invalid.
  152. """
  153. true_values = ["true", "1", "yes", "y"]
  154. false_values = ["false", "0", "no", "n"]
  155. if value.lower() in true_values:
  156. return True
  157. elif value.lower() in false_values:
  158. return False
  159. raise EnvironmentVarValueError(f"Invalid boolean value: {value} for {field_name}")
  160. def interpret_int_env(value: str, field_name: str) -> int:
  161. """Interpret an integer environment variable value.
  162. Args:
  163. value: The environment variable value.
  164. field_name: The field name.
  165. Returns:
  166. The interpreted value.
  167. Raises:
  168. EnvironmentVarValueError: If the value is invalid.
  169. """
  170. try:
  171. return int(value)
  172. except ValueError as ve:
  173. raise EnvironmentVarValueError(
  174. f"Invalid integer value: {value} for {field_name}"
  175. ) from ve
  176. def interpret_existing_path_env(value: str, field_name: str) -> ExistingPath:
  177. """Interpret a path environment variable value as an existing path.
  178. Args:
  179. value: The environment variable value.
  180. field_name: The field name.
  181. Returns:
  182. The interpreted value.
  183. Raises:
  184. EnvironmentVarValueError: If the path does not exist.
  185. """
  186. path = Path(value)
  187. if not path.exists():
  188. raise EnvironmentVarValueError(f"Path does not exist: {path} for {field_name}")
  189. return path
  190. def interpret_path_env(value: str, field_name: str) -> Path:
  191. """Interpret a path environment variable value.
  192. Args:
  193. value: The environment variable value.
  194. field_name: The field name.
  195. Returns:
  196. The interpreted value.
  197. """
  198. return Path(value)
  199. def interpret_enum_env(value: str, field_type: GenericType, field_name: str) -> Any:
  200. """Interpret an enum environment variable value.
  201. Args:
  202. value: The environment variable value.
  203. field_type: The field type.
  204. field_name: The field name.
  205. Returns:
  206. The interpreted value.
  207. Raises:
  208. EnvironmentVarValueError: If the value is invalid.
  209. """
  210. try:
  211. return field_type(value)
  212. except ValueError as ve:
  213. raise EnvironmentVarValueError(
  214. f"Invalid enum value: {value} for {field_name}"
  215. ) from ve
  216. def interpret_env_var_value(
  217. value: str, field_type: GenericType, field_name: str
  218. ) -> Any:
  219. """Interpret an environment variable value based on the field type.
  220. Args:
  221. value: The environment variable value.
  222. field_type: The field type.
  223. field_name: The field name.
  224. Returns:
  225. The interpreted value.
  226. Raises:
  227. ValueError: If the value is invalid.
  228. """
  229. field_type = value_inside_optional(field_type)
  230. if is_union(field_type):
  231. raise ValueError(
  232. f"Union types are not supported for environment variables: {field_name}."
  233. )
  234. if field_type is bool:
  235. return interpret_boolean_env(value, field_name)
  236. elif field_type is str:
  237. return value
  238. elif field_type is int:
  239. return interpret_int_env(value, field_name)
  240. elif field_type is Path:
  241. return interpret_path_env(value, field_name)
  242. elif field_type is ExistingPath:
  243. return interpret_existing_path_env(value, field_name)
  244. elif inspect.isclass(field_type) and issubclass(field_type, enum.Enum):
  245. return interpret_enum_env(value, field_type, field_name)
  246. else:
  247. raise ValueError(
  248. f"Invalid type for environment variable {field_name}: {field_type}. This is probably an issue in Reflex."
  249. )
  250. T = TypeVar("T")
  251. class EnvVar(Generic[T]):
  252. """Environment variable."""
  253. name: str
  254. default: Any
  255. type_: T
  256. def __init__(self, name: str, default: Any, type_: T) -> None:
  257. """Initialize the environment variable.
  258. Args:
  259. name: The environment variable name.
  260. default: The default value.
  261. type_: The type of the value.
  262. """
  263. self.name = name
  264. self.default = default
  265. self.type_ = type_
  266. def interpret(self, value: str) -> T:
  267. """Interpret the environment variable value.
  268. Args:
  269. value: The environment variable value.
  270. Returns:
  271. The interpreted value.
  272. """
  273. return interpret_env_var_value(value, self.type_, self.name)
  274. def getenv(self) -> Optional[T]:
  275. """Get the interpreted environment variable value.
  276. Returns:
  277. The environment variable value.
  278. """
  279. env_value = os.getenv(self.name, None)
  280. if env_value is not None:
  281. return self.interpret(env_value)
  282. return None
  283. def is_set(self) -> bool:
  284. """Check if the environment variable is set.
  285. Returns:
  286. True if the environment variable is set.
  287. """
  288. return self.name in os.environ
  289. def get(self) -> T:
  290. """Get the interpreted environment variable value or the default value if not set.
  291. Returns:
  292. The interpreted value.
  293. """
  294. env_value = self.getenv()
  295. if env_value is not None:
  296. return env_value
  297. return self.default
  298. def set(self, value: T | None) -> None:
  299. """Set the environment variable. None unsets the variable.
  300. Args:
  301. value: The value to set.
  302. """
  303. if value is None:
  304. _ = os.environ.pop(self.name, None)
  305. else:
  306. if isinstance(value, enum.Enum):
  307. value = value.value
  308. os.environ[self.name] = str(value)
  309. class env_var: # type: ignore
  310. """Descriptor for environment variables."""
  311. name: str
  312. default: Any
  313. internal: bool = False
  314. def __init__(self, default: Any, internal: bool = False) -> None:
  315. """Initialize the descriptor.
  316. Args:
  317. default: The default value.
  318. internal: Whether the environment variable is reflex internal.
  319. """
  320. self.default = default
  321. self.internal = internal
  322. def __set_name__(self, owner, name):
  323. """Set the name of the descriptor.
  324. Args:
  325. owner: The owner class.
  326. name: The name of the descriptor.
  327. """
  328. self.name = name
  329. def __get__(self, instance, owner):
  330. """Get the EnvVar instance.
  331. Args:
  332. instance: The instance.
  333. owner: The owner class.
  334. Returns:
  335. The EnvVar instance.
  336. """
  337. type_ = get_args(get_type_hints(owner)[self.name])[0]
  338. env_name = self.name
  339. if self.internal:
  340. env_name = f"__{env_name}"
  341. return EnvVar(name=env_name, default=self.default, type_=type_)
  342. if TYPE_CHECKING:
  343. def env_var(default, internal=False) -> EnvVar:
  344. """Typing helper for the env_var descriptor.
  345. Args:
  346. default: The default value.
  347. internal: Whether the environment variable is reflex internal.
  348. Returns:
  349. The EnvVar instance.
  350. """
  351. return default
  352. class PathExistsFlag:
  353. """Flag to indicate that a path must exist."""
  354. ExistingPath = Annotated[Path, PathExistsFlag]
  355. class EnvironmentVariables:
  356. """Environment variables class to instantiate environment variables."""
  357. # Whether to use npm over bun to install frontend packages.
  358. REFLEX_USE_NPM: EnvVar[bool] = env_var(False)
  359. # The npm registry to use.
  360. NPM_CONFIG_REGISTRY: EnvVar[Optional[str]] = env_var(None)
  361. # Whether to use Granian for the backend. Otherwise, use Uvicorn.
  362. REFLEX_USE_GRANIAN: EnvVar[bool] = env_var(False)
  363. # The username to use for authentication on python package repository. Username and password must both be provided.
  364. TWINE_USERNAME: EnvVar[Optional[str]] = env_var(None)
  365. # The password to use for authentication on python package repository. Username and password must both be provided.
  366. TWINE_PASSWORD: EnvVar[Optional[str]] = env_var(None)
  367. # Whether to use the system installed bun. If set to false, bun will be bundled with the app.
  368. REFLEX_USE_SYSTEM_BUN: EnvVar[bool] = env_var(False)
  369. # Whether to use the system installed node and npm. If set to false, node and npm will be bundled with the app.
  370. REFLEX_USE_SYSTEM_NODE: EnvVar[bool] = env_var(False)
  371. # The working directory for the next.js commands.
  372. REFLEX_WEB_WORKDIR: EnvVar[Path] = env_var(Path(constants.Dirs.WEB))
  373. # Path to the alembic config file
  374. ALEMBIC_CONFIG: EnvVar[ExistingPath] = env_var(Path(constants.ALEMBIC_CONFIG))
  375. # Disable SSL verification for HTTPX requests.
  376. SSL_NO_VERIFY: EnvVar[bool] = env_var(False)
  377. # The directory to store uploaded files.
  378. REFLEX_UPLOADED_FILES_DIR: EnvVar[Path] = env_var(
  379. Path(constants.Dirs.UPLOADED_FILES)
  380. )
  381. # Whether to use separate processes to compile the frontend and how many. If not set, defaults to thread executor.
  382. REFLEX_COMPILE_PROCESSES: EnvVar[Optional[int]] = env_var(None)
  383. # Whether to use separate threads to compile the frontend and how many. Defaults to `min(32, os.cpu_count() + 4)`.
  384. REFLEX_COMPILE_THREADS: EnvVar[Optional[int]] = env_var(None)
  385. # The directory to store reflex dependencies.
  386. REFLEX_DIR: EnvVar[Path] = env_var(Path(constants.Reflex.DIR))
  387. # Whether to print the SQL queries if the log level is INFO or lower.
  388. SQLALCHEMY_ECHO: EnvVar[bool] = env_var(False)
  389. # Whether to ignore the redis config error. Some redis servers only allow out-of-band configuration.
  390. REFLEX_IGNORE_REDIS_CONFIG_ERROR: EnvVar[bool] = env_var(False)
  391. # Whether to skip purging the web directory in dev mode.
  392. REFLEX_PERSIST_WEB_DIR: EnvVar[bool] = env_var(False)
  393. # The reflex.build frontend host.
  394. REFLEX_BUILD_FRONTEND: EnvVar[str] = env_var(
  395. constants.Templates.REFLEX_BUILD_FRONTEND
  396. )
  397. # The reflex.build backend host.
  398. REFLEX_BUILD_BACKEND: EnvVar[str] = env_var(
  399. constants.Templates.REFLEX_BUILD_BACKEND
  400. )
  401. # This env var stores the execution mode of the app
  402. REFLEX_ENV_MODE: EnvVar[constants.Env] = env_var(constants.Env.DEV)
  403. # Whether to run the backend only. Exclusive with REFLEX_FRONTEND_ONLY.
  404. REFLEX_BACKEND_ONLY: EnvVar[bool] = env_var(False)
  405. # Whether to run the frontend only. Exclusive with REFLEX_BACKEND_ONLY.
  406. REFLEX_FRONTEND_ONLY: EnvVar[bool] = env_var(False)
  407. # Reflex internal env to reload the config.
  408. RELOAD_CONFIG: EnvVar[bool] = env_var(False, internal=True)
  409. # If this env var is set to "yes", App.compile will be a no-op
  410. REFLEX_SKIP_COMPILE: EnvVar[bool] = env_var(False, internal=True)
  411. # Whether to run app harness tests in headless mode.
  412. APP_HARNESS_HEADLESS: EnvVar[bool] = env_var(False)
  413. # Which app harness driver to use.
  414. APP_HARNESS_DRIVER: EnvVar[str] = env_var("Chrome")
  415. # Arguments to pass to the app harness driver.
  416. APP_HARNESS_DRIVER_ARGS: EnvVar[str] = env_var("")
  417. # Where to save screenshots when tests fail.
  418. SCREENSHOT_DIR: EnvVar[Optional[Path]] = env_var(None)
  419. environment = EnvironmentVariables()
  420. class Config(Base):
  421. """The config defines runtime settings for the app.
  422. By default, the config is defined in an `rxconfig.py` file in the root of the app.
  423. ```python
  424. # rxconfig.py
  425. import reflex as rx
  426. config = rx.Config(
  427. app_name="myapp",
  428. api_url="http://localhost:8000",
  429. )
  430. ```
  431. Every config value can be overridden by an environment variable with the same name in uppercase.
  432. For example, `db_url` can be overridden by setting the `DB_URL` environment variable.
  433. See the [configuration](https://reflex.dev/docs/getting-started/configuration/) docs for more info.
  434. """
  435. class Config:
  436. """Pydantic config for the config."""
  437. validate_assignment = True
  438. # The name of the app (should match the name of the app directory).
  439. app_name: str
  440. # The log level to use.
  441. loglevel: constants.LogLevel = constants.LogLevel.DEFAULT
  442. # The port to run the frontend on. NOTE: When running in dev mode, the next available port will be used if this is taken.
  443. frontend_port: int = constants.DefaultPorts.FRONTEND_PORT
  444. # The path to run the frontend on. For example, "/app" will run the frontend on http://localhost:3000/app
  445. frontend_path: str = ""
  446. # The port to run the backend on. NOTE: When running in dev mode, the next available port will be used if this is taken.
  447. backend_port: int = constants.DefaultPorts.BACKEND_PORT
  448. # The backend url the frontend will connect to. This must be updated if the backend is hosted elsewhere, or in production.
  449. api_url: str = f"http://localhost:{backend_port}"
  450. # The url the frontend will be hosted on.
  451. deploy_url: Optional[str] = f"http://localhost:{frontend_port}"
  452. # The url the backend will be hosted on.
  453. backend_host: str = "0.0.0.0"
  454. # The database url used by rx.Model.
  455. db_url: Optional[str] = "sqlite:///reflex.db"
  456. # The redis url
  457. redis_url: Optional[str] = None
  458. # Telemetry opt-in.
  459. telemetry_enabled: bool = True
  460. # The bun path
  461. bun_path: ExistingPath = constants.Bun.DEFAULT_PATH
  462. # Timeout to do a production build of a frontend page.
  463. static_page_generation_timeout: int = 60
  464. # List of origins that are allowed to connect to the backend API.
  465. cors_allowed_origins: List[str] = ["*"]
  466. # Tailwind config.
  467. tailwind: Optional[Dict[str, Any]] = {"plugins": ["@tailwindcss/typography"]}
  468. # Timeout when launching the gunicorn server. TODO(rename this to backend_timeout?)
  469. timeout: int = 120
  470. # Whether to enable or disable nextJS gzip compression.
  471. next_compression: bool = True
  472. # Whether to use React strict mode in nextJS
  473. react_strict_mode: bool = True
  474. # Additional frontend packages to install.
  475. frontend_packages: List[str] = []
  476. # The hosting service backend URL.
  477. cp_backend_url: str = Hosting.CP_BACKEND_URL
  478. # The hosting service frontend URL.
  479. cp_web_url: str = Hosting.CP_WEB_URL
  480. # The worker class used in production mode
  481. gunicorn_worker_class: str = "uvicorn.workers.UvicornH11Worker"
  482. # Number of gunicorn workers from user
  483. gunicorn_workers: Optional[int] = None
  484. # Number of requests before a worker is restarted
  485. gunicorn_max_requests: int = 100
  486. # Variance limit for max requests; gunicorn only
  487. gunicorn_max_requests_jitter: int = 25
  488. # Indicate which type of state manager to use
  489. state_manager_mode: constants.StateManagerMode = constants.StateManagerMode.DISK
  490. # Maximum expiration lock time for redis state manager
  491. redis_lock_expiration: int = constants.Expiration.LOCK
  492. # Token expiration time for redis state manager
  493. redis_token_expiration: int = constants.Expiration.TOKEN
  494. # Attributes that were explicitly set by the user.
  495. _non_default_attributes: Set[str] = pydantic.PrivateAttr(set())
  496. # Path to file containing key-values pairs to override in the environment; Dotenv format.
  497. env_file: Optional[str] = None
  498. def __init__(self, *args, **kwargs):
  499. """Initialize the config values.
  500. Args:
  501. *args: The args to pass to the Pydantic init method.
  502. **kwargs: The kwargs to pass to the Pydantic init method.
  503. Raises:
  504. ConfigError: If some values in the config are invalid.
  505. """
  506. super().__init__(*args, **kwargs)
  507. # Update the config from environment variables.
  508. env_kwargs = self.update_from_env()
  509. for key, env_value in env_kwargs.items():
  510. setattr(self, key, env_value)
  511. # Update default URLs if ports were set
  512. kwargs.update(env_kwargs)
  513. self._non_default_attributes.update(kwargs)
  514. self._replace_defaults(**kwargs)
  515. if (
  516. self.state_manager_mode == constants.StateManagerMode.REDIS
  517. and not self.redis_url
  518. ):
  519. raise ConfigError(
  520. "REDIS_URL is required when using the redis state manager."
  521. )
  522. @property
  523. def module(self) -> str:
  524. """Get the module name of the app.
  525. Returns:
  526. The module name.
  527. """
  528. return ".".join([self.app_name, self.app_name])
  529. def update_from_env(self) -> dict[str, Any]:
  530. """Update the config values based on set environment variables.
  531. If there is a set env_file, it is loaded first.
  532. Returns:
  533. The updated config values.
  534. """
  535. if self.env_file:
  536. try:
  537. from dotenv import load_dotenv # type: ignore
  538. # load env file if exists
  539. load_dotenv(self.env_file, override=True)
  540. except ImportError:
  541. console.error(
  542. """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`."""
  543. )
  544. updated_values = {}
  545. # Iterate over the fields.
  546. for key, field in self.__fields__.items():
  547. # The env var name is the key in uppercase.
  548. env_var = os.environ.get(key.upper())
  549. # If the env var is set, override the config value.
  550. if env_var is not None:
  551. if key.upper() != "DB_URL":
  552. console.info(
  553. f"Overriding config value {key} with env var {key.upper()}={env_var}",
  554. dedupe=True,
  555. )
  556. # Interpret the value.
  557. value = interpret_env_var_value(env_var, field.outer_type_, field.name)
  558. # Set the value.
  559. updated_values[key] = value
  560. return updated_values
  561. def get_event_namespace(self) -> str:
  562. """Get the path that the backend Websocket server lists on.
  563. Returns:
  564. The namespace for websocket.
  565. """
  566. event_url = constants.Endpoint.EVENT.get_url()
  567. return urllib.parse.urlsplit(event_url).path
  568. def _replace_defaults(self, **kwargs):
  569. """Replace formatted defaults when the caller provides updates.
  570. Args:
  571. **kwargs: The kwargs passed to the config or from the env.
  572. """
  573. if "api_url" not in self._non_default_attributes and "backend_port" in kwargs:
  574. self.api_url = f"http://localhost:{kwargs['backend_port']}"
  575. if (
  576. "deploy_url" not in self._non_default_attributes
  577. and "frontend_port" in kwargs
  578. ):
  579. self.deploy_url = f"http://localhost:{kwargs['frontend_port']}"
  580. if "api_url" not in self._non_default_attributes:
  581. # If running in Github Codespaces, override API_URL
  582. codespace_name = os.getenv("CODESPACE_NAME")
  583. GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv(
  584. "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
  585. )
  586. # If running on Replit.com interactively, override API_URL to ensure we maintain the backend_port
  587. replit_dev_domain = os.getenv("REPLIT_DEV_DOMAIN")
  588. backend_port = kwargs.get("backend_port", self.backend_port)
  589. if codespace_name and GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN:
  590. self.api_url = (
  591. f"https://{codespace_name}-{kwargs.get('backend_port', self.backend_port)}"
  592. f".{GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}"
  593. )
  594. elif replit_dev_domain and backend_port:
  595. self.api_url = f"https://{replit_dev_domain}:{backend_port}"
  596. def _set_persistent(self, **kwargs):
  597. """Set values in this config and in the environment so they persist into subprocess.
  598. Args:
  599. **kwargs: The kwargs passed to the config.
  600. """
  601. for key, value in kwargs.items():
  602. if value is not None:
  603. os.environ[key.upper()] = str(value)
  604. setattr(self, key, value)
  605. self._non_default_attributes.update(kwargs)
  606. self._replace_defaults(**kwargs)
  607. def get_config(reload: bool = False) -> Config:
  608. """Get the app config.
  609. Args:
  610. reload: Re-import the rxconfig module from disk
  611. Returns:
  612. The app config.
  613. """
  614. sys.path.insert(0, os.getcwd())
  615. # only import the module if it exists. If a module spec exists then
  616. # the module exists.
  617. spec = importlib.util.find_spec(constants.Config.MODULE) # type: ignore
  618. if not spec:
  619. # we need this condition to ensure that a ModuleNotFound error is not thrown when
  620. # running unit/integration tests.
  621. return Config(app_name="")
  622. rxconfig = importlib.import_module(constants.Config.MODULE)
  623. if reload:
  624. importlib.reload(rxconfig)
  625. return rxconfig.config