config.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. """The Reflex config."""
  2. from __future__ import annotations
  3. import importlib
  4. import os
  5. import sys
  6. import urllib.parse
  7. from typing import Any, Dict, List, Optional, Set
  8. import pydantic
  9. from reflex import constants
  10. from reflex.base import Base
  11. from reflex.utils import console
  12. class DBConfig(Base):
  13. """Database config."""
  14. engine: str
  15. username: Optional[str] = ""
  16. password: Optional[str] = ""
  17. host: Optional[str] = ""
  18. port: Optional[int] = None
  19. database: str
  20. @classmethod
  21. def postgresql(
  22. cls,
  23. database: str,
  24. username: str,
  25. password: str | None = None,
  26. host: str | None = None,
  27. port: int | None = 5432,
  28. ) -> DBConfig:
  29. """Create an instance with postgresql engine.
  30. Args:
  31. database: Database name.
  32. username: Database username.
  33. password: Database password.
  34. host: Database host.
  35. port: Database port.
  36. Returns:
  37. DBConfig instance.
  38. """
  39. return cls(
  40. engine="postgresql",
  41. username=username,
  42. password=password,
  43. host=host,
  44. port=port,
  45. database=database,
  46. )
  47. @classmethod
  48. def postgresql_psycopg2(
  49. cls,
  50. database: str,
  51. username: str,
  52. password: str | None = None,
  53. host: str | None = None,
  54. port: int | None = 5432,
  55. ) -> DBConfig:
  56. """Create an instance with postgresql+psycopg2 engine.
  57. Args:
  58. database: Database name.
  59. username: Database username.
  60. password: Database password.
  61. host: Database host.
  62. port: Database port.
  63. Returns:
  64. DBConfig instance.
  65. """
  66. return cls(
  67. engine="postgresql+psycopg2",
  68. username=username,
  69. password=password,
  70. host=host,
  71. port=port,
  72. database=database,
  73. )
  74. @classmethod
  75. def sqlite(
  76. cls,
  77. database: str,
  78. ) -> DBConfig:
  79. """Create an instance with sqlite engine.
  80. Args:
  81. database: Database name.
  82. Returns:
  83. DBConfig instance.
  84. """
  85. return cls(
  86. engine="sqlite",
  87. database=database,
  88. )
  89. def get_url(self) -> str:
  90. """Get database URL.
  91. Returns:
  92. The database URL.
  93. """
  94. host = (
  95. f"{self.host}:{self.port}" if self.host and self.port else self.host or ""
  96. )
  97. username = urllib.parse.quote_plus(self.username) if self.username else ""
  98. password = urllib.parse.quote_plus(self.password) if self.password else ""
  99. if username:
  100. path = f"{username}:{password}@{host}" if password else f"{username}@{host}"
  101. else:
  102. path = f"{host}"
  103. return f"{self.engine}://{path}/{self.database}"
  104. class Config(Base):
  105. """A Reflex config."""
  106. class Config:
  107. """Pydantic config for the config."""
  108. validate_assignment = True
  109. # The name of the app.
  110. app_name: str
  111. # The log level to use.
  112. loglevel: constants.LogLevel = constants.LogLevel.INFO
  113. # The port to run the frontend on.
  114. frontend_port: int = 3000
  115. # The path to run the frontend on.
  116. frontend_path: str = ""
  117. # The port to run the backend on.
  118. backend_port: int = 8000
  119. # The backend url the frontend will connect to.
  120. api_url: str = f"http://localhost:{backend_port}"
  121. # The url the frontend will be hosted on.
  122. deploy_url: Optional[str] = f"http://localhost:{frontend_port}"
  123. # The url the backend will be hosted on.
  124. backend_host: str = "0.0.0.0"
  125. # The database url.
  126. db_url: Optional[str] = "sqlite:///reflex.db"
  127. # The redis url.
  128. redis_url: Optional[str] = None
  129. # Telemetry opt-in.
  130. telemetry_enabled: bool = True
  131. # The bun path
  132. bun_path: str = constants.Bun.DEFAULT_PATH
  133. # List of origins that are allowed to connect to the backend API.
  134. cors_allowed_origins: List[str] = ["*"]
  135. # Tailwind config.
  136. tailwind: Optional[Dict[str, Any]] = {}
  137. # Timeout when launching the gunicorn server. TODO(rename this to backend_timeout?)
  138. timeout: int = 120
  139. # Whether to enable or disable nextJS gzip compression.
  140. next_compression: bool = True
  141. # The event namespace for ws connection
  142. event_namespace: Optional[str] = None
  143. # Additional frontend packages to install.
  144. frontend_packages: List[str] = []
  145. # Params to remove eventually.
  146. # For rest are for deploy only.
  147. # The rxdeploy url.
  148. rxdeploy_url: Optional[str] = None
  149. # The hosting service backend URL.
  150. cp_backend_url: str = constants.Hosting.CP_BACKEND_URL
  151. # The hosting service frontend URL.
  152. cp_web_url: str = constants.Hosting.CP_WEB_URL
  153. # The username.
  154. username: Optional[str] = None
  155. # The worker class used in production mode
  156. gunicorn_worker_class: str = "uvicorn.workers.UvicornH11Worker"
  157. # Attributes that were explicitly set by the user.
  158. _non_default_attributes: Set[str] = pydantic.PrivateAttr(set())
  159. def __init__(self, *args, **kwargs):
  160. """Initialize the config values.
  161. Args:
  162. *args: The args to pass to the Pydantic init method.
  163. **kwargs: The kwargs to pass to the Pydantic init method.
  164. """
  165. super().__init__(*args, **kwargs)
  166. # Check for deprecated values.
  167. self.check_deprecated_values(**kwargs)
  168. # Update the config from environment variables.
  169. env_kwargs = self.update_from_env()
  170. for key, env_value in env_kwargs.items():
  171. setattr(self, key, env_value)
  172. # Update default URLs if ports were set
  173. kwargs.update(env_kwargs)
  174. self._non_default_attributes.update(kwargs)
  175. self._replace_defaults(**kwargs)
  176. @staticmethod
  177. def check_deprecated_values(**kwargs):
  178. """Check for deprecated config values.
  179. Args:
  180. **kwargs: The kwargs passed to the config.
  181. Raises:
  182. ValueError: If a deprecated config value is found.
  183. """
  184. if "db_config" in kwargs:
  185. raise ValueError("db_config is deprecated - use db_url instead")
  186. if "admin_dash" in kwargs:
  187. raise ValueError(
  188. "admin_dash is deprecated in the config - pass it as a param to rx.App instead"
  189. )
  190. if "env_path" in kwargs:
  191. raise ValueError(
  192. "env_path is deprecated - use environment variables instead"
  193. )
  194. def update_from_env(self) -> dict[str, Any]:
  195. """Update the config from environment variables.
  196. Returns:
  197. The updated config values.
  198. Raises:
  199. ValueError: If an environment variable is set to an invalid type.
  200. """
  201. updated_values = {}
  202. # Iterate over the fields.
  203. for key, field in self.__fields__.items():
  204. # The env var name is the key in uppercase.
  205. env_var = os.environ.get(key.upper())
  206. # If the env var is set, override the config value.
  207. if env_var is not None:
  208. if key.upper() != "DB_URL":
  209. console.info(
  210. f"Overriding config value {key} with env var {key.upper()}={env_var}"
  211. )
  212. # Convert the env var to the expected type.
  213. try:
  214. if issubclass(field.type_, bool):
  215. # special handling for bool values
  216. env_var = env_var.lower() in ["true", "1", "yes"]
  217. else:
  218. env_var = field.type_(env_var)
  219. except ValueError:
  220. console.error(
  221. f"Could not convert {key.upper()}={env_var} to type {field.type_}"
  222. )
  223. raise
  224. # Set the value.
  225. updated_values[key] = env_var
  226. return updated_values
  227. def get_event_namespace(self) -> str | None:
  228. """Get the websocket event namespace.
  229. Returns:
  230. The namespace for websocket.
  231. """
  232. if self.event_namespace:
  233. return f'/{self.event_namespace.strip("/")}'
  234. event_url = constants.Endpoint.EVENT.get_url()
  235. return urllib.parse.urlsplit(event_url).path
  236. def _replace_defaults(self, **kwargs):
  237. """Replace formatted defaults when the caller provides updates.
  238. Args:
  239. **kwargs: The kwargs passed to the config or from the env.
  240. """
  241. if "api_url" not in self._non_default_attributes and "backend_port" in kwargs:
  242. self.api_url = f"http://localhost:{kwargs['backend_port']}"
  243. if (
  244. "deploy_url" not in self._non_default_attributes
  245. and "frontend_port" in kwargs
  246. ):
  247. self.deploy_url = f"http://localhost:{kwargs['frontend_port']}"
  248. # If running in Github Codespaces, override API_URL
  249. codespace_name = os.getenv("CODESPACE_NAME")
  250. if "api_url" not in self._non_default_attributes and codespace_name:
  251. GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv(
  252. "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
  253. )
  254. if codespace_name:
  255. self.api_url = (
  256. f"https://{codespace_name}-{kwargs.get('backend_port', self.backend_port)}"
  257. f".{GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}"
  258. )
  259. def _set_persistent(self, **kwargs):
  260. """Set values in this config and in the environment so they persist into subprocess.
  261. Args:
  262. **kwargs: The kwargs passed to the config.
  263. """
  264. for key, value in kwargs.items():
  265. if value is not None:
  266. os.environ[key.upper()] = str(value)
  267. setattr(self, key, value)
  268. self._non_default_attributes.update(kwargs)
  269. self._replace_defaults(**kwargs)
  270. def get_config(reload: bool = False) -> Config:
  271. """Get the app config.
  272. Args:
  273. reload: Re-import the rxconfig module from disk
  274. Returns:
  275. The app config.
  276. """
  277. sys.path.insert(0, os.getcwd())
  278. try:
  279. rxconfig = __import__(constants.Config.MODULE)
  280. if reload:
  281. importlib.reload(rxconfig)
  282. return rxconfig.config
  283. except ImportError:
  284. return Config(app_name="") # type: ignore