app.py 75 KB

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