app.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  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, ParamSpec, 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. @dataclasses.dataclass(frozen=True)
  193. class UploadFile(StarletteUploadFile):
  194. """A file uploaded to the server.
  195. Args:
  196. file: The standard Python file object (non-async).
  197. filename: The original file name.
  198. size: The size of the file in bytes.
  199. headers: The headers of the request.
  200. """
  201. file: BinaryIO
  202. path: Path | None = dataclasses.field(default=None)
  203. _deprecated_filename: str | None = dataclasses.field(default=None)
  204. size: int | None = dataclasses.field(default=None)
  205. headers: Headers = dataclasses.field(default_factory=Headers)
  206. @property
  207. def name(self) -> str | None:
  208. """Get the name of the uploaded file.
  209. Returns:
  210. The name of the uploaded file.
  211. """
  212. if self.path:
  213. return self.path.name
  214. return None
  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. P = ParamSpec("P")
  258. @dataclasses.dataclass()
  259. class App(MiddlewareMixin, LifespanMixin):
  260. """The main Reflex app that encapsulates the backend and frontend.
  261. Every Reflex app needs an app defined in its main module.
  262. ```python
  263. # app.py
  264. import reflex as rx
  265. # Define state and pages
  266. ...
  267. app = rx.App(
  268. # Set global level style.
  269. style={...},
  270. # Set the top level theme.
  271. theme=rx.theme(accent_color="blue"),
  272. )
  273. ```
  274. """
  275. # The global [theme](https://reflex.dev/docs/styling/theming/#theme) for the entire app.
  276. theme: Component | None = dataclasses.field(
  277. default_factory=lambda: themes.theme(accent_color="blue")
  278. )
  279. # The [global style](https://reflex.dev/docs/styling/overview/#global-styles}) for the app.
  280. style: ComponentStyle = dataclasses.field(default_factory=dict)
  281. # A list of URLs to [stylesheets](https://reflex.dev/docs/styling/custom-stylesheets/) to include in the app.
  282. stylesheets: list[str] = dataclasses.field(default_factory=list)
  283. # A component that is present on every page (defaults to the Connection Error banner).
  284. overlay_component: Component | ComponentCallable | None = dataclasses.field(
  285. default=None
  286. )
  287. # Error boundary component to wrap the app with.
  288. error_boundary: ComponentCallable | None = dataclasses.field(default=None)
  289. # 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.
  290. app_wraps: dict[tuple[int, str], Callable[[bool], Component | None]] = (
  291. dataclasses.field(
  292. default_factory=lambda: {
  293. (55, "ErrorBoundary"): (
  294. lambda stateful: default_error_boundary() if stateful else None
  295. ),
  296. (5, "Overlay"): (
  297. lambda stateful: default_overlay_component() if stateful else None
  298. ),
  299. (4, "ExtraOverlay"): lambda stateful: extra_overlay_function(),
  300. }
  301. )
  302. )
  303. # Components to add to the head of every page.
  304. head_components: list[Component] = dataclasses.field(default_factory=list)
  305. # The Socket.IO AsyncServer instance.
  306. sio: AsyncServer | None = None
  307. # The language to add to the html root tag of every page.
  308. html_lang: str | None = None
  309. # Attributes to add to the html root tag of every page.
  310. html_custom_attrs: dict[str, str] | None = None
  311. # A map from a route to an unevaluated page.
  312. _unevaluated_pages: dict[str, UnevaluatedPage] = dataclasses.field(
  313. default_factory=dict
  314. )
  315. # A map from a page route to the component to render. Users should use `add_page`.
  316. _pages: dict[str, Component] = dataclasses.field(default_factory=dict)
  317. # A mapping of pages which created states as they were being evaluated.
  318. _stateful_pages: dict[str, None] = dataclasses.field(default_factory=dict)
  319. # The backend API object.
  320. _api: Starlette | None = None
  321. # The state class to use for the app.
  322. _state: type[BaseState] | None = None
  323. # Class to manage many client states.
  324. _state_manager: StateManager | None = None
  325. # Mapping from a route to event handlers to trigger when the page loads.
  326. _load_events: dict[str, list[IndividualEventType[()]]] = dataclasses.field(
  327. default_factory=dict
  328. )
  329. # Admin dashboard to view and manage the database.
  330. admin_dash: AdminDash | None = None
  331. # The async server name space.
  332. _event_namespace: EventNamespace | None = None
  333. # Background tasks that are currently running.
  334. _background_tasks: set[asyncio.Task] = dataclasses.field(default_factory=set)
  335. # Frontend Error Handler Function
  336. frontend_exception_handler: Callable[[Exception], None] = (
  337. default_frontend_exception_handler
  338. )
  339. # Backend Error Handler Function
  340. backend_exception_handler: Callable[
  341. [Exception], EventSpec | list[EventSpec] | None
  342. ] = default_backend_exception_handler
  343. # Put the toast provider in the app wrap.
  344. toaster: Component | None = dataclasses.field(default_factory=toast.provider)
  345. # Transform the ASGI app before running it.
  346. api_transformer: (
  347. Sequence[Callable[[ASGIApp], ASGIApp] | Starlette]
  348. | Callable[[ASGIApp], ASGIApp]
  349. | Starlette
  350. | None
  351. ) = None
  352. # FastAPI app for compatibility with FastAPI.
  353. _cached_fastapi_app: FastAPI | None = None
  354. @property
  355. @deprecated("Use `api_transformer=your_fastapi_app` instead.")
  356. def api(self) -> FastAPI:
  357. """Get the backend api.
  358. Returns:
  359. The backend api.
  360. """
  361. if self._cached_fastapi_app is None:
  362. self._cached_fastapi_app = FastAPI()
  363. console.deprecate(
  364. feature_name="App.api",
  365. reason="Set `api_transformer=your_fastapi_app` instead.",
  366. deprecation_version="0.7.9",
  367. removal_version="0.8.0",
  368. )
  369. return self._cached_fastapi_app
  370. @property
  371. def event_namespace(self) -> EventNamespace | None:
  372. """Get the event namespace.
  373. Returns:
  374. The event namespace.
  375. """
  376. return self._event_namespace
  377. def __post_init__(self):
  378. """Initialize the app.
  379. Raises:
  380. ValueError: If the event namespace is not provided in the config.
  381. Also, if there are multiple client subclasses of rx.BaseState(Subclasses of rx.BaseState should consist
  382. of the DefaultState and the client app state).
  383. """
  384. # Special case to allow test cases have multiple subclasses of rx.BaseState.
  385. if not is_testing_env() and BaseState.__subclasses__() != [State]:
  386. # Only rx.State is allowed as Base State subclass.
  387. msg = "rx.BaseState cannot be subclassed directly. Use rx.State instead"
  388. raise ValueError(msg)
  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. msg = f"Custom `sio` must use `async_mode='asgi'`, not '{self.sio.async_mode}'."
  444. raise RuntimeError(msg)
  445. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  446. socket_app = EngineIOApp(self.sio, socketio_path="")
  447. namespace = config.get_event_namespace()
  448. # Create the event namespace and attach the main app. Not related to any paths.
  449. self._event_namespace = EventNamespace(namespace, self)
  450. # Register the event namespace with the socket.
  451. self.sio.register_namespace(self.event_namespace)
  452. # Mount the socket app with the API.
  453. if self._api:
  454. class HeaderMiddleware:
  455. def __init__(self, app: ASGIApp):
  456. self.app = app
  457. async def __call__(self, scope: Scope, receive: Receive, send: Send):
  458. original_send = send
  459. async def modified_send(message: Message):
  460. if message["type"] == "websocket.accept":
  461. if scope.get("subprotocols"):
  462. # The following *does* say "subprotocol" instead of "subprotocols", intentionally.
  463. message["subprotocol"] = scope["subprotocols"][0]
  464. headers = dict(message.get("headers", []))
  465. header_key = b"sec-websocket-protocol"
  466. if subprotocol := headers.get(header_key):
  467. message["headers"] = [
  468. *message.get("headers", []),
  469. (header_key, subprotocol),
  470. ]
  471. return await original_send(message)
  472. return await self.app(scope, receive, modified_send)
  473. socket_app_with_headers = HeaderMiddleware(socket_app)
  474. self._api.mount(str(constants.Endpoint.EVENT), socket_app_with_headers)
  475. # Check the exception handlers
  476. self._validate_exception_handlers()
  477. def __repr__(self) -> str:
  478. """Get the string representation of the app.
  479. Returns:
  480. The string representation of the app.
  481. """
  482. return f"<App state={self._state.__name__ if self._state else None}>"
  483. def __call__(self) -> ASGIApp:
  484. """Run the backend api instance.
  485. Raises:
  486. ValueError: If the app has not been initialized.
  487. Returns:
  488. The backend api.
  489. """
  490. # For py3.9 compatibility when redis is used, we MUST add any decorator pages
  491. # before compiling the app in a thread to avoid event loop error (REF-2172).
  492. self._apply_decorated_pages()
  493. compile_future = concurrent.futures.ThreadPoolExecutor(max_workers=1).submit(
  494. self._compile
  495. )
  496. def callback(f: concurrent.futures.Future):
  497. # Force background compile errors to print eagerly
  498. return f.result()
  499. compile_future.add_done_callback(callback)
  500. # Wait for the compile to finish to ensure all optional endpoints are mounted.
  501. compile_future.result()
  502. if not self._api:
  503. msg = "The app has not been initialized."
  504. raise ValueError(msg)
  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. msg = "The state manager has not been initialized."
  598. raise ValueError(msg)
  599. return self._state_manager
  600. @staticmethod
  601. def _generate_component(component: Component | ComponentCallable) -> Component:
  602. """Generate a component from a callable.
  603. Args:
  604. component: The component function to call or Component to return as-is.
  605. Returns:
  606. The generated component.
  607. """
  608. from reflex.compiler.compiler import into_component
  609. return into_component(component)
  610. def add_page(
  611. self,
  612. component: Component | ComponentCallable | None = None,
  613. route: str | None = None,
  614. title: str | Var | None = None,
  615. description: str | Var | None = None,
  616. image: str = constants.DefaultPage.IMAGE,
  617. on_load: EventType[()] | None = None,
  618. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  619. context: dict[str, Any] | None = None,
  620. ):
  621. """Add a page to the app.
  622. If the component is a callable, by default the route is the name of the
  623. function. Otherwise, a route must be provided.
  624. Args:
  625. component: The component to display at the page.
  626. route: The route to display the component at.
  627. title: The title of the page.
  628. description: The description of the page.
  629. image: The image to display on the page.
  630. on_load: The event handler(s) that will be called each time the page load.
  631. meta: The metadata of the page.
  632. context: Values passed to page for custom page-specific logic.
  633. Raises:
  634. PageValueError: When the component is not set for a non-404 page.
  635. RouteValueError: When the specified route name already exists.
  636. """
  637. # If the route is not set, get it from the callable.
  638. if route is None:
  639. if not isinstance(component, Callable):
  640. msg = "Route must be set if component is not a callable."
  641. raise exceptions.RouteValueError(msg)
  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. msg = "Component must be set for a non-404 page."
  656. raise exceptions.PageValueError(msg)
  657. # Check if the route given is valid
  658. verify_route_validity(route)
  659. unevaluated_page = UnevaluatedPage(
  660. component=component,
  661. route=route,
  662. title=title,
  663. description=description,
  664. image=image,
  665. on_load=on_load,
  666. meta=meta,
  667. context=context,
  668. )
  669. if route in self._unevaluated_pages:
  670. if self._unevaluated_pages[route].component is component:
  671. unevaluated_page = unevaluated_page.merged_with(
  672. self._unevaluated_pages[route]
  673. )
  674. console.warn(
  675. f"Page {route} is being redefined with the same component."
  676. )
  677. else:
  678. route_name = (
  679. f"`{route}` or `/`"
  680. if route == constants.PageNames.INDEX_ROUTE
  681. else f"`{route}`"
  682. )
  683. existing_component = self._unevaluated_pages[route].component
  684. msg = (
  685. f"Tried to add page {readable_name_from_component(component)} with route {route_name} but "
  686. f"page {readable_name_from_component(existing_component)} with the same route already exists. "
  687. "Make sure you do not have two pages with the same route."
  688. )
  689. raise exceptions.RouteValueError(msg)
  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. msg = f"You cannot use different slug names for the same dynamic path in {route} and {new_route} ('{r}' != '{nr}')"
  758. raise RouteValueError(msg)
  759. if rw not in segments and r != nr:
  760. # if the section being compared in both routes is not a dynamic segment(i.e not wrapped in brackets)
  761. # then we are guaranteed that the route is valid and there's no need checking the rest.
  762. # eg. /posts/[id]/info/[slug1] and /posts/[id]/info1/[slug1] is always going to be valid since
  763. # info1 will break away into its own tree.
  764. break
  765. def add_custom_404_page(
  766. self,
  767. component: Component | ComponentCallable | None = None,
  768. title: str = constants.Page404.TITLE,
  769. image: str = constants.Page404.IMAGE,
  770. description: str = constants.Page404.DESCRIPTION,
  771. on_load: EventType[()] | None = None,
  772. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  773. ):
  774. """Define a custom 404 page for any url having no match.
  775. If there is no page defined on 'index' route, add the 404 page to it.
  776. If there is no global catchall defined, add the 404 page with a catchall.
  777. Args:
  778. component: The component to display at the page.
  779. title: The title of the page.
  780. image: The image to display on the page.
  781. description: The description of the page.
  782. on_load: The event handler(s) that will be called each time the page load.
  783. meta: The metadata of the page.
  784. """
  785. console.deprecate(
  786. feature_name="App.add_custom_404_page",
  787. reason=f"Use app.add_page(component, route='/{constants.Page404.SLUG}') instead.",
  788. deprecation_version="0.6.7",
  789. removal_version="0.8.0",
  790. )
  791. self.add_page(
  792. component=component,
  793. route=constants.Page404.SLUG,
  794. title=title or constants.Page404.TITLE,
  795. image=image or constants.Page404.IMAGE,
  796. description=description or constants.Page404.DESCRIPTION,
  797. on_load=on_load,
  798. meta=meta,
  799. )
  800. def _setup_admin_dash(self):
  801. """Setup the admin dash."""
  802. try:
  803. from starlette_admin.contrib.sqla.admin import Admin
  804. from starlette_admin.contrib.sqla.view import ModelView
  805. except ImportError:
  806. return
  807. # Get the admin dash.
  808. if not self._api:
  809. return
  810. admin_dash = self.admin_dash
  811. if admin_dash and admin_dash.models:
  812. # Build the admin dashboard
  813. admin = (
  814. admin_dash.admin
  815. if admin_dash.admin
  816. else Admin(
  817. engine=Model.get_db_engine(),
  818. title="Reflex Admin Dashboard",
  819. logo_url="https://reflex.dev/Reflex.svg",
  820. )
  821. )
  822. for model in admin_dash.models:
  823. view = admin_dash.view_overrides.get(model, ModelView)
  824. admin.add_view(view(model))
  825. admin.mount_to(self._api)
  826. def _get_frontend_packages(self, imports: dict[str, set[ImportVar]]):
  827. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  828. Args:
  829. imports: A dictionary containing the imports used in the current page.
  830. Example:
  831. >>> _get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  832. """
  833. dependencies = constants.PackageJson.DEPENDENCIES
  834. dev_dependencies = constants.PackageJson.DEV_DEPENDENCIES
  835. page_imports = {
  836. i
  837. for i, tags in imports.items()
  838. if i not in dependencies
  839. and i not in dev_dependencies
  840. and not any(i.startswith(prefix) for prefix in ["/", "$/", ".", "next/"])
  841. and i != ""
  842. and any(tag.install for tag in tags)
  843. }
  844. pinned = {i.rpartition("@")[0] for i in page_imports if "@" in i}
  845. page_imports = {i for i in page_imports if i not in pinned}
  846. frontend_packages = get_config().frontend_packages
  847. _frontend_packages = []
  848. for package in frontend_packages:
  849. if package in page_imports:
  850. console.warn(
  851. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  852. )
  853. continue
  854. _frontend_packages.append(package)
  855. page_imports.update(_frontend_packages)
  856. prerequisites.install_frontend_packages(page_imports, get_config())
  857. def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component:
  858. for component in tuple(app_wrappers.values()):
  859. app_wrappers.update(component._get_all_app_wrap_components())
  860. order = sorted(app_wrappers, key=lambda k: k[0], reverse=True)
  861. root = parent = copy.deepcopy(app_wrappers[order[0]])
  862. for key in order[1:]:
  863. child = copy.deepcopy(app_wrappers[key])
  864. parent.children.append(child)
  865. parent = child
  866. return root
  867. def _should_compile(self) -> bool:
  868. """Check if the app should be compiled.
  869. Returns:
  870. Whether the app should be compiled.
  871. """
  872. # Check the environment variable.
  873. if environment.REFLEX_SKIP_COMPILE.get():
  874. return False
  875. nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
  876. # Check the nocompile file.
  877. if nocompile.exists():
  878. # Delete the nocompile file
  879. nocompile.unlink(missing_ok=True)
  880. return False
  881. # By default, compile the app.
  882. return True
  883. def _add_overlay_to_component(self, component: Component) -> Component:
  884. if self.overlay_component is None:
  885. return component
  886. children = component.children
  887. overlay_component = self._generate_component(self.overlay_component)
  888. if children[0] == overlay_component:
  889. return component
  890. # recreate OverlayFragment with overlay_component as first child
  891. return OverlayFragment.create(overlay_component, *children)
  892. def _setup_overlay_component(self):
  893. """If a State is not used and no overlay_component is specified, do not render the connection modal."""
  894. if self._state is None and self.overlay_component is default_overlay_component:
  895. self.overlay_component = None
  896. for k, component in self._pages.items():
  897. self._pages[k] = self._add_overlay_to_component(component)
  898. def _setup_sticky_badge(self):
  899. """Add the sticky badge to the app."""
  900. from reflex.components.component import memo
  901. @memo
  902. def memoized_badge():
  903. sticky_badge = sticky()
  904. sticky_badge._add_style_recursive({})
  905. return sticky_badge
  906. self.app_wraps[(0, "StickyBadge")] = lambda _: memoized_badge()
  907. def _apply_decorated_pages(self):
  908. """Add @rx.page decorated pages to the app.
  909. This has to be done in the MainThread for py38 and py39 compatibility, so the
  910. decorated pages are added to the app before the app is compiled (in a thread)
  911. to workaround REF-2172.
  912. This can move back into `compile_` when py39 support is dropped.
  913. """
  914. app_name = get_config().app_name
  915. # Add the @rx.page decorated pages to collect on_load events.
  916. for render, kwargs in DECORATED_PAGES[app_name]:
  917. self.add_page(render, **kwargs)
  918. def _validate_var_dependencies(self, state: type[BaseState] | None = None) -> None:
  919. """Validate the dependencies of the vars in the app.
  920. Args:
  921. state: The state to validate the dependencies for.
  922. Raises:
  923. VarDependencyError: When a computed var has an invalid dependency.
  924. """
  925. if not self._state:
  926. return
  927. if not state:
  928. state = self._state
  929. for var in state.computed_vars.values():
  930. if not var._cache:
  931. continue
  932. deps = var._deps(objclass=state)
  933. for state_name, dep_set in deps.items():
  934. state_cls = (
  935. state.get_root_state().get_class_substate(state_name)
  936. if state_name != state.get_full_name()
  937. else state
  938. )
  939. for dep in dep_set:
  940. if dep not in state_cls.vars and dep not in state_cls.backend_vars:
  941. msg = f"ComputedVar {var._js_expr} on state {state.__name__} has an invalid dependency {state_name}.{dep}"
  942. raise exceptions.VarDependencyError(msg)
  943. for substate in state.class_subclasses:
  944. self._validate_var_dependencies(substate)
  945. def _compile(self, export: bool = False, dry_run: bool = False):
  946. """Compile the app and output it to the pages folder.
  947. Args:
  948. export: Whether to compile the app for export.
  949. dry_run: Whether to compile the app without saving it.
  950. Raises:
  951. ReflexRuntimeError: When any page uses state, but no rx.State subclass is defined.
  952. FileNotFoundError: When a plugin requires a file that does not exist.
  953. """
  954. from reflex.utils.exceptions import ReflexRuntimeError
  955. self._pages = {}
  956. def get_compilation_time() -> str:
  957. return str(datetime.now().time()).split(".")[0]
  958. should_compile = self._should_compile()
  959. backend_dir = prerequisites.get_backend_dir()
  960. if not dry_run and not should_compile and backend_dir.exists():
  961. stateful_pages_marker = backend_dir / constants.Dirs.STATEFUL_PAGES
  962. if stateful_pages_marker.exists():
  963. with stateful_pages_marker.open("r") as f:
  964. stateful_pages = json.load(f)
  965. for route in stateful_pages:
  966. console.debug(f"BE Evaluating stateful page: {route}")
  967. self._compile_page(route, save_page=False)
  968. self._enable_state()
  969. self._add_optional_endpoints()
  970. return
  971. # Render a default 404 page if the user didn't supply one
  972. if constants.Page404.SLUG not in self._unevaluated_pages:
  973. self.add_page(route=constants.Page404.SLUG)
  974. # Fix up the style.
  975. self.style = evaluate_style_namespaces(self.style)
  976. # Add the app wrappers.
  977. app_wrappers: dict[tuple[int, str], Component] = {
  978. # Default app wrap component renders {children}
  979. (0, "AppWrap"): AppWrap.create()
  980. }
  981. if self.theme is not None:
  982. # If a theme component was provided, wrap the app with it
  983. app_wrappers[(20, "Theme")] = self.theme
  984. # Get the env mode.
  985. config = get_config()
  986. if config.react_strict_mode:
  987. app_wrappers[(200, "StrictMode")] = StrictMode.create()
  988. if not should_compile and not dry_run:
  989. with console.timing("Evaluate Pages (Backend)"):
  990. for route in self._unevaluated_pages:
  991. console.debug(f"Evaluating page: {route}")
  992. self._compile_page(route, save_page=should_compile)
  993. # Save the pages which created new states at eval time.
  994. self._write_stateful_pages_marker()
  995. # Add the optional endpoints (_upload)
  996. self._add_optional_endpoints()
  997. return
  998. # Create a progress bar.
  999. progress = Progress(
  1000. *Progress.get_default_columns()[:-1],
  1001. MofNCompleteColumn(),
  1002. TimeElapsedColumn(),
  1003. )
  1004. # try to be somewhat accurate - but still not 100%
  1005. adhoc_steps_without_executor = 7
  1006. fixed_pages_within_executor = 4
  1007. plugin_count = len(config.plugins)
  1008. progress.start()
  1009. task = progress.add_task(
  1010. f"[{get_compilation_time()}] Compiling:",
  1011. total=len(self._pages)
  1012. + (len(self._unevaluated_pages) * 2)
  1013. + fixed_pages_within_executor
  1014. + adhoc_steps_without_executor
  1015. + plugin_count,
  1016. )
  1017. with console.timing("Evaluate Pages (Frontend)"):
  1018. performance_metrics: list[tuple[str, float]] = []
  1019. for route in self._unevaluated_pages:
  1020. console.debug(f"Evaluating page: {route}")
  1021. start = timer()
  1022. self._compile_page(route, save_page=should_compile)
  1023. end = timer()
  1024. performance_metrics.append((route, end - start))
  1025. progress.advance(task)
  1026. console.debug(
  1027. "Slowest pages:\n"
  1028. + "\n".join(
  1029. f"{route}: {time * 1000:.1f}ms"
  1030. for route, time in sorted(
  1031. performance_metrics, key=lambda x: x[1], reverse=True
  1032. )[:10]
  1033. )
  1034. )
  1035. # Save the pages which created new states at eval time.
  1036. self._write_stateful_pages_marker()
  1037. # Add the optional endpoints (_upload)
  1038. self._add_optional_endpoints()
  1039. self._validate_var_dependencies()
  1040. self._setup_overlay_component()
  1041. if config.show_built_with_reflex is None:
  1042. if (
  1043. get_compile_context() == constants.CompileContext.DEPLOY
  1044. and prerequisites.get_user_tier() in ["pro", "team", "enterprise"]
  1045. ):
  1046. config.show_built_with_reflex = False
  1047. else:
  1048. config.show_built_with_reflex = True
  1049. if is_prod_mode() and config.show_built_with_reflex:
  1050. self._setup_sticky_badge()
  1051. progress.advance(task)
  1052. # Store the compile results.
  1053. compile_results: list[tuple[str, str]] = []
  1054. progress.advance(task)
  1055. # Track imports found.
  1056. all_imports = {}
  1057. # This has to happen before compiling stateful components as that
  1058. # prevents recursive functions from reaching all components.
  1059. for component in self._pages.values():
  1060. # Add component._get_all_imports() to all_imports.
  1061. all_imports.update(component._get_all_imports())
  1062. # Add the app wrappers from this component.
  1063. app_wrappers.update(component._get_all_app_wrap_components())
  1064. if (toaster := self.toaster) is not None:
  1065. from reflex.components.component import memo
  1066. @memo
  1067. def memoized_toast_provider():
  1068. return toaster
  1069. toast_provider = Fragment.create(memoized_toast_provider())
  1070. app_wrappers[(1, "ToasterProvider")] = toast_provider
  1071. # Add the app wraps to the app.
  1072. for key, app_wrap in self.app_wraps.items():
  1073. component = app_wrap(self._state is not None)
  1074. if component is not None:
  1075. app_wrappers[key] = component
  1076. if self.error_boundary:
  1077. from reflex.compiler.compiler import into_component
  1078. console.deprecate(
  1079. feature_name="App.error_boundary",
  1080. reason="Use app_wraps instead.",
  1081. deprecation_version="0.7.1",
  1082. removal_version="0.8.0",
  1083. )
  1084. app_wrappers[(55, "ErrorBoundary")] = into_component(self.error_boundary)
  1085. # Perform auto-memoization of stateful components.
  1086. with console.timing("Auto-memoize StatefulComponents"):
  1087. (
  1088. stateful_components_path,
  1089. stateful_components_code,
  1090. page_components,
  1091. ) = compiler.compile_stateful_components(self._pages.values())
  1092. progress.advance(task)
  1093. # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State.
  1094. if code_uses_state_contexts(stateful_components_code) and self._state is None:
  1095. msg = (
  1096. "To access rx.State in frontend components, at least one "
  1097. "subclass of rx.State must be defined in the app."
  1098. )
  1099. raise ReflexRuntimeError(msg)
  1100. compile_results.append((stateful_components_path, stateful_components_code))
  1101. progress.advance(task)
  1102. # Compile the root document before fork.
  1103. compile_results.append(
  1104. compiler.compile_document_root(
  1105. self.head_components,
  1106. html_lang=self.html_lang,
  1107. html_custom_attrs=(
  1108. {**self.html_custom_attrs} if self.html_custom_attrs else {}
  1109. ),
  1110. )
  1111. )
  1112. progress.advance(task)
  1113. # Copy the assets.
  1114. assets_src = Path.cwd() / constants.Dirs.APP_ASSETS
  1115. if assets_src.is_dir() and not dry_run:
  1116. with console.timing("Copy assets"):
  1117. path_ops.update_directory_tree(
  1118. src=assets_src,
  1119. dest=(
  1120. Path.cwd() / prerequisites.get_web_dir() / constants.Dirs.PUBLIC
  1121. ),
  1122. )
  1123. executor = ExecutorType.get_executor_from_environment()
  1124. for route, component in zip(self._pages, page_components, strict=True):
  1125. ExecutorSafeFunctions.COMPONENTS[route] = component
  1126. ExecutorSafeFunctions.STATE = self._state
  1127. modify_files_tasks: list[tuple[str, str, Callable[[str], str]]] = []
  1128. with console.timing("Compile to Javascript"), executor as executor:
  1129. result_futures: list[
  1130. concurrent.futures.Future[
  1131. list[tuple[str, str]] | tuple[str, str] | None
  1132. ]
  1133. ] = []
  1134. def _submit_work(
  1135. fn: Callable[P, list[tuple[str, str]] | tuple[str, str] | None],
  1136. *args: P.args,
  1137. **kwargs: P.kwargs,
  1138. ):
  1139. f = executor.submit(fn, *args, **kwargs)
  1140. f.add_done_callback(lambda _: progress.advance(task))
  1141. result_futures.append(f)
  1142. # Compile the pre-compiled pages.
  1143. for route in self._pages:
  1144. _submit_work(
  1145. ExecutorSafeFunctions.compile_page,
  1146. route,
  1147. )
  1148. # Compile the root stylesheet with base styles.
  1149. _submit_work(compiler.compile_root_stylesheet, self.stylesheets)
  1150. # Compile the theme.
  1151. _submit_work(compile_theme, self.style)
  1152. def _submit_work_without_advancing(
  1153. fn: Callable[P, list[tuple[str, str]] | tuple[str, str] | None],
  1154. *args: P.args,
  1155. **kwargs: P.kwargs,
  1156. ):
  1157. f = executor.submit(fn, *args, **kwargs)
  1158. result_futures.append(f)
  1159. for plugin in config.plugins:
  1160. plugin.pre_compile(
  1161. add_save_task=_submit_work_without_advancing,
  1162. add_modify_task=(
  1163. lambda *args, plugin=plugin: modify_files_tasks.append(
  1164. (
  1165. plugin.__class__.__module__ + plugin.__class__.__name__,
  1166. *args,
  1167. )
  1168. )
  1169. ),
  1170. )
  1171. # Wait for all compilation tasks to complete.
  1172. for future in concurrent.futures.as_completed(result_futures):
  1173. if (result := future.result()) is not None:
  1174. if isinstance(result, list):
  1175. compile_results.extend(result)
  1176. else:
  1177. compile_results.append(result)
  1178. progress.advance(task, advance=len(config.plugins))
  1179. app_root = self._app_root(app_wrappers=app_wrappers)
  1180. # Get imports from AppWrap components.
  1181. all_imports.update(app_root._get_all_imports())
  1182. progress.advance(task)
  1183. # Compile the contexts.
  1184. compile_results.append(
  1185. compiler.compile_contexts(self._state, self.theme),
  1186. )
  1187. if self.theme is not None:
  1188. # Fix #2992 by removing the top-level appearance prop
  1189. self.theme.appearance = None # pyright: ignore[reportAttributeAccessIssue]
  1190. progress.advance(task)
  1191. # Compile the app root.
  1192. compile_results.append(
  1193. compiler.compile_app(app_root),
  1194. )
  1195. progress.advance(task)
  1196. # Compile custom components.
  1197. (
  1198. custom_components_output,
  1199. custom_components_result,
  1200. custom_components_imports,
  1201. ) = compiler.compile_components(dict.fromkeys(CUSTOM_COMPONENTS.values()))
  1202. compile_results.append((custom_components_output, custom_components_result))
  1203. all_imports.update(custom_components_imports)
  1204. progress.advance(task)
  1205. progress.stop()
  1206. if dry_run:
  1207. return
  1208. # Install frontend packages.
  1209. with console.timing("Install Frontend Packages"):
  1210. self._get_frontend_packages(all_imports)
  1211. # Setup the next.config.js
  1212. transpile_packages = [
  1213. package
  1214. for package, import_vars in all_imports.items()
  1215. if any(import_var.transpile for import_var in import_vars)
  1216. ]
  1217. prerequisites.update_next_config(
  1218. export=export,
  1219. transpile_packages=transpile_packages,
  1220. )
  1221. if is_prod_mode():
  1222. # Empty the .web pages directory.
  1223. compiler.purge_web_pages_dir()
  1224. else:
  1225. # In dev mode, delete removed pages and update existing pages.
  1226. keep_files = [Path(output_path) for output_path, _ in compile_results]
  1227. for p in Path(prerequisites.get_web_dir() / constants.Dirs.PAGES).rglob(
  1228. "*"
  1229. ):
  1230. if p.is_file() and p not in keep_files:
  1231. # Remove pages that are no longer in the app.
  1232. p.unlink()
  1233. output_mapping: dict[Path, str] = {}
  1234. for output_path, code in compile_results:
  1235. path = compiler_utils.resolve_path_of_web_dir(output_path)
  1236. if path in output_mapping:
  1237. console.warn(
  1238. f"Path {path} has two different outputs. The first one will be used."
  1239. )
  1240. else:
  1241. output_mapping[path] = code
  1242. for plugin in config.plugins:
  1243. for static_file_path, content in plugin.get_static_assets():
  1244. path = compiler_utils.resolve_path_of_web_dir(static_file_path)
  1245. if path in output_mapping:
  1246. console.warn(
  1247. f"Plugin {plugin.__class__.__name__} is trying to write to {path} but it already exists. The plugin file will be ignored."
  1248. )
  1249. else:
  1250. output_mapping[path] = (
  1251. content.decode("utf-8")
  1252. if isinstance(content, bytes)
  1253. else content
  1254. )
  1255. for plugin_name, file_path, modify_fn in modify_files_tasks:
  1256. path = compiler_utils.resolve_path_of_web_dir(file_path)
  1257. file_content = output_mapping.get(path)
  1258. if file_content is None:
  1259. if path.exists():
  1260. file_content = path.read_text()
  1261. else:
  1262. msg = f"Plugin {plugin_name} is trying to modify {path} but it does not exist."
  1263. raise FileNotFoundError(msg)
  1264. output_mapping[path] = modify_fn(file_content)
  1265. with console.timing("Write to Disk"):
  1266. for output_path, code in output_mapping.items():
  1267. compiler_utils.write_file(output_path, code)
  1268. def _write_stateful_pages_marker(self):
  1269. """Write list of routes that create dynamic states for the backend to use later."""
  1270. if self._state is not None:
  1271. stateful_pages_marker = (
  1272. prerequisites.get_backend_dir() / constants.Dirs.STATEFUL_PAGES
  1273. )
  1274. stateful_pages_marker.parent.mkdir(parents=True, exist_ok=True)
  1275. with stateful_pages_marker.open("w") as f:
  1276. json.dump(list(self._stateful_pages), f)
  1277. def add_all_routes_endpoint(self):
  1278. """Add an endpoint to the app that returns all the routes."""
  1279. if not self._api:
  1280. return
  1281. async def all_routes(_request: Request) -> Response:
  1282. return JSONResponse(list(self._unevaluated_pages.keys()))
  1283. self._api.add_route(
  1284. str(constants.Endpoint.ALL_ROUTES), all_routes, methods=["GET"]
  1285. )
  1286. @contextlib.asynccontextmanager
  1287. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  1288. """Modify the state out of band.
  1289. Args:
  1290. token: The token to modify the state for.
  1291. Yields:
  1292. The state to modify.
  1293. Raises:
  1294. RuntimeError: If the app has not been initialized yet.
  1295. """
  1296. if self.event_namespace is None:
  1297. msg = "App has not been initialized yet."
  1298. raise RuntimeError(msg)
  1299. # Get exclusive access to the state.
  1300. async with self.state_manager.modify_state(token) as state:
  1301. # No other event handler can modify the state while in this context.
  1302. yield state
  1303. delta = await state._get_resolved_delta()
  1304. if delta:
  1305. # When the state is modified reset dirty status and emit the delta to the frontend.
  1306. state._clean()
  1307. await self.event_namespace.emit_update(
  1308. update=StateUpdate(delta=delta),
  1309. sid=state.router.session.session_id,
  1310. )
  1311. def _process_background(
  1312. self, state: BaseState, event: Event
  1313. ) -> asyncio.Task | None:
  1314. """Process an event in the background and emit updates as they arrive.
  1315. Args:
  1316. state: The state to process the event for.
  1317. event: The event to process.
  1318. Returns:
  1319. Task if the event was backgroundable, otherwise None
  1320. """
  1321. substate, handler = state._get_event_handler(event)
  1322. if not handler.is_background:
  1323. return None
  1324. async def _coro():
  1325. """Coroutine to process the event and emit updates inside an asyncio.Task.
  1326. Raises:
  1327. RuntimeError: If the app has not been initialized yet.
  1328. """
  1329. if self.event_namespace is None:
  1330. msg = "App has not been initialized yet."
  1331. raise RuntimeError(msg)
  1332. # Process the event.
  1333. async for update in state._process_event(
  1334. handler=handler, state=substate, payload=event.payload
  1335. ):
  1336. # Postprocess the event.
  1337. update = await self._postprocess(state, event, update)
  1338. # Send the update to the client.
  1339. await self.event_namespace.emit_update(
  1340. update=update,
  1341. sid=state.router.session.session_id,
  1342. )
  1343. task = asyncio.create_task(_coro())
  1344. self._background_tasks.add(task)
  1345. # Clean up task from background_tasks set when complete.
  1346. task.add_done_callback(self._background_tasks.discard)
  1347. return task
  1348. def _validate_exception_handlers(self):
  1349. """Validate the custom event exception handlers for front- and backend.
  1350. Raises:
  1351. ValueError: If the custom exception handlers are invalid.
  1352. """
  1353. frontend_arg_spec = {
  1354. "exception": Exception,
  1355. }
  1356. backend_arg_spec = {
  1357. "exception": Exception,
  1358. }
  1359. for handler_domain, handler_fn, handler_spec in zip(
  1360. ["frontend", "backend"],
  1361. [self.frontend_exception_handler, self.backend_exception_handler],
  1362. [
  1363. frontend_arg_spec,
  1364. backend_arg_spec,
  1365. ],
  1366. strict=True,
  1367. ):
  1368. if hasattr(handler_fn, "__name__"):
  1369. _fn_name = handler_fn.__name__
  1370. else:
  1371. _fn_name = type(handler_fn).__name__
  1372. if isinstance(handler_fn, functools.partial):
  1373. msg = f"Provided custom {handler_domain} exception handler `{_fn_name}` is a partial function. Please provide a named function instead."
  1374. raise ValueError(msg)
  1375. if not callable(handler_fn):
  1376. msg = f"Provided custom {handler_domain} exception handler `{_fn_name}` is not a function."
  1377. raise ValueError(msg)
  1378. # Allow named functions only as lambda functions cannot be introspected
  1379. if _fn_name == "<lambda>":
  1380. msg = f"Provided custom {handler_domain} exception handler `{_fn_name}` is a lambda function. Please use a named function instead."
  1381. raise ValueError(msg)
  1382. # Check if the function has the necessary annotations and types in the right order
  1383. argspec = inspect.getfullargspec(handler_fn)
  1384. arg_annotations = {
  1385. k: eval(v) if isinstance(v, str) else v
  1386. for k, v in argspec.annotations.items()
  1387. if k not in ["args", "kwargs", "return"]
  1388. }
  1389. for required_arg_index, required_arg in enumerate(handler_spec):
  1390. if required_arg not in arg_annotations:
  1391. msg = f"Provided custom {handler_domain} exception handler `{_fn_name}` does not take the required argument `{required_arg}`"
  1392. raise ValueError(msg)
  1393. if list(arg_annotations.keys())[required_arg_index] != required_arg:
  1394. msg = (
  1395. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong argument order."
  1396. f"Expected `{required_arg}` as the {required_arg_index + 1} argument but got `{list(arg_annotations.keys())[required_arg_index]}`"
  1397. )
  1398. raise ValueError(msg)
  1399. if not issubclass(arg_annotations[required_arg], Exception):
  1400. msg = (
  1401. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong type for {required_arg} argument."
  1402. f"Expected to be `Exception` but got `{arg_annotations[required_arg]}`"
  1403. )
  1404. raise ValueError(msg)
  1405. # Check if the return type is valid for backend exception handler
  1406. if handler_domain == "backend":
  1407. sig = inspect.signature(self.backend_exception_handler)
  1408. return_type = (
  1409. eval(sig.return_annotation)
  1410. if isinstance(sig.return_annotation, str)
  1411. else sig.return_annotation
  1412. )
  1413. valid = bool(
  1414. return_type == EventSpec
  1415. or return_type == EventSpec | None
  1416. or return_type == list[EventSpec]
  1417. or return_type == inspect.Signature.empty
  1418. or return_type is None
  1419. )
  1420. if not valid:
  1421. msg = (
  1422. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong return type."
  1423. f"Expected `EventSpec | list[EventSpec] | None` but got `{return_type}`"
  1424. )
  1425. raise ValueError(msg)
  1426. async def process(
  1427. app: App, event: Event, sid: str, headers: dict, client_ip: str
  1428. ) -> AsyncIterator[StateUpdate]:
  1429. """Process an event.
  1430. Args:
  1431. app: The app to process the event for.
  1432. event: The event to process.
  1433. sid: The Socket.IO session id.
  1434. headers: The client headers.
  1435. client_ip: The client_ip.
  1436. Raises:
  1437. Exception: If a reflex specific error occurs during processing the event.
  1438. Yields:
  1439. The state updates after processing the event.
  1440. """
  1441. from reflex.utils import telemetry
  1442. try:
  1443. # Add request data to the state.
  1444. router_data = event.router_data
  1445. router_data.update(
  1446. {
  1447. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  1448. constants.RouteVar.CLIENT_TOKEN: event.token,
  1449. constants.RouteVar.SESSION_ID: sid,
  1450. constants.RouteVar.HEADERS: headers,
  1451. constants.RouteVar.CLIENT_IP: client_ip,
  1452. }
  1453. )
  1454. # Get the state for the session exclusively.
  1455. async with app.state_manager.modify_state(event.substate_token) as state:
  1456. # When this is a brand new instance of the state, signal the
  1457. # frontend to reload before processing it.
  1458. if (
  1459. not state.router_data
  1460. and event.name != get_hydrate_event(state)
  1461. and app.event_namespace is not None
  1462. ):
  1463. await asyncio.create_task(
  1464. app.event_namespace.emit(
  1465. "reload",
  1466. data=event,
  1467. to=sid,
  1468. )
  1469. )
  1470. return
  1471. # re-assign only when the value is different
  1472. if state.router_data != router_data:
  1473. # assignment will recurse into substates and force recalculation of
  1474. # dependent ComputedVar (dynamic route variables)
  1475. state.router_data = router_data
  1476. state.router = RouterData(router_data)
  1477. # Preprocess the event.
  1478. update = await app._preprocess(state, event)
  1479. # If there was an update, yield it.
  1480. if update is not None:
  1481. yield update
  1482. # Only process the event if there is no update.
  1483. else:
  1484. if app._process_background(state, event) is not None:
  1485. # `final=True` allows the frontend send more events immediately.
  1486. yield StateUpdate(final=True)
  1487. else:
  1488. # Process the event synchronously.
  1489. async for update in state._process(event):
  1490. # Postprocess the event.
  1491. update = await app._postprocess(state, event, update)
  1492. # Yield the update.
  1493. yield update
  1494. except Exception as ex:
  1495. telemetry.send_error(ex, context="backend")
  1496. app.backend_exception_handler(ex)
  1497. raise
  1498. async def ping(_request: Request) -> Response:
  1499. """Test API endpoint.
  1500. Args:
  1501. _request: The Starlette request object.
  1502. Returns:
  1503. The response.
  1504. """
  1505. return JSONResponse("pong")
  1506. async def health(_request: Request) -> JSONResponse:
  1507. """Health check endpoint to assess the status of the database and Redis services.
  1508. Args:
  1509. _request: The Starlette request object.
  1510. Returns:
  1511. JSONResponse: A JSON object with the health status:
  1512. - "status" (bool): Overall health, True if all checks pass.
  1513. - "db" (bool or str): Database status - True, False, or "NA".
  1514. - "redis" (bool or str): Redis status - True, False, or "NA".
  1515. """
  1516. health_status = {"status": True}
  1517. status_code = 200
  1518. tasks = []
  1519. if prerequisites.check_db_used():
  1520. tasks.append(get_db_status())
  1521. if prerequisites.check_redis_used():
  1522. tasks.append(prerequisites.get_redis_status())
  1523. results = await asyncio.gather(*tasks)
  1524. for result in results:
  1525. health_status |= result
  1526. if "redis" in health_status and health_status["redis"] is None:
  1527. health_status["redis"] = False
  1528. if not all(health_status.values()):
  1529. health_status["status"] = False
  1530. status_code = 503
  1531. return JSONResponse(content=health_status, status_code=status_code)
  1532. def upload(app: App):
  1533. """Upload a file.
  1534. Args:
  1535. app: The app to upload the file for.
  1536. Returns:
  1537. The upload function.
  1538. """
  1539. async def upload_file(request: Request):
  1540. """Upload a file.
  1541. Args:
  1542. request: The Starlette request object.
  1543. Returns:
  1544. StreamingResponse yielding newline-delimited JSON of StateUpdate
  1545. emitted by the upload handler.
  1546. Raises:
  1547. UploadValueError: if there are no args with supported annotation.
  1548. UploadTypeError: if a background task is used as the handler.
  1549. HTTPException: when the request does not include token / handler headers.
  1550. """
  1551. from reflex.utils.exceptions import UploadTypeError, UploadValueError
  1552. # Get the files from the request.
  1553. try:
  1554. files = await request.form()
  1555. except ClientDisconnect:
  1556. return Response() # user cancelled
  1557. files = files.getlist("files")
  1558. if not files:
  1559. msg = "No files were uploaded."
  1560. raise UploadValueError(msg)
  1561. token = request.headers.get("reflex-client-token")
  1562. handler = request.headers.get("reflex-event-handler")
  1563. if not token or not handler:
  1564. raise HTTPException(
  1565. status_code=400,
  1566. detail="Missing reflex-client-token or reflex-event-handler header.",
  1567. )
  1568. # Get the state for the session.
  1569. substate_token = _substate_key(token, handler.rpartition(".")[0])
  1570. state = await app.state_manager.get_state(substate_token)
  1571. # get the current session ID
  1572. # get the current state(parent state/substate)
  1573. path = handler.split(".")[:-1]
  1574. current_state = state.get_substate(path)
  1575. handler_upload_param = ()
  1576. # get handler function
  1577. func = getattr(type(current_state), handler.split(".")[-1])
  1578. # check if there exists any handler args with annotation, list[UploadFile]
  1579. if isinstance(func, EventHandler):
  1580. if func.is_background:
  1581. msg = f"@rx.event(background=True) is not supported for upload handler `{handler}`."
  1582. raise UploadTypeError(msg)
  1583. func = func.fn
  1584. if isinstance(func, functools.partial):
  1585. func = func.func
  1586. for k, v in get_type_hints(func).items():
  1587. if types.is_generic_alias(v) and types._issubclass(
  1588. get_args(v)[0],
  1589. UploadFile,
  1590. ):
  1591. handler_upload_param = (k, v)
  1592. break
  1593. if not handler_upload_param:
  1594. msg = (
  1595. f"`{handler}` handler should have a parameter annotated as "
  1596. "list[rx.UploadFile]"
  1597. )
  1598. raise UploadValueError(msg)
  1599. # Make a copy of the files as they are closed after the request.
  1600. # This behaviour changed from fastapi 0.103.0 to 0.103.1 as the
  1601. # AsyncExitStack was removed from the request scope and is now
  1602. # part of the routing function which closes this before the
  1603. # event is handled.
  1604. file_copies = []
  1605. for file in files:
  1606. if not isinstance(file, StarletteUploadFile):
  1607. raise UploadValueError(
  1608. "Uploaded file is not an UploadFile." + str(file)
  1609. )
  1610. content_copy = io.BytesIO()
  1611. content_copy.write(await file.read())
  1612. content_copy.seek(0)
  1613. file_copies.append(
  1614. UploadFile(
  1615. file=content_copy,
  1616. path=Path(file.filename.lstrip("/")) if file.filename else None,
  1617. _deprecated_filename=file.filename,
  1618. size=file.size,
  1619. headers=file.headers,
  1620. )
  1621. )
  1622. event = Event(
  1623. token=token,
  1624. name=handler,
  1625. payload={handler_upload_param[0]: file_copies},
  1626. )
  1627. async def _ndjson_updates():
  1628. """Process the upload event, generating ndjson updates.
  1629. Yields:
  1630. Each state update as JSON followed by a new line.
  1631. """
  1632. # Process the event.
  1633. async with app.state_manager.modify_state(event.substate_token) as state:
  1634. async for update in state._process(event):
  1635. # Postprocess the event.
  1636. update = await app._postprocess(state, event, update)
  1637. yield update.json() + "\n"
  1638. # Stream updates to client
  1639. return StreamingResponse(
  1640. _ndjson_updates(),
  1641. media_type="application/x-ndjson",
  1642. )
  1643. return upload_file
  1644. class EventNamespace(AsyncNamespace):
  1645. """The event namespace."""
  1646. # The application object.
  1647. app: App
  1648. # Keep a mapping between socket ID and client token.
  1649. token_to_sid: dict[str, str]
  1650. # Keep a mapping between client token and socket ID.
  1651. sid_to_token: dict[str, str]
  1652. def __init__(self, namespace: str, app: App):
  1653. """Initialize the event namespace.
  1654. Args:
  1655. namespace: The namespace.
  1656. app: The application object.
  1657. """
  1658. super().__init__(namespace)
  1659. self.token_to_sid = {}
  1660. self.sid_to_token = {}
  1661. self.app = app
  1662. def on_connect(self, sid: str, environ: dict):
  1663. """Event for when the websocket is connected.
  1664. Args:
  1665. sid: The Socket.IO session id.
  1666. environ: The request information, including HTTP headers.
  1667. """
  1668. subprotocol = environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL")
  1669. if subprotocol and subprotocol != constants.Reflex.VERSION:
  1670. console.warn(
  1671. f"Frontend version {subprotocol} for session {sid} does not match the backend version {constants.Reflex.VERSION}."
  1672. )
  1673. def on_disconnect(self, sid: str):
  1674. """Event for when the websocket disconnects.
  1675. Args:
  1676. sid: The Socket.IO session id.
  1677. """
  1678. disconnect_token = self.sid_to_token.pop(sid, None)
  1679. if disconnect_token:
  1680. self.token_to_sid.pop(disconnect_token, None)
  1681. async def emit_update(self, update: StateUpdate, sid: str) -> None:
  1682. """Emit an update to the client.
  1683. Args:
  1684. update: The state update to send.
  1685. sid: The Socket.IO session id.
  1686. """
  1687. if not sid:
  1688. # If the sid is None, we are not connected to a client. Prevent sending
  1689. # updates to all clients.
  1690. return
  1691. if sid not in self.sid_to_token:
  1692. console.warn(f"Attempting to send delta to disconnected websocket {sid}")
  1693. return
  1694. # Creating a task prevents the update from being blocked behind other coroutines.
  1695. await asyncio.create_task(
  1696. self.emit(str(constants.SocketEvent.EVENT), update, to=sid)
  1697. )
  1698. async def on_event(self, sid: str, data: Any):
  1699. """Event for receiving front-end websocket events.
  1700. Raises:
  1701. RuntimeError: If the Socket.IO is badly initialized.
  1702. Args:
  1703. sid: The Socket.IO session id.
  1704. data: The event data.
  1705. Raises:
  1706. EventDeserializationError: If the event data is not a dictionary.
  1707. """
  1708. fields = data
  1709. if isinstance(fields, str):
  1710. console.warn(
  1711. "Received event data as a string. This generally should not happen and may indicate a bug."
  1712. f" Event data: {fields}"
  1713. )
  1714. try:
  1715. fields = json.loads(fields)
  1716. except json.JSONDecodeError as ex:
  1717. msg = f"Failed to deserialize event data: {fields}."
  1718. raise exceptions.EventDeserializationError(msg) from ex
  1719. if not isinstance(fields, dict):
  1720. msg = f"Event data must be a dictionary, but received {fields} of type {type(fields)}."
  1721. raise exceptions.EventDeserializationError(msg)
  1722. try:
  1723. # Get the event.
  1724. event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS})
  1725. except (TypeError, ValueError) as ex:
  1726. msg = f"Failed to deserialize event data: {fields}."
  1727. raise exceptions.EventDeserializationError(msg) from ex
  1728. self.token_to_sid[event.token] = sid
  1729. self.sid_to_token[sid] = event.token
  1730. # Get the event environment.
  1731. if self.app.sio is None:
  1732. msg = "Socket.IO is not initialized."
  1733. raise RuntimeError(msg)
  1734. environ = self.app.sio.get_environ(sid, self.namespace)
  1735. if environ is None:
  1736. msg = "Socket.IO environ is not initialized."
  1737. raise RuntimeError(msg)
  1738. # Get the client headers.
  1739. headers = {
  1740. k.decode("utf-8"): v.decode("utf-8")
  1741. for (k, v) in environ["asgi.scope"]["headers"]
  1742. }
  1743. # Get the client IP
  1744. try:
  1745. client_ip = environ["asgi.scope"]["client"][0]
  1746. except (KeyError, IndexError):
  1747. client_ip = environ.get("REMOTE_ADDR", "0.0.0.0")
  1748. # Process the events.
  1749. async for update in process(self.app, event, sid, headers, client_ip):
  1750. # Emit the update from processing the event.
  1751. await self.emit_update(update=update, sid=sid)
  1752. async def on_ping(self, sid: str):
  1753. """Event for testing the API endpoint.
  1754. Args:
  1755. sid: The Socket.IO session id.
  1756. """
  1757. # Emit the test event.
  1758. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)