app.py 65 KB

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