app.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  1. """The main Reflex app."""
  2. from __future__ import annotations
  3. import asyncio
  4. import concurrent.futures
  5. import contextlib
  6. import copy
  7. import dataclasses
  8. import functools
  9. import inspect
  10. import io
  11. import json
  12. import sys
  13. import traceback
  14. from collections.abc import AsyncIterator, Callable, Coroutine, Sequence
  15. from datetime import datetime
  16. from pathlib import Path
  17. from timeit import default_timer as timer
  18. from types import SimpleNamespace
  19. from typing import TYPE_CHECKING, Any, BinaryIO, get_args, get_type_hints
  20. from fastapi import FastAPI
  21. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  22. from socketio import ASGIApp as EngineIOApp
  23. from socketio import AsyncNamespace, AsyncServer
  24. from starlette.applications import Starlette
  25. from starlette.datastructures import Headers
  26. from starlette.datastructures import UploadFile as StarletteUploadFile
  27. from starlette.exceptions import HTTPException
  28. from starlette.middleware import cors
  29. from starlette.requests import ClientDisconnect, Request
  30. from starlette.responses import JSONResponse, Response, StreamingResponse
  31. from starlette.staticfiles import StaticFiles
  32. from typing_extensions import deprecated
  33. from reflex import constants
  34. from reflex.admin import AdminDash
  35. from reflex.app_mixins import AppMixin, LifespanMixin, MiddlewareMixin
  36. from reflex.compiler import compiler
  37. from reflex.compiler import utils as compiler_utils
  38. from reflex.compiler.compiler import (
  39. ExecutorSafeFunctions,
  40. compile_theme,
  41. readable_name_from_component,
  42. )
  43. from reflex.components.base.app_wrap import AppWrap
  44. from reflex.components.base.error_boundary import ErrorBoundary
  45. from reflex.components.base.fragment import Fragment
  46. from reflex.components.base.strict_mode import StrictMode
  47. from reflex.components.component import (
  48. CUSTOM_COMPONENTS,
  49. Component,
  50. ComponentStyle,
  51. evaluate_style_namespaces,
  52. )
  53. from reflex.components.core.banner import (
  54. backend_disabled,
  55. connection_pulser,
  56. connection_toaster,
  57. )
  58. from reflex.components.core.breakpoints import set_breakpoints
  59. from reflex.components.core.client_side_routing import (
  60. Default404Page,
  61. wait_for_client_redirect,
  62. )
  63. from reflex.components.core.sticky import sticky
  64. from reflex.components.core.upload import Upload, get_upload_dir
  65. from reflex.components.radix import themes
  66. from reflex.components.sonner.toast import toast
  67. from reflex.config import ExecutorType, environment, get_config
  68. from reflex.event import (
  69. _EVENT_FIELDS,
  70. Event,
  71. EventHandler,
  72. EventSpec,
  73. EventType,
  74. IndividualEventType,
  75. get_hydrate_event,
  76. )
  77. from reflex.model import Model, get_db_status
  78. from reflex.page import DECORATED_PAGES
  79. from reflex.route import (
  80. get_route_args,
  81. replace_brackets_with_keywords,
  82. verify_route_validity,
  83. )
  84. from reflex.state import (
  85. BaseState,
  86. RouterData,
  87. State,
  88. StateManager,
  89. StateUpdate,
  90. _substate_key,
  91. all_base_state_classes,
  92. code_uses_state_contexts,
  93. )
  94. from reflex.utils import (
  95. codespaces,
  96. console,
  97. exceptions,
  98. format,
  99. path_ops,
  100. prerequisites,
  101. types,
  102. )
  103. from reflex.utils.exec import get_compile_context, is_prod_mode, is_testing_env
  104. from reflex.utils.imports import ImportVar
  105. from reflex.utils.types import ASGIApp, Message, Receive, Scope, Send
  106. if TYPE_CHECKING:
  107. from reflex.vars import Var
  108. # Define custom types.
  109. ComponentCallable = Callable[[], Component | tuple[Component, ...] | str | Var]
  110. else:
  111. ComponentCallable = Callable[[], Component | tuple[Component, ...] | str]
  112. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  113. def default_frontend_exception_handler(exception: Exception) -> None:
  114. """Default frontend exception handler function.
  115. Args:
  116. exception: The exception.
  117. """
  118. console.error(f"[Reflex Frontend Exception]\n {exception}\n")
  119. def default_backend_exception_handler(exception: Exception) -> EventSpec:
  120. """Default backend exception handler function.
  121. Args:
  122. exception: The exception.
  123. Returns:
  124. EventSpec: The window alert event.
  125. """
  126. from reflex.components.sonner.toast import toast
  127. error = traceback.format_exc()
  128. console.error(f"[Reflex Backend Exception]\n {error}\n")
  129. error_message = (
  130. ["Contact the website administrator."]
  131. if is_prod_mode()
  132. else [f"{type(exception).__name__}: {exception}.", "See logs for details."]
  133. )
  134. return toast(
  135. "An error occurred.",
  136. level="error",
  137. fallback_to_alert=True,
  138. description="<br/>".join(error_message),
  139. position="top-center",
  140. id="backend_error",
  141. style={"width": "500px"},
  142. )
  143. def extra_overlay_function() -> Component | None:
  144. """Extra overlay function to add to the overlay component.
  145. Returns:
  146. The extra overlay function.
  147. """
  148. config = get_config()
  149. extra_config = config.extra_overlay_function
  150. config_overlay = None
  151. if extra_config:
  152. module, _, function_name = extra_config.rpartition(".")
  153. try:
  154. module = __import__(module)
  155. config_overlay = Fragment.create(getattr(module, function_name)())
  156. config_overlay._get_all_imports()
  157. except Exception as e:
  158. from reflex.compiler.utils import save_error
  159. log_path = save_error(e)
  160. console.error(
  161. f"Error loading extra_overlay_function {extra_config}. Error saved to {log_path}"
  162. )
  163. return config_overlay
  164. def default_overlay_component() -> Component:
  165. """Default overlay_component attribute for App.
  166. Returns:
  167. The default overlay_component, which is a connection_modal.
  168. """
  169. from reflex.components.component import memo
  170. def default_overlay_components():
  171. return Fragment.create(
  172. connection_pulser(),
  173. connection_toaster(),
  174. *(
  175. [backend_disabled()]
  176. if get_compile_context() == constants.CompileContext.DEPLOY
  177. else []
  178. ),
  179. *codespaces.codespaces_auto_redirect(),
  180. )
  181. return Fragment.create(memo(default_overlay_components)())
  182. def default_error_boundary(*children: Component) -> Component:
  183. """Default error_boundary attribute for App.
  184. Args:
  185. *children: The children to render in the error boundary.
  186. Returns:
  187. The default error_boundary, which is an ErrorBoundary.
  188. """
  189. return ErrorBoundary.create(*children)
  190. class OverlayFragment(Fragment):
  191. """Alias for Fragment, used to wrap the overlay_component."""
  192. pass
  193. @dataclasses.dataclass(frozen=True)
  194. class UploadFile(StarletteUploadFile):
  195. """A file uploaded to the server.
  196. Args:
  197. file: The standard Python file object (non-async).
  198. filename: The original file name.
  199. size: The size of the file in bytes.
  200. headers: The headers of the request.
  201. """
  202. file: BinaryIO
  203. path: Path | None = dataclasses.field(default=None)
  204. _deprecated_filename: str | None = dataclasses.field(default=None)
  205. size: int | None = dataclasses.field(default=None)
  206. headers: Headers = dataclasses.field(default_factory=Headers)
  207. @property
  208. def name(self) -> str | None:
  209. """Get the name of the uploaded file.
  210. Returns:
  211. The name of the uploaded file.
  212. """
  213. if self.path:
  214. return self.path.name
  215. @property
  216. def filename(self) -> str | None:
  217. """Get the filename of the uploaded file.
  218. Returns:
  219. The filename of the uploaded file.
  220. """
  221. console.deprecate(
  222. feature_name="UploadFile.filename",
  223. reason="Use UploadFile.name instead.",
  224. deprecation_version="0.7.1",
  225. removal_version="0.8.0",
  226. )
  227. return self._deprecated_filename
  228. @dataclasses.dataclass(
  229. frozen=True,
  230. )
  231. class UnevaluatedPage:
  232. """An uncompiled page."""
  233. component: Component | ComponentCallable
  234. route: str
  235. title: Var | str | None
  236. description: Var | str | None
  237. image: str
  238. on_load: EventType[()] | None
  239. meta: list[dict[str, str]]
  240. context: dict[str, Any] | None
  241. def merged_with(self, other: UnevaluatedPage) -> UnevaluatedPage:
  242. """Merge the other page into this one.
  243. Args:
  244. other: The other page to merge with.
  245. Returns:
  246. The merged page.
  247. """
  248. return dataclasses.replace(
  249. self,
  250. title=self.title if self.title is not None else other.title,
  251. description=self.description
  252. if self.description is not None
  253. else other.description,
  254. on_load=self.on_load if self.on_load is not None else other.on_load,
  255. context=self.context if self.context is not None else other.context,
  256. )
  257. @dataclasses.dataclass()
  258. class App(MiddlewareMixin, LifespanMixin):
  259. """The main Reflex app that encapsulates the backend and frontend.
  260. Every Reflex app needs an app defined in its main module.
  261. ```python
  262. # app.py
  263. import reflex as rx
  264. # Define state and pages
  265. ...
  266. app = rx.App(
  267. # Set global level style.
  268. style={...},
  269. # Set the top level theme.
  270. theme=rx.theme(accent_color="blue"),
  271. )
  272. ```
  273. """
  274. # The global [theme](https://reflex.dev/docs/styling/theming/#theme) for the entire app.
  275. theme: Component | None = dataclasses.field(
  276. default_factory=lambda: themes.theme(accent_color="blue")
  277. )
  278. # The [global style](https://reflex.dev/docs/styling/overview/#global-styles}) for the app.
  279. style: ComponentStyle = dataclasses.field(default_factory=dict)
  280. # A list of URLs to [stylesheets](https://reflex.dev/docs/styling/custom-stylesheets/) to include in the app.
  281. stylesheets: list[str] = dataclasses.field(default_factory=list)
  282. # A component that is present on every page (defaults to the Connection Error banner).
  283. overlay_component: Component | ComponentCallable | None = dataclasses.field(
  284. default=None
  285. )
  286. # Error boundary component to wrap the app with.
  287. error_boundary: ComponentCallable | None = dataclasses.field(default=None)
  288. # App wraps to be applied to the whole app. Expected to be a dictionary of (order, name) to a function that takes whether the state is enabled and optionally returns a component.
  289. app_wraps: dict[tuple[int, str], Callable[[bool], Component | None]] = (
  290. dataclasses.field(
  291. default_factory=lambda: {
  292. (55, "ErrorBoundary"): (
  293. lambda stateful: default_error_boundary() if stateful else None
  294. ),
  295. (5, "Overlay"): (
  296. lambda stateful: default_overlay_component() if stateful else None
  297. ),
  298. (4, "ExtraOverlay"): lambda stateful: extra_overlay_function(),
  299. }
  300. )
  301. )
  302. # Components to add to the head of every page.
  303. head_components: list[Component] = dataclasses.field(default_factory=list)
  304. # The Socket.IO AsyncServer instance.
  305. sio: AsyncServer | None = None
  306. # The language to add to the html root tag of every page.
  307. html_lang: str | None = None
  308. # Attributes to add to the html root tag of every page.
  309. html_custom_attrs: dict[str, str] | None = None
  310. # A map from a route to an unevaluated page.
  311. _unevaluated_pages: dict[str, UnevaluatedPage] = dataclasses.field(
  312. default_factory=dict
  313. )
  314. # A map from a page route to the component to render. Users should use `add_page`.
  315. _pages: dict[str, Component] = dataclasses.field(default_factory=dict)
  316. # A mapping of pages which created states as they were being evaluated.
  317. _stateful_pages: dict[str, None] = dataclasses.field(default_factory=dict)
  318. # The backend API object.
  319. _api: Starlette | None = None
  320. # The state class to use for the app.
  321. _state: type[BaseState] | None = None
  322. # Class to manage many client states.
  323. _state_manager: StateManager | None = None
  324. # Mapping from a route to event handlers to trigger when the page loads.
  325. _load_events: dict[str, list[IndividualEventType[()]]] = dataclasses.field(
  326. default_factory=dict
  327. )
  328. # Admin dashboard to view and manage the database.
  329. admin_dash: AdminDash | None = None
  330. # The async server name space.
  331. _event_namespace: EventNamespace | None = None
  332. # Background tasks that are currently running.
  333. _background_tasks: set[asyncio.Task] = dataclasses.field(default_factory=set)
  334. # Frontend Error Handler Function
  335. frontend_exception_handler: Callable[[Exception], None] = (
  336. default_frontend_exception_handler
  337. )
  338. # Backend Error Handler Function
  339. backend_exception_handler: Callable[
  340. [Exception], EventSpec | list[EventSpec] | None
  341. ] = default_backend_exception_handler
  342. # Put the toast provider in the app wrap.
  343. toaster: Component | None = dataclasses.field(default_factory=toast.provider)
  344. # Transform the ASGI app before running it.
  345. api_transformer: (
  346. Sequence[Callable[[ASGIApp], ASGIApp] | Starlette]
  347. | Callable[[ASGIApp], ASGIApp]
  348. | Starlette
  349. | None
  350. ) = None
  351. # FastAPI app for compatibility with FastAPI.
  352. _cached_fastapi_app: FastAPI | None = None
  353. @property
  354. @deprecated("Use `api_transformer=your_fastapi_app` instead.")
  355. def api(self) -> FastAPI:
  356. """Get the backend api.
  357. Returns:
  358. The backend api.
  359. """
  360. if self._cached_fastapi_app is None:
  361. self._cached_fastapi_app = FastAPI()
  362. console.deprecate(
  363. feature_name="App.api",
  364. reason="Set `api_transformer=your_fastapi_app` instead.",
  365. deprecation_version="0.7.9",
  366. removal_version="0.8.0",
  367. )
  368. return self._cached_fastapi_app
  369. @property
  370. def event_namespace(self) -> EventNamespace | None:
  371. """Get the event namespace.
  372. Returns:
  373. The event namespace.
  374. """
  375. return self._event_namespace
  376. def __post_init__(self):
  377. """Initialize the app.
  378. Raises:
  379. ValueError: If the event namespace is not provided in the config.
  380. Also, if there are multiple client subclasses of rx.BaseState(Subclasses of rx.BaseState should consist
  381. of the DefaultState and the client app state).
  382. """
  383. # Special case to allow test cases have multiple subclasses of rx.BaseState.
  384. if not is_testing_env() and BaseState.__subclasses__() != [State]:
  385. # Only rx.State is allowed as Base State subclass.
  386. raise ValueError(
  387. "rx.BaseState cannot be subclassed directly. Use rx.State instead"
  388. )
  389. get_config(reload=True)
  390. if "breakpoints" in self.style:
  391. set_breakpoints(self.style.pop("breakpoints"))
  392. # Set up the API.
  393. self._api = Starlette()
  394. App._add_cors(self._api)
  395. self._add_default_endpoints()
  396. for clz in App.__mro__:
  397. if clz == App:
  398. continue
  399. if issubclass(clz, AppMixin):
  400. clz._init_mixin(self)
  401. self._setup_state()
  402. # Set up the admin dash.
  403. self._setup_admin_dash()
  404. if sys.platform == "win32" and not is_prod_mode():
  405. # Hack to fix Windows hot reload issue.
  406. from reflex.utils.compat import windows_hot_reload_lifespan_hack
  407. self.register_lifespan_task(windows_hot_reload_lifespan_hack)
  408. def _enable_state(self) -> None:
  409. """Enable state for the app."""
  410. if not self._state:
  411. self._state = State
  412. self._setup_state()
  413. def _setup_state(self) -> None:
  414. """Set up the state for the app.
  415. Raises:
  416. RuntimeError: If the socket server is invalid.
  417. """
  418. if not self._state:
  419. return
  420. config = get_config()
  421. # Set up the state manager.
  422. self._state_manager = StateManager.create(state=self._state)
  423. # Set up the Socket.IO AsyncServer.
  424. if not self.sio:
  425. self.sio = AsyncServer(
  426. async_mode="asgi",
  427. cors_allowed_origins=(
  428. "*"
  429. if config.cors_allowed_origins == ["*"]
  430. else config.cors_allowed_origins
  431. ),
  432. cors_credentials=True,
  433. max_http_buffer_size=environment.REFLEX_SOCKET_MAX_HTTP_BUFFER_SIZE.get(),
  434. ping_interval=environment.REFLEX_SOCKET_INTERVAL.get(),
  435. ping_timeout=environment.REFLEX_SOCKET_TIMEOUT.get(),
  436. json=SimpleNamespace(
  437. dumps=staticmethod(format.json_dumps),
  438. loads=staticmethod(json.loads),
  439. ),
  440. transports=["websocket"],
  441. )
  442. elif getattr(self.sio, "async_mode", "") != "asgi":
  443. raise RuntimeError(
  444. f"Custom `sio` must use `async_mode='asgi'`, not '{self.sio.async_mode}'."
  445. )
  446. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  447. socket_app = EngineIOApp(self.sio, socketio_path="")
  448. namespace = config.get_event_namespace()
  449. # Create the event namespace and attach the main app. Not related to any paths.
  450. self._event_namespace = EventNamespace(namespace, self)
  451. # Register the event namespace with the socket.
  452. self.sio.register_namespace(self.event_namespace)
  453. # Mount the socket app with the API.
  454. if self._api:
  455. class HeaderMiddleware:
  456. def __init__(self, app: ASGIApp):
  457. self.app = app
  458. async def __call__(self, scope: Scope, receive: Receive, send: Send):
  459. original_send = send
  460. async def modified_send(message: Message):
  461. if message["type"] == "websocket.accept":
  462. if scope.get("subprotocols"):
  463. # The following *does* say "subprotocol" instead of "subprotocols", intentionally.
  464. message["subprotocol"] = scope["subprotocols"][0]
  465. headers = dict(message.get("headers", []))
  466. header_key = b"sec-websocket-protocol"
  467. if subprotocol := headers.get(header_key):
  468. message["headers"] = [
  469. *message.get("headers", []),
  470. (header_key, subprotocol),
  471. ]
  472. return await original_send(message)
  473. return await self.app(scope, receive, modified_send)
  474. socket_app_with_headers = HeaderMiddleware(socket_app)
  475. self._api.mount(str(constants.Endpoint.EVENT), socket_app_with_headers)
  476. # Check the exception handlers
  477. self._validate_exception_handlers()
  478. def __repr__(self) -> str:
  479. """Get the string representation of the app.
  480. Returns:
  481. The string representation of the app.
  482. """
  483. return f"<App state={self._state.__name__ if self._state else None}>"
  484. def __call__(self) -> ASGIApp:
  485. """Run the backend api instance.
  486. Raises:
  487. ValueError: If the app has not been initialized.
  488. Returns:
  489. The backend api.
  490. """
  491. # For py3.9 compatibility when redis is used, we MUST add any decorator pages
  492. # before compiling the app in a thread to avoid event loop error (REF-2172).
  493. self._apply_decorated_pages()
  494. compile_future = concurrent.futures.ThreadPoolExecutor(max_workers=1).submit(
  495. self._compile
  496. )
  497. compile_future.add_done_callback(
  498. # Force background compile errors to print eagerly
  499. lambda f: f.result()
  500. )
  501. # Wait for the compile to finish to ensure all optional endpoints are mounted.
  502. compile_future.result()
  503. if not self._api:
  504. raise ValueError("The app has not been initialized.")
  505. if self._cached_fastapi_app is not None:
  506. asgi_app = self._cached_fastapi_app
  507. asgi_app.mount("", self._api)
  508. App._add_cors(asgi_app)
  509. else:
  510. asgi_app = self._api
  511. if self.api_transformer is not None:
  512. api_transformers: Sequence[Starlette | Callable[[ASGIApp], ASGIApp]] = (
  513. [self.api_transformer]
  514. if not isinstance(self.api_transformer, Sequence)
  515. else self.api_transformer
  516. )
  517. for api_transformer in api_transformers:
  518. if isinstance(api_transformer, Starlette):
  519. # Mount the api to the fastapi app.
  520. App._add_cors(api_transformer)
  521. api_transformer.mount("", asgi_app)
  522. asgi_app = api_transformer
  523. else:
  524. # Transform the asgi app.
  525. asgi_app = api_transformer(asgi_app)
  526. top_asgi_app = Starlette(lifespan=self._run_lifespan_tasks)
  527. top_asgi_app.mount("", asgi_app)
  528. App._add_cors(top_asgi_app)
  529. return top_asgi_app
  530. def _add_default_endpoints(self):
  531. """Add default api endpoints (ping)."""
  532. # To test the server.
  533. if not self._api:
  534. return
  535. self._api.add_route(
  536. str(constants.Endpoint.PING),
  537. ping,
  538. methods=["GET"],
  539. )
  540. self._api.add_route(
  541. str(constants.Endpoint.HEALTH),
  542. health,
  543. methods=["GET"],
  544. )
  545. def _add_optional_endpoints(self):
  546. """Add optional api endpoints (_upload)."""
  547. if not self._api:
  548. return
  549. upload_is_used_marker = (
  550. prerequisites.get_backend_dir() / constants.Dirs.UPLOAD_IS_USED
  551. )
  552. if Upload.is_used or upload_is_used_marker.exists():
  553. # To upload files.
  554. self._api.add_route(
  555. str(constants.Endpoint.UPLOAD),
  556. upload(self),
  557. methods=["POST"],
  558. )
  559. # To access uploaded files.
  560. self._api.mount(
  561. str(constants.Endpoint.UPLOAD),
  562. StaticFiles(directory=get_upload_dir()),
  563. name="uploaded_files",
  564. )
  565. upload_is_used_marker.parent.mkdir(parents=True, exist_ok=True)
  566. upload_is_used_marker.touch()
  567. if codespaces.is_running_in_codespaces():
  568. self._api.add_route(
  569. str(constants.Endpoint.AUTH_CODESPACE),
  570. codespaces.auth_codespace,
  571. methods=["GET"],
  572. )
  573. if environment.REFLEX_ADD_ALL_ROUTES_ENDPOINT.get():
  574. self.add_all_routes_endpoint()
  575. @staticmethod
  576. def _add_cors(api: Starlette):
  577. """Add CORS middleware to the app.
  578. Args:
  579. api: The Starlette app to add CORS middleware to.
  580. """
  581. api.add_middleware(
  582. cors.CORSMiddleware,
  583. allow_credentials=True,
  584. allow_methods=["*"],
  585. allow_headers=["*"],
  586. allow_origins=get_config().cors_allowed_origins,
  587. )
  588. @property
  589. def state_manager(self) -> StateManager:
  590. """Get the state manager.
  591. Returns:
  592. The initialized state manager.
  593. Raises:
  594. ValueError: if the state has not been initialized.
  595. """
  596. if self._state_manager is None:
  597. raise ValueError("The state manager has not been initialized.")
  598. return self._state_manager
  599. @staticmethod
  600. def _generate_component(component: Component | ComponentCallable) -> Component:
  601. """Generate a component from a callable.
  602. Args:
  603. component: The component function to call or Component to return as-is.
  604. Returns:
  605. The generated component.
  606. """
  607. from reflex.compiler.compiler import into_component
  608. return into_component(component)
  609. def add_page(
  610. self,
  611. component: Component | ComponentCallable | None = None,
  612. route: str | None = None,
  613. title: str | Var | None = None,
  614. description: str | Var | None = None,
  615. image: str = constants.DefaultPage.IMAGE,
  616. on_load: EventType[()] | None = None,
  617. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  618. context: dict[str, Any] | None = None,
  619. ):
  620. """Add a page to the app.
  621. If the component is a callable, by default the route is the name of the
  622. function. Otherwise, a route must be provided.
  623. Args:
  624. component: The component to display at the page.
  625. route: The route to display the component at.
  626. title: The title of the page.
  627. description: The description of the page.
  628. image: The image to display on the page.
  629. on_load: The event handler(s) that will be called each time the page load.
  630. meta: The metadata of the page.
  631. context: Values passed to page for custom page-specific logic.
  632. Raises:
  633. PageValueError: When the component is not set for a non-404 page.
  634. RouteValueError: When the specified route name already exists.
  635. """
  636. # If the route is not set, get it from the callable.
  637. if route is None:
  638. if not isinstance(component, Callable):
  639. raise exceptions.RouteValueError(
  640. "Route must be set if component is not a callable."
  641. )
  642. # Format the route.
  643. route = format.format_route(component.__name__)
  644. else:
  645. route = format.format_route(route, format_case=False)
  646. if route == constants.Page404.SLUG:
  647. if component is None:
  648. component = Default404Page.create()
  649. component = wait_for_client_redirect(self._generate_component(component))
  650. title = title or constants.Page404.TITLE
  651. description = description or constants.Page404.DESCRIPTION
  652. image = image or constants.Page404.IMAGE
  653. else:
  654. if component is None:
  655. raise exceptions.PageValueError(
  656. "Component must be set for a non-404 page."
  657. )
  658. # Check if the route given is valid
  659. verify_route_validity(route)
  660. unevaluated_page = UnevaluatedPage(
  661. component=component,
  662. route=route,
  663. title=title,
  664. description=description,
  665. image=image,
  666. on_load=on_load,
  667. meta=meta,
  668. context=context,
  669. )
  670. if route in self._unevaluated_pages:
  671. if self._unevaluated_pages[route].component is component:
  672. unevaluated_page = unevaluated_page.merged_with(
  673. self._unevaluated_pages[route]
  674. )
  675. console.warn(
  676. f"Page {route} is being redefined with the same component."
  677. )
  678. else:
  679. route_name = (
  680. f"`{route}` or `/`"
  681. if route == constants.PageNames.INDEX_ROUTE
  682. else f"`{route}`"
  683. )
  684. existing_component = self._unevaluated_pages[route].component
  685. raise exceptions.RouteValueError(
  686. f"Tried to add page {readable_name_from_component(component)} with route {route_name} but "
  687. f"page {readable_name_from_component(existing_component)} with the same route already exists. "
  688. "Make sure you do not have two pages with the same route."
  689. )
  690. # Setup dynamic args for the route.
  691. # this state assignment is only required for tests using the deprecated state kwarg for App
  692. state = self._state if self._state else State
  693. state.setup_dynamic_args(get_route_args(route))
  694. if on_load:
  695. self._load_events[route] = (
  696. on_load if isinstance(on_load, list) else [on_load]
  697. )
  698. self._unevaluated_pages[route] = unevaluated_page
  699. def _compile_page(self, route: str, save_page: bool = True):
  700. """Compile a page.
  701. Args:
  702. route: The route of the page to compile.
  703. save_page: If True, the compiled page is saved to self._pages.
  704. """
  705. n_states_before = len(all_base_state_classes)
  706. component, enable_state = compiler.compile_unevaluated_page(
  707. route, self._unevaluated_pages[route], self._state, self.style, self.theme
  708. )
  709. # Indicate that the app should use state.
  710. if enable_state:
  711. self._enable_state()
  712. # Indicate that evaluating this page creates one or more state classes.
  713. if len(all_base_state_classes) > n_states_before:
  714. self._stateful_pages[route] = None
  715. # Add the page.
  716. self._check_routes_conflict(route)
  717. if save_page:
  718. self._pages[route] = component
  719. def get_load_events(self, route: str) -> list[IndividualEventType[()]]:
  720. """Get the load events for a route.
  721. Args:
  722. route: The route to get the load events for.
  723. Returns:
  724. The load events for the route.
  725. """
  726. route = route.lstrip("/")
  727. if route == "":
  728. route = constants.PageNames.INDEX_ROUTE
  729. return self._load_events.get(route, [])
  730. def _check_routes_conflict(self, new_route: str):
  731. """Verify if there is any conflict between the new route and any existing route.
  732. Based on conflicts that NextJS would throw if not intercepted.
  733. Raises:
  734. RouteValueError: exception showing which conflict exist with the route to be added
  735. Args:
  736. new_route: the route being newly added.
  737. """
  738. from reflex.utils.exceptions import RouteValueError
  739. if "[" not in new_route:
  740. return
  741. segments = (
  742. constants.RouteRegex.SINGLE_SEGMENT,
  743. constants.RouteRegex.DOUBLE_SEGMENT,
  744. constants.RouteRegex.SINGLE_CATCHALL_SEGMENT,
  745. constants.RouteRegex.DOUBLE_CATCHALL_SEGMENT,
  746. )
  747. for route in self._pages:
  748. replaced_route = replace_brackets_with_keywords(route)
  749. for rw, r, nr in zip(
  750. replaced_route.split("/"),
  751. route.split("/"),
  752. new_route.split("/"),
  753. strict=False,
  754. ):
  755. if rw in segments and r != nr:
  756. # If the slugs in the segments of both routes are not the same, then the route is invalid
  757. raise RouteValueError(
  758. f"You cannot use different slug names for the same dynamic path in {route} and {new_route} ('{r}' != '{nr}')"
  759. )
  760. elif rw not in segments and r != nr:
  761. # if the section being compared in both routes is not a dynamic segment(i.e not wrapped in brackets)
  762. # then we are guaranteed that the route is valid and there's no need checking the rest.
  763. # eg. /posts/[id]/info/[slug1] and /posts/[id]/info1/[slug1] is always going to be valid since
  764. # info1 will break away into its own tree.
  765. break
  766. def add_custom_404_page(
  767. self,
  768. component: Component | ComponentCallable | None = None,
  769. title: str = constants.Page404.TITLE,
  770. image: str = constants.Page404.IMAGE,
  771. description: str = constants.Page404.DESCRIPTION,
  772. on_load: EventType[()] | None = None,
  773. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  774. ):
  775. """Define a custom 404 page for any url having no match.
  776. If there is no page defined on 'index' route, add the 404 page to it.
  777. If there is no global catchall defined, add the 404 page with a catchall.
  778. Args:
  779. component: The component to display at the page.
  780. title: The title of the page.
  781. image: The image to display on the page.
  782. description: The description of the page.
  783. on_load: The event handler(s) that will be called each time the page load.
  784. meta: The metadata of the page.
  785. """
  786. console.deprecate(
  787. feature_name="App.add_custom_404_page",
  788. reason=f"Use app.add_page(component, route='/{constants.Page404.SLUG}') instead.",
  789. deprecation_version="0.6.7",
  790. removal_version="0.8.0",
  791. )
  792. self.add_page(
  793. component=component,
  794. route=constants.Page404.SLUG,
  795. title=title or constants.Page404.TITLE,
  796. image=image or constants.Page404.IMAGE,
  797. description=description or constants.Page404.DESCRIPTION,
  798. on_load=on_load,
  799. meta=meta,
  800. )
  801. def _setup_admin_dash(self):
  802. """Setup the admin dash."""
  803. try:
  804. from starlette_admin.contrib.sqla.admin import Admin
  805. from starlette_admin.contrib.sqla.view import ModelView
  806. except ImportError:
  807. return
  808. # Get the admin dash.
  809. if not self._api:
  810. return
  811. admin_dash = self.admin_dash
  812. if admin_dash and admin_dash.models:
  813. # Build the admin dashboard
  814. admin = (
  815. admin_dash.admin
  816. if admin_dash.admin
  817. else Admin(
  818. engine=Model.get_db_engine(),
  819. title="Reflex Admin Dashboard",
  820. logo_url="https://reflex.dev/Reflex.svg",
  821. )
  822. )
  823. for model in admin_dash.models:
  824. view = admin_dash.view_overrides.get(model, ModelView)
  825. admin.add_view(view(model))
  826. admin.mount_to(self._api)
  827. def _get_frontend_packages(self, imports: dict[str, set[ImportVar]]):
  828. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  829. Args:
  830. imports: A dictionary containing the imports used in the current page.
  831. Example:
  832. >>> _get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  833. """
  834. page_imports = {
  835. i
  836. for i, tags in imports.items()
  837. if i not in constants.PackageJson.DEPENDENCIES
  838. and i not in constants.PackageJson.DEV_DEPENDENCIES
  839. and not any(i.startswith(prefix) for prefix in ["/", "$/", ".", "next/"])
  840. and i != ""
  841. and any(tag.install for tag in tags)
  842. }
  843. pinned = {i.rpartition("@")[0] for i in page_imports if "@" in i}
  844. page_imports = {i for i in page_imports if i not in pinned}
  845. frontend_packages = get_config().frontend_packages
  846. _frontend_packages = []
  847. for package in frontend_packages:
  848. if package in (get_config().tailwind or {}).get("plugins", []):
  849. console.warn(
  850. f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`"
  851. )
  852. continue
  853. if package in page_imports:
  854. console.warn(
  855. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  856. )
  857. continue
  858. _frontend_packages.append(package)
  859. page_imports.update(_frontend_packages)
  860. prerequisites.install_frontend_packages(page_imports, get_config())
  861. def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component:
  862. for component in tuple(app_wrappers.values()):
  863. app_wrappers.update(component._get_all_app_wrap_components())
  864. order = sorted(app_wrappers, key=lambda k: k[0], reverse=True)
  865. root = parent = copy.deepcopy(app_wrappers[order[0]])
  866. for key in order[1:]:
  867. child = copy.deepcopy(app_wrappers[key])
  868. parent.children.append(child)
  869. parent = child
  870. return root
  871. def _should_compile(self) -> bool:
  872. """Check if the app should be compiled.
  873. Returns:
  874. Whether the app should be compiled.
  875. """
  876. # Check the environment variable.
  877. if environment.REFLEX_SKIP_COMPILE.get():
  878. return False
  879. nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
  880. # Check the nocompile file.
  881. if nocompile.exists():
  882. # Delete the nocompile file
  883. nocompile.unlink(missing_ok=True)
  884. return False
  885. # By default, compile the app.
  886. return True
  887. def _add_overlay_to_component(self, component: Component) -> Component:
  888. if self.overlay_component is None:
  889. return component
  890. children = component.children
  891. overlay_component = self._generate_component(self.overlay_component)
  892. if children[0] == overlay_component:
  893. return component
  894. # recreate OverlayFragment with overlay_component as first child
  895. component = OverlayFragment.create(overlay_component, *children)
  896. return component
  897. def _setup_overlay_component(self):
  898. """If a State is not used and no overlay_component is specified, do not render the connection modal."""
  899. if self._state is None and self.overlay_component is default_overlay_component:
  900. self.overlay_component = None
  901. for k, component in self._pages.items():
  902. self._pages[k] = self._add_overlay_to_component(component)
  903. def _setup_sticky_badge(self):
  904. """Add the sticky badge to the app."""
  905. from reflex.components.component import memo
  906. @memo
  907. def memoized_badge():
  908. sticky_badge = sticky()
  909. sticky_badge._add_style_recursive({})
  910. return sticky_badge
  911. self.app_wraps[(0, "StickyBadge")] = lambda _: memoized_badge()
  912. def _apply_decorated_pages(self):
  913. """Add @rx.page decorated pages to the app.
  914. This has to be done in the MainThread for py38 and py39 compatibility, so the
  915. decorated pages are added to the app before the app is compiled (in a thread)
  916. to workaround REF-2172.
  917. This can move back into `compile_` when py39 support is dropped.
  918. """
  919. app_name = get_config().app_name
  920. # Add the @rx.page decorated pages to collect on_load events.
  921. for render, kwargs in DECORATED_PAGES[app_name]:
  922. self.add_page(render, **kwargs)
  923. def _validate_var_dependencies(self, state: type[BaseState] | None = None) -> None:
  924. """Validate the dependencies of the vars in the app.
  925. Args:
  926. state: The state to validate the dependencies for.
  927. Raises:
  928. VarDependencyError: When a computed var has an invalid dependency.
  929. """
  930. if not self._state:
  931. return
  932. if not state:
  933. state = self._state
  934. for var in state.computed_vars.values():
  935. if not var._cache:
  936. continue
  937. deps = var._deps(objclass=state)
  938. for state_name, dep_set in deps.items():
  939. state_cls = (
  940. state.get_root_state().get_class_substate(state_name)
  941. if state_name != state.get_full_name()
  942. else state
  943. )
  944. for dep in dep_set:
  945. if dep not in state_cls.vars and dep not in state_cls.backend_vars:
  946. raise exceptions.VarDependencyError(
  947. f"ComputedVar {var._js_expr} on state {state.__name__} has an invalid dependency {state_name}.{dep}"
  948. )
  949. for substate in state.class_subclasses:
  950. self._validate_var_dependencies(substate)
  951. def _compile(self, export: bool = False, dry_run: bool = False):
  952. """Compile the app and output it to the pages folder.
  953. Args:
  954. export: Whether to compile the app for export.
  955. dry_run: Whether to compile the app without saving it.
  956. Raises:
  957. ReflexRuntimeError: When any page uses state, but no rx.State subclass is defined.
  958. """
  959. from reflex.utils.exceptions import ReflexRuntimeError
  960. self._pages = {}
  961. def get_compilation_time() -> str:
  962. return str(datetime.now().time()).split(".")[0]
  963. should_compile = self._should_compile()
  964. backend_dir = prerequisites.get_backend_dir()
  965. if not dry_run and not should_compile and backend_dir.exists():
  966. stateful_pages_marker = backend_dir / constants.Dirs.STATEFUL_PAGES
  967. if stateful_pages_marker.exists():
  968. with stateful_pages_marker.open("r") as f:
  969. stateful_pages = json.load(f)
  970. for route in stateful_pages:
  971. console.debug(f"BE Evaluating stateful page: {route}")
  972. self._compile_page(route, save_page=False)
  973. self._enable_state()
  974. self._add_optional_endpoints()
  975. return
  976. # Render a default 404 page if the user didn't supply one
  977. if constants.Page404.SLUG not in self._unevaluated_pages:
  978. self.add_page(route=constants.Page404.SLUG)
  979. # Fix up the style.
  980. self.style = evaluate_style_namespaces(self.style)
  981. # Add the app wrappers.
  982. app_wrappers: dict[tuple[int, str], Component] = {
  983. # Default app wrap component renders {children}
  984. (0, "AppWrap"): AppWrap.create()
  985. }
  986. if self.theme is not None:
  987. # If a theme component was provided, wrap the app with it
  988. app_wrappers[(20, "Theme")] = self.theme
  989. # Get the env mode.
  990. config = get_config()
  991. if config.react_strict_mode:
  992. app_wrappers[(200, "StrictMode")] = StrictMode.create()
  993. if not should_compile and not dry_run:
  994. with console.timing("Evaluate Pages (Backend)"):
  995. for route in self._unevaluated_pages:
  996. console.debug(f"Evaluating page: {route}")
  997. self._compile_page(route, save_page=should_compile)
  998. # Save the pages which created new states at eval time.
  999. self._write_stateful_pages_marker()
  1000. # Add the optional endpoints (_upload)
  1001. self._add_optional_endpoints()
  1002. return
  1003. # Create a progress bar.
  1004. progress = Progress(
  1005. *Progress.get_default_columns()[:-1],
  1006. MofNCompleteColumn(),
  1007. TimeElapsedColumn(),
  1008. )
  1009. # try to be somewhat accurate - but still not 100%
  1010. adhoc_steps_without_executor = 7
  1011. fixed_pages_within_executor = 5
  1012. progress.start()
  1013. task = progress.add_task(
  1014. f"[{get_compilation_time()}] Compiling:",
  1015. total=len(self._pages)
  1016. + (len(self._unevaluated_pages) * 2)
  1017. + fixed_pages_within_executor
  1018. + adhoc_steps_without_executor,
  1019. )
  1020. with console.timing("Evaluate Pages (Frontend)"):
  1021. performance_metrics: list[tuple[str, float]] = []
  1022. for route in self._unevaluated_pages:
  1023. console.debug(f"Evaluating page: {route}")
  1024. start = timer()
  1025. self._compile_page(route, save_page=should_compile)
  1026. end = timer()
  1027. performance_metrics.append((route, end - start))
  1028. progress.advance(task)
  1029. console.debug(
  1030. "Slowest pages:\n"
  1031. + "\n".join(
  1032. f"{route}: {time * 1000:.1f}ms"
  1033. for route, time in sorted(
  1034. performance_metrics, key=lambda x: x[1], reverse=True
  1035. )[:10]
  1036. )
  1037. )
  1038. # Save the pages which created new states at eval time.
  1039. self._write_stateful_pages_marker()
  1040. # Add the optional endpoints (_upload)
  1041. self._add_optional_endpoints()
  1042. self._validate_var_dependencies()
  1043. self._setup_overlay_component()
  1044. if config.show_built_with_reflex is None:
  1045. if (
  1046. get_compile_context() == constants.CompileContext.DEPLOY
  1047. and prerequisites.get_user_tier() in ["pro", "team", "enterprise"]
  1048. ):
  1049. config.show_built_with_reflex = False
  1050. else:
  1051. config.show_built_with_reflex = True
  1052. if is_prod_mode() and config.show_built_with_reflex:
  1053. self._setup_sticky_badge()
  1054. progress.advance(task)
  1055. # Store the compile results.
  1056. compile_results: list[tuple[str, str]] = []
  1057. progress.advance(task)
  1058. # Track imports found.
  1059. all_imports = {}
  1060. # This has to happen before compiling stateful components as that
  1061. # prevents recursive functions from reaching all components.
  1062. for component in self._pages.values():
  1063. # Add component._get_all_imports() to all_imports.
  1064. all_imports.update(component._get_all_imports())
  1065. # Add the app wrappers from this component.
  1066. app_wrappers.update(component._get_all_app_wrap_components())
  1067. if (toaster := self.toaster) is not None:
  1068. from reflex.components.component import memo
  1069. @memo
  1070. def memoized_toast_provider():
  1071. return toaster
  1072. toast_provider = Fragment.create(memoized_toast_provider())
  1073. app_wrappers[(1, "ToasterProvider")] = toast_provider
  1074. # Add the app wraps to the app.
  1075. for key, app_wrap in self.app_wraps.items():
  1076. component = app_wrap(self._state is not None)
  1077. if component is not None:
  1078. app_wrappers[key] = component
  1079. if self.error_boundary:
  1080. from reflex.compiler.compiler import into_component
  1081. console.deprecate(
  1082. feature_name="App.error_boundary",
  1083. reason="Use app_wraps instead.",
  1084. deprecation_version="0.7.1",
  1085. removal_version="0.8.0",
  1086. )
  1087. app_wrappers[(55, "ErrorBoundary")] = into_component(self.error_boundary)
  1088. # Perform auto-memoization of stateful components.
  1089. with console.timing("Auto-memoize StatefulComponents"):
  1090. (
  1091. stateful_components_path,
  1092. stateful_components_code,
  1093. page_components,
  1094. ) = compiler.compile_stateful_components(self._pages.values())
  1095. progress.advance(task)
  1096. # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State.
  1097. if code_uses_state_contexts(stateful_components_code) and self._state is None:
  1098. raise ReflexRuntimeError(
  1099. "To access rx.State in frontend components, at least one "
  1100. "subclass of rx.State must be defined in the app."
  1101. )
  1102. compile_results.append((stateful_components_path, stateful_components_code))
  1103. progress.advance(task)
  1104. # Compile the root document before fork.
  1105. compile_results.append(
  1106. compiler.compile_document_root(
  1107. self.head_components,
  1108. html_lang=self.html_lang,
  1109. html_custom_attrs=(
  1110. {**self.html_custom_attrs} if self.html_custom_attrs else {}
  1111. ),
  1112. )
  1113. )
  1114. progress.advance(task)
  1115. # Copy the assets.
  1116. assets_src = Path.cwd() / constants.Dirs.APP_ASSETS
  1117. if assets_src.is_dir() and not dry_run:
  1118. with console.timing("Copy assets"):
  1119. path_ops.update_directory_tree(
  1120. src=assets_src,
  1121. dest=(
  1122. Path.cwd() / prerequisites.get_web_dir() / constants.Dirs.PUBLIC
  1123. ),
  1124. )
  1125. executor = ExecutorType.get_executor_from_environment()
  1126. for route, component in zip(self._pages, page_components, strict=True):
  1127. ExecutorSafeFunctions.COMPONENTS[route] = component
  1128. ExecutorSafeFunctions.STATE = self._state
  1129. with console.timing("Compile to Javascript"), executor as executor:
  1130. result_futures: list[concurrent.futures.Future[tuple[str, str]]] = []
  1131. def _submit_work(fn: Callable[..., tuple[str, str]], *args, **kwargs):
  1132. f = executor.submit(fn, *args, **kwargs)
  1133. f.add_done_callback(lambda _: progress.advance(task))
  1134. result_futures.append(f)
  1135. # Compile the pre-compiled pages.
  1136. for route in self._pages:
  1137. _submit_work(
  1138. ExecutorSafeFunctions.compile_page,
  1139. route,
  1140. )
  1141. # Compile the root stylesheet with base styles.
  1142. _submit_work(compiler.compile_root_stylesheet, self.stylesheets)
  1143. # Compile the theme.
  1144. _submit_work(compile_theme, self.style)
  1145. # Compile the Tailwind config.
  1146. if config.tailwind is not None:
  1147. config.tailwind["content"] = config.tailwind.get(
  1148. "content", constants.Tailwind.CONTENT
  1149. )
  1150. _submit_work(compiler.compile_tailwind, config.tailwind)
  1151. else:
  1152. _submit_work(compiler.remove_tailwind_from_postcss)
  1153. # Wait for all compilation tasks to complete.
  1154. compile_results.extend(
  1155. future.result()
  1156. for future in concurrent.futures.as_completed(result_futures)
  1157. )
  1158. app_root = self._app_root(app_wrappers=app_wrappers)
  1159. # Get imports from AppWrap components.
  1160. all_imports.update(app_root._get_all_imports())
  1161. progress.advance(task)
  1162. # Compile the contexts.
  1163. compile_results.append(
  1164. compiler.compile_contexts(self._state, self.theme),
  1165. )
  1166. if self.theme is not None:
  1167. # Fix #2992 by removing the top-level appearance prop
  1168. self.theme.appearance = None
  1169. progress.advance(task)
  1170. # Compile the app root.
  1171. compile_results.append(
  1172. compiler.compile_app(app_root),
  1173. )
  1174. progress.advance(task)
  1175. # Compile custom components.
  1176. (
  1177. custom_components_output,
  1178. custom_components_result,
  1179. custom_components_imports,
  1180. ) = compiler.compile_components(set(CUSTOM_COMPONENTS.values()))
  1181. compile_results.append((custom_components_output, custom_components_result))
  1182. all_imports.update(custom_components_imports)
  1183. progress.advance(task)
  1184. progress.stop()
  1185. if dry_run:
  1186. return
  1187. # Install frontend packages.
  1188. with console.timing("Install Frontend Packages"):
  1189. self._get_frontend_packages(all_imports)
  1190. # Setup the next.config.js
  1191. transpile_packages = [
  1192. package
  1193. for package, import_vars in all_imports.items()
  1194. if any(import_var.transpile for import_var in import_vars)
  1195. ]
  1196. prerequisites.update_next_config(
  1197. export=export,
  1198. transpile_packages=transpile_packages,
  1199. )
  1200. if is_prod_mode():
  1201. # Empty the .web pages directory.
  1202. compiler.purge_web_pages_dir()
  1203. else:
  1204. # In dev mode, delete removed pages and update existing pages.
  1205. keep_files = [Path(output_path) for output_path, _ in compile_results]
  1206. for p in Path(prerequisites.get_web_dir() / constants.Dirs.PAGES).rglob(
  1207. "*"
  1208. ):
  1209. if p.is_file() and p not in keep_files:
  1210. # Remove pages that are no longer in the app.
  1211. p.unlink()
  1212. with console.timing("Write to Disk"):
  1213. for output_path, code in compile_results:
  1214. compiler_utils.write_page(output_path, code)
  1215. def _write_stateful_pages_marker(self):
  1216. """Write list of routes that create dynamic states for the backend to use later."""
  1217. if self._state is not None:
  1218. stateful_pages_marker = (
  1219. prerequisites.get_backend_dir() / constants.Dirs.STATEFUL_PAGES
  1220. )
  1221. stateful_pages_marker.parent.mkdir(parents=True, exist_ok=True)
  1222. with stateful_pages_marker.open("w") as f:
  1223. json.dump(list(self._stateful_pages), f)
  1224. def add_all_routes_endpoint(self):
  1225. """Add an endpoint to the app that returns all the routes."""
  1226. if not self._api:
  1227. return
  1228. async def all_routes(_request: Request) -> Response:
  1229. return JSONResponse(list(self._unevaluated_pages.keys()))
  1230. self._api.add_route(
  1231. str(constants.Endpoint.ALL_ROUTES), all_routes, methods=["GET"]
  1232. )
  1233. @contextlib.asynccontextmanager
  1234. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1235. """Modify the state out of band.
  1236. Args:
  1237. token: The token to modify the state for.
  1238. Yields:
  1239. The state to modify.
  1240. Raises:
  1241. RuntimeError: If the app has not been initialized yet.
  1242. """
  1243. if self.event_namespace is None:
  1244. raise RuntimeError("App has not been initialized yet.")
  1245. # Get exclusive access to the state.
  1246. async with self.state_manager.modify_state(token) as state:
  1247. # No other event handler can modify the state while in this context.
  1248. yield state
  1249. delta = await state._get_resolved_delta()
  1250. if delta:
  1251. # When the state is modified reset dirty status and emit the delta to the frontend.
  1252. state._clean()
  1253. await self.event_namespace.emit_update(
  1254. update=StateUpdate(delta=delta),
  1255. sid=state.router.session.session_id,
  1256. )
  1257. def _process_background(
  1258. self, state: BaseState, event: Event
  1259. ) -> asyncio.Task | None:
  1260. """Process an event in the background and emit updates as they arrive.
  1261. Args:
  1262. state: The state to process the event for.
  1263. event: The event to process.
  1264. Returns:
  1265. Task if the event was backgroundable, otherwise None
  1266. """
  1267. substate, handler = state._get_event_handler(event)
  1268. if not handler.is_background:
  1269. return None
  1270. async def _coro():
  1271. """Coroutine to process the event and emit updates inside an asyncio.Task.
  1272. Raises:
  1273. RuntimeError: If the app has not been initialized yet.
  1274. """
  1275. if self.event_namespace is None:
  1276. raise RuntimeError("App has not been initialized yet.")
  1277. # Process the event.
  1278. async for update in state._process_event(
  1279. handler=handler, state=substate, payload=event.payload
  1280. ):
  1281. # Postprocess the event.
  1282. update = await self._postprocess(state, event, update)
  1283. # Send the update to the client.
  1284. await self.event_namespace.emit_update(
  1285. update=update,
  1286. sid=state.router.session.session_id,
  1287. )
  1288. task = asyncio.create_task(_coro())
  1289. self._background_tasks.add(task)
  1290. # Clean up task from background_tasks set when complete.
  1291. task.add_done_callback(self._background_tasks.discard)
  1292. return task
  1293. def _validate_exception_handlers(self):
  1294. """Validate the custom event exception handlers for front- and backend.
  1295. Raises:
  1296. ValueError: If the custom exception handlers are invalid.
  1297. """
  1298. frontend_arg_spec = {
  1299. "exception": Exception,
  1300. }
  1301. backend_arg_spec = {
  1302. "exception": Exception,
  1303. }
  1304. for handler_domain, handler_fn, handler_spec in zip(
  1305. ["frontend", "backend"],
  1306. [self.frontend_exception_handler, self.backend_exception_handler],
  1307. [
  1308. frontend_arg_spec,
  1309. backend_arg_spec,
  1310. ],
  1311. strict=True,
  1312. ):
  1313. if hasattr(handler_fn, "__name__"):
  1314. _fn_name = handler_fn.__name__
  1315. else:
  1316. _fn_name = type(handler_fn).__name__
  1317. if isinstance(handler_fn, functools.partial):
  1318. raise ValueError(
  1319. f"Provided custom {handler_domain} exception handler `{_fn_name}` is a partial function. Please provide a named function instead."
  1320. )
  1321. if not callable(handler_fn):
  1322. raise ValueError(
  1323. f"Provided custom {handler_domain} exception handler `{_fn_name}` is not a function."
  1324. )
  1325. # Allow named functions only as lambda functions cannot be introspected
  1326. if _fn_name == "<lambda>":
  1327. raise ValueError(
  1328. f"Provided custom {handler_domain} exception handler `{_fn_name}` is a lambda function. Please use a named function instead."
  1329. )
  1330. # Check if the function has the necessary annotations and types in the right order
  1331. argspec = inspect.getfullargspec(handler_fn)
  1332. arg_annotations = {
  1333. k: eval(v) if isinstance(v, str) else v
  1334. for k, v in argspec.annotations.items()
  1335. if k not in ["args", "kwargs", "return"]
  1336. }
  1337. for required_arg_index, required_arg in enumerate(handler_spec):
  1338. if required_arg not in arg_annotations:
  1339. raise ValueError(
  1340. f"Provided custom {handler_domain} exception handler `{_fn_name}` does not take the required argument `{required_arg}`"
  1341. )
  1342. elif (
  1343. not list(arg_annotations.keys())[required_arg_index] == required_arg
  1344. ):
  1345. raise ValueError(
  1346. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong argument order."
  1347. f"Expected `{required_arg}` as the {required_arg_index + 1} argument but got `{list(arg_annotations.keys())[required_arg_index]}`"
  1348. )
  1349. if not issubclass(arg_annotations[required_arg], Exception):
  1350. raise ValueError(
  1351. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong type for {required_arg} argument."
  1352. f"Expected to be `Exception` but got `{arg_annotations[required_arg]}`"
  1353. )
  1354. # Check if the return type is valid for backend exception handler
  1355. if handler_domain == "backend":
  1356. sig = inspect.signature(self.backend_exception_handler)
  1357. return_type = (
  1358. eval(sig.return_annotation)
  1359. if isinstance(sig.return_annotation, str)
  1360. else sig.return_annotation
  1361. )
  1362. valid = bool(
  1363. return_type == EventSpec
  1364. or return_type == EventSpec | None
  1365. or return_type == list[EventSpec]
  1366. or return_type == inspect.Signature.empty
  1367. or return_type is None
  1368. )
  1369. if not valid:
  1370. raise ValueError(
  1371. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong return type."
  1372. f"Expected `EventSpec | list[EventSpec] | None` but got `{return_type}`"
  1373. )
  1374. async def process(
  1375. app: App, event: Event, sid: str, headers: dict, client_ip: str
  1376. ) -> AsyncIterator[StateUpdate]:
  1377. """Process an event.
  1378. Args:
  1379. app: The app to process the event for.
  1380. event: The event to process.
  1381. sid: The Socket.IO session id.
  1382. headers: The client headers.
  1383. client_ip: The client_ip.
  1384. Raises:
  1385. Exception: If a reflex specific error occurs during processing the event.
  1386. Yields:
  1387. The state updates after processing the event.
  1388. """
  1389. from reflex.utils import telemetry
  1390. try:
  1391. # Add request data to the state.
  1392. router_data = event.router_data
  1393. router_data.update(
  1394. {
  1395. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  1396. constants.RouteVar.CLIENT_TOKEN: event.token,
  1397. constants.RouteVar.SESSION_ID: sid,
  1398. constants.RouteVar.HEADERS: headers,
  1399. constants.RouteVar.CLIENT_IP: client_ip,
  1400. }
  1401. )
  1402. # Get the state for the session exclusively.
  1403. async with app.state_manager.modify_state(event.substate_token) as state:
  1404. # When this is a brand new instance of the state, signal the
  1405. # frontend to reload before processing it.
  1406. if (
  1407. not state.router_data
  1408. and event.name != get_hydrate_event(state)
  1409. and app.event_namespace is not None
  1410. ):
  1411. await asyncio.create_task(
  1412. app.event_namespace.emit(
  1413. "reload",
  1414. data=event,
  1415. to=sid,
  1416. )
  1417. )
  1418. return
  1419. # re-assign only when the value is different
  1420. if state.router_data != router_data:
  1421. # assignment will recurse into substates and force recalculation of
  1422. # dependent ComputedVar (dynamic route variables)
  1423. state.router_data = router_data
  1424. state.router = RouterData(router_data)
  1425. # Preprocess the event.
  1426. update = await app._preprocess(state, event)
  1427. # If there was an update, yield it.
  1428. if update is not None:
  1429. yield update
  1430. # Only process the event if there is no update.
  1431. else:
  1432. if app._process_background(state, event) is not None:
  1433. # `final=True` allows the frontend send more events immediately.
  1434. yield StateUpdate(final=True)
  1435. else:
  1436. # Process the event synchronously.
  1437. async for update in state._process(event):
  1438. # Postprocess the event.
  1439. update = await app._postprocess(state, event, update)
  1440. # Yield the update.
  1441. yield update
  1442. except Exception as ex:
  1443. telemetry.send_error(ex, context="backend")
  1444. app.backend_exception_handler(ex)
  1445. raise
  1446. async def ping(_request: Request) -> Response:
  1447. """Test API endpoint.
  1448. Args:
  1449. _request: The Starlette request object.
  1450. Returns:
  1451. The response.
  1452. """
  1453. return JSONResponse("pong")
  1454. async def health(_request: Request) -> JSONResponse:
  1455. """Health check endpoint to assess the status of the database and Redis services.
  1456. Args:
  1457. _request: The Starlette request object.
  1458. Returns:
  1459. JSONResponse: A JSON object with the health status:
  1460. - "status" (bool): Overall health, True if all checks pass.
  1461. - "db" (bool or str): Database status - True, False, or "NA".
  1462. - "redis" (bool or str): Redis status - True, False, or "NA".
  1463. """
  1464. health_status = {"status": True}
  1465. status_code = 200
  1466. tasks = []
  1467. if prerequisites.check_db_used():
  1468. tasks.append(get_db_status())
  1469. if prerequisites.check_redis_used():
  1470. tasks.append(prerequisites.get_redis_status())
  1471. results = await asyncio.gather(*tasks)
  1472. for result in results:
  1473. health_status |= result
  1474. if "redis" in health_status and health_status["redis"] is None:
  1475. health_status["redis"] = False
  1476. if not all(health_status.values()):
  1477. health_status["status"] = False
  1478. status_code = 503
  1479. return JSONResponse(content=health_status, status_code=status_code)
  1480. def upload(app: App):
  1481. """Upload a file.
  1482. Args:
  1483. app: The app to upload the file for.
  1484. Returns:
  1485. The upload function.
  1486. """
  1487. async def upload_file(request: Request):
  1488. """Upload a file.
  1489. Args:
  1490. request: The Starlette request object.
  1491. Returns:
  1492. StreamingResponse yielding newline-delimited JSON of StateUpdate
  1493. emitted by the upload handler.
  1494. Raises:
  1495. UploadValueError: if there are no args with supported annotation.
  1496. UploadTypeError: if a background task is used as the handler.
  1497. HTTPException: when the request does not include token / handler headers.
  1498. """
  1499. from reflex.utils.exceptions import UploadTypeError, UploadValueError
  1500. # Get the files from the request.
  1501. try:
  1502. files = await request.form()
  1503. except ClientDisconnect:
  1504. return Response() # user cancelled
  1505. files = files.getlist("files")
  1506. if not files:
  1507. raise UploadValueError("No files were uploaded.")
  1508. token = request.headers.get("reflex-client-token")
  1509. handler = request.headers.get("reflex-event-handler")
  1510. if not token or not handler:
  1511. raise HTTPException(
  1512. status_code=400,
  1513. detail="Missing reflex-client-token or reflex-event-handler header.",
  1514. )
  1515. # Get the state for the session.
  1516. substate_token = _substate_key(token, handler.rpartition(".")[0])
  1517. state = await app.state_manager.get_state(substate_token)
  1518. # get the current session ID
  1519. # get the current state(parent state/substate)
  1520. path = handler.split(".")[:-1]
  1521. current_state = state.get_substate(path)
  1522. handler_upload_param = ()
  1523. # get handler function
  1524. func = getattr(type(current_state), handler.split(".")[-1])
  1525. # check if there exists any handler args with annotation, list[UploadFile]
  1526. if isinstance(func, EventHandler):
  1527. if func.is_background:
  1528. raise UploadTypeError(
  1529. f"@rx.event(background=True) is not supported for upload handler `{handler}`.",
  1530. )
  1531. func = func.fn
  1532. if isinstance(func, functools.partial):
  1533. func = func.func
  1534. for k, v in get_type_hints(func).items():
  1535. if types.is_generic_alias(v) and types._issubclass(
  1536. get_args(v)[0],
  1537. UploadFile,
  1538. ):
  1539. handler_upload_param = (k, v)
  1540. break
  1541. if not handler_upload_param:
  1542. raise UploadValueError(
  1543. f"`{handler}` handler should have a parameter annotated as "
  1544. "list[rx.UploadFile]"
  1545. )
  1546. # Make a copy of the files as they are closed after the request.
  1547. # This behaviour changed from fastapi 0.103.0 to 0.103.1 as the
  1548. # AsyncExitStack was removed from the request scope and is now
  1549. # part of the routing function which closes this before the
  1550. # event is handled.
  1551. file_copies = []
  1552. for file in files:
  1553. if not isinstance(file, StarletteUploadFile):
  1554. raise UploadValueError(
  1555. "Uploaded file is not an UploadFile." + str(file)
  1556. )
  1557. content_copy = io.BytesIO()
  1558. content_copy.write(await file.read())
  1559. content_copy.seek(0)
  1560. file_copies.append(
  1561. UploadFile(
  1562. file=content_copy,
  1563. path=Path(file.filename.lstrip("/")) if file.filename else None,
  1564. _deprecated_filename=file.filename,
  1565. size=file.size,
  1566. headers=file.headers,
  1567. )
  1568. )
  1569. event = Event(
  1570. token=token,
  1571. name=handler,
  1572. payload={handler_upload_param[0]: file_copies},
  1573. )
  1574. async def _ndjson_updates():
  1575. """Process the upload event, generating ndjson updates.
  1576. Yields:
  1577. Each state update as JSON followed by a new line.
  1578. """
  1579. # Process the event.
  1580. async with app.state_manager.modify_state(event.substate_token) as state:
  1581. async for update in state._process(event):
  1582. # Postprocess the event.
  1583. update = await app._postprocess(state, event, update)
  1584. yield update.json() + "\n"
  1585. # Stream updates to client
  1586. return StreamingResponse(
  1587. _ndjson_updates(),
  1588. media_type="application/x-ndjson",
  1589. )
  1590. return upload_file
  1591. class EventNamespace(AsyncNamespace):
  1592. """The event namespace."""
  1593. # The application object.
  1594. app: App
  1595. # Keep a mapping between socket ID and client token.
  1596. token_to_sid: dict[str, str]
  1597. # Keep a mapping between client token and socket ID.
  1598. sid_to_token: dict[str, str]
  1599. def __init__(self, namespace: str, app: App):
  1600. """Initialize the event namespace.
  1601. Args:
  1602. namespace: The namespace.
  1603. app: The application object.
  1604. """
  1605. super().__init__(namespace)
  1606. self.token_to_sid = {}
  1607. self.sid_to_token = {}
  1608. self.app = app
  1609. def on_connect(self, sid: str, environ: dict):
  1610. """Event for when the websocket is connected.
  1611. Args:
  1612. sid: The Socket.IO session id.
  1613. environ: The request information, including HTTP headers.
  1614. """
  1615. subprotocol = environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL")
  1616. if subprotocol and subprotocol != constants.Reflex.VERSION:
  1617. console.warn(
  1618. f"Frontend version {subprotocol} for session {sid} does not match the backend version {constants.Reflex.VERSION}."
  1619. )
  1620. def on_disconnect(self, sid: str):
  1621. """Event for when the websocket disconnects.
  1622. Args:
  1623. sid: The Socket.IO session id.
  1624. """
  1625. disconnect_token = self.sid_to_token.pop(sid, None)
  1626. if disconnect_token:
  1627. self.token_to_sid.pop(disconnect_token, None)
  1628. async def emit_update(self, update: StateUpdate, sid: str) -> None:
  1629. """Emit an update to the client.
  1630. Args:
  1631. update: The state update to send.
  1632. sid: The Socket.IO session id.
  1633. """
  1634. # Creating a task prevents the update from being blocked behind other coroutines.
  1635. await asyncio.create_task(
  1636. self.emit(str(constants.SocketEvent.EVENT), update, to=sid)
  1637. )
  1638. async def on_event(self, sid: str, data: Any):
  1639. """Event for receiving front-end websocket events.
  1640. Raises:
  1641. RuntimeError: If the Socket.IO is badly initialized.
  1642. Args:
  1643. sid: The Socket.IO session id.
  1644. data: The event data.
  1645. Raises:
  1646. EventDeserializationError: If the event data is not a dictionary.
  1647. """
  1648. fields = data
  1649. if isinstance(fields, str):
  1650. console.warn(
  1651. "Received event data as a string. This generally should not happen and may indicate a bug."
  1652. f" Event data: {fields}"
  1653. )
  1654. try:
  1655. fields = json.loads(fields)
  1656. except json.JSONDecodeError as ex:
  1657. raise exceptions.EventDeserializationError(
  1658. f"Failed to deserialize event data: {fields}."
  1659. ) from ex
  1660. if not isinstance(fields, dict):
  1661. raise exceptions.EventDeserializationError(
  1662. f"Event data must be a dictionary, but received {fields} of type {type(fields)}."
  1663. )
  1664. try:
  1665. # Get the event.
  1666. event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS})
  1667. except (TypeError, ValueError) as ex:
  1668. raise exceptions.EventDeserializationError(
  1669. f"Failed to deserialize event data: {fields}."
  1670. ) from ex
  1671. self.token_to_sid[event.token] = sid
  1672. self.sid_to_token[sid] = event.token
  1673. # Get the event environment.
  1674. if self.app.sio is None:
  1675. raise RuntimeError("Socket.IO is not initialized.")
  1676. environ = self.app.sio.get_environ(sid, self.namespace)
  1677. if environ is None:
  1678. raise RuntimeError("Socket.IO environ is not initialized.")
  1679. # Get the client headers.
  1680. headers = {
  1681. k.decode("utf-8"): v.decode("utf-8")
  1682. for (k, v) in environ["asgi.scope"]["headers"]
  1683. }
  1684. # Get the client IP
  1685. try:
  1686. client_ip = environ["asgi.scope"]["client"][0]
  1687. except (KeyError, IndexError):
  1688. client_ip = environ.get("REMOTE_ADDR", "0.0.0.0")
  1689. # Process the events.
  1690. async for update in process(self.app, event, sid, headers, client_ip):
  1691. # Emit the update from processing the event.
  1692. await self.emit_update(update=update, sid=sid)
  1693. async def on_ping(self, sid: str):
  1694. """Event for testing the API endpoint.
  1695. Args:
  1696. sid: The Socket.IO session id.
  1697. """
  1698. # Emit the test event.
  1699. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)