app.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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 functools
  8. import inspect
  9. import io
  10. import multiprocessing
  11. import os
  12. import platform
  13. import sys
  14. from datetime import datetime
  15. from typing import (
  16. Any,
  17. AsyncIterator,
  18. Callable,
  19. Coroutine,
  20. Dict,
  21. List,
  22. Optional,
  23. Set,
  24. Type,
  25. Union,
  26. get_args,
  27. get_type_hints,
  28. )
  29. from fastapi import FastAPI, HTTPException, Request, UploadFile
  30. from fastapi.middleware import cors
  31. from fastapi.responses import StreamingResponse
  32. from fastapi.staticfiles import StaticFiles
  33. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  34. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  35. from starlette_admin.contrib.sqla.admin import Admin
  36. from starlette_admin.contrib.sqla.view import ModelView
  37. from reflex import constants
  38. from reflex.admin import AdminDash
  39. from reflex.base import Base
  40. from reflex.compiler import compiler
  41. from reflex.compiler import utils as compiler_utils
  42. from reflex.compiler.compiler import ExecutorSafeFunctions
  43. from reflex.components.base.app_wrap import AppWrap
  44. from reflex.components.base.fragment import Fragment
  45. from reflex.components.component import (
  46. Component,
  47. ComponentStyle,
  48. evaluate_style_namespaces,
  49. )
  50. from reflex.components.core.banner import connection_pulser, connection_toaster
  51. from reflex.components.core.breakpoints import set_breakpoints
  52. from reflex.components.core.client_side_routing import (
  53. Default404Page,
  54. wait_for_client_redirect,
  55. )
  56. from reflex.components.core.upload import Upload, get_upload_dir
  57. from reflex.components.radix import themes
  58. from reflex.config import get_config
  59. from reflex.event import Event, EventHandler, EventSpec
  60. from reflex.middleware import HydrateMiddleware, Middleware
  61. from reflex.model import Model
  62. from reflex.page import (
  63. DECORATED_PAGES,
  64. )
  65. from reflex.route import (
  66. get_route_args,
  67. replace_brackets_with_keywords,
  68. verify_route_validity,
  69. )
  70. from reflex.state import (
  71. BaseState,
  72. RouterData,
  73. State,
  74. StateManager,
  75. StateUpdate,
  76. _substate_key,
  77. code_uses_state_contexts,
  78. )
  79. from reflex.utils import codespaces, console, exceptions, format, prerequisites, types
  80. from reflex.utils.exec import is_testing_env, should_skip_compile
  81. from reflex.utils.imports import ImportVar
  82. # Define custom types.
  83. ComponentCallable = Callable[[], Component]
  84. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  85. def default_overlay_component() -> Component:
  86. """Default overlay_component attribute for App.
  87. Returns:
  88. The default overlay_component, which is a connection_modal.
  89. """
  90. return Fragment.create(
  91. connection_pulser(),
  92. connection_toaster(),
  93. *codespaces.codespaces_auto_redirect(),
  94. )
  95. class OverlayFragment(Fragment):
  96. """Alias for Fragment, used to wrap the overlay_component."""
  97. pass
  98. class LifespanMixin(Base):
  99. """A Mixin that allow tasks to run during the whole app lifespan."""
  100. # Lifespan tasks that are planned to run.
  101. lifespan_tasks: Set[Union[asyncio.Task, Callable]] = set()
  102. @contextlib.asynccontextmanager
  103. async def _run_lifespan_tasks(self, app: FastAPI):
  104. running_tasks = []
  105. try:
  106. async with contextlib.AsyncExitStack() as stack:
  107. for task in self.lifespan_tasks:
  108. if isinstance(task, asyncio.Task):
  109. running_tasks.append(task)
  110. else:
  111. signature = inspect.signature(task)
  112. if "app" in signature.parameters:
  113. task = functools.partial(task, app=app)
  114. _t = task()
  115. if isinstance(_t, contextlib._AsyncGeneratorContextManager):
  116. await stack.enter_async_context(_t)
  117. elif isinstance(_t, Coroutine):
  118. running_tasks.append(asyncio.create_task(_t))
  119. yield
  120. finally:
  121. cancel_kwargs = (
  122. {"msg": "lifespan_cleanup"} if sys.version_info >= (3, 9) else {}
  123. )
  124. for task in running_tasks:
  125. task.cancel(**cancel_kwargs)
  126. def register_lifespan_task(self, task: Callable | asyncio.Task, **task_kwargs):
  127. """Register a task to run during the lifespan of the app.
  128. Args:
  129. task: The task to register.
  130. task_kwargs: The kwargs of the task.
  131. """
  132. if task_kwargs:
  133. task = functools.partial(task, **task_kwargs) # type: ignore
  134. self.lifespan_tasks.add(task) # type: ignore
  135. class App(LifespanMixin, Base):
  136. """The main Reflex app that encapsulates the backend and frontend.
  137. Every Reflex app needs an app defined in its main module.
  138. ```python
  139. # app.py
  140. import reflex as rx
  141. # Define state and pages
  142. ...
  143. app = rx.App(
  144. # Set global level style.
  145. style={...},
  146. # Set the top level theme.
  147. theme=rx.theme(accent_color="blue"),
  148. )
  149. ```
  150. """
  151. # The global [theme](https://reflex.dev/docs/styling/theming/#theme) for the entire app.
  152. theme: Optional[Component] = themes.theme(accent_color="blue")
  153. # The [global style](https://reflex.dev/docs/styling/overview/#global-styles}) for the app.
  154. style: ComponentStyle = {}
  155. # A list of URLs to [stylesheets](https://reflex.dev/docs/styling/custom-stylesheets/) to include in the app.
  156. stylesheets: List[str] = []
  157. # A component that is present on every page (defaults to the Connection Error banner).
  158. overlay_component: Optional[Union[Component, ComponentCallable]] = (
  159. default_overlay_component
  160. )
  161. # Components to add to the head of every page.
  162. head_components: List[Component] = []
  163. # The Socket.IO AsyncServer instance.
  164. sio: Optional[AsyncServer] = None
  165. # The language to add to the html root tag of every page.
  166. html_lang: Optional[str] = None
  167. # Attributes to add to the html root tag of every page.
  168. html_custom_attrs: Optional[Dict[str, str]] = None
  169. # A map from a page route to the component to render. Users should use `add_page`. PRIVATE.
  170. pages: Dict[str, Component] = {}
  171. # The backend API object. PRIVATE.
  172. api: FastAPI = None # type: ignore
  173. # The state class to use for the app. PRIVATE.
  174. state: Optional[Type[BaseState]] = None
  175. # Class to manage many client states.
  176. _state_manager: Optional[StateManager] = None
  177. # Middleware to add to the app. Users should use `add_middleware`. PRIVATE.
  178. middleware: List[Middleware] = []
  179. # Mapping from a route to event handlers to trigger when the page loads. PRIVATE.
  180. load_events: Dict[str, List[Union[EventHandler, EventSpec]]] = {}
  181. # Admin dashboard to view and manage the database. PRIVATE.
  182. admin_dash: Optional[AdminDash] = None
  183. # The async server name space. PRIVATE.
  184. event_namespace: Optional[EventNamespace] = None
  185. # Background tasks that are currently running. PRIVATE.
  186. background_tasks: Set[asyncio.Task] = set()
  187. def __init__(self, **kwargs):
  188. """Initialize the app.
  189. Args:
  190. **kwargs: Kwargs to initialize the app with.
  191. Raises:
  192. ValueError: If the event namespace is not provided in the config.
  193. Also, if there are multiple client subclasses of rx.BaseState(Subclasses of rx.BaseState should consist
  194. of the DefaultState and the client app state).
  195. """
  196. if "connect_error_component" in kwargs:
  197. raise ValueError(
  198. "`connect_error_component` is deprecated, use `overlay_component` instead"
  199. )
  200. super().__init__(**kwargs)
  201. base_state_subclasses = BaseState.__subclasses__()
  202. # Special case to allow test cases have multiple subclasses of rx.BaseState.
  203. if not is_testing_env() and len(base_state_subclasses) > 1:
  204. # Only one Base State class is allowed.
  205. raise ValueError(
  206. "rx.BaseState cannot be subclassed multiple times. use rx.State instead"
  207. )
  208. if "breakpoints" in self.style:
  209. set_breakpoints(self.style.pop("breakpoints"))
  210. # Add middleware.
  211. self.middleware.append(HydrateMiddleware())
  212. # Set up the API.
  213. self.api = FastAPI(lifespan=self._run_lifespan_tasks)
  214. self._add_cors()
  215. self._add_default_endpoints()
  216. self._setup_state()
  217. # Set up the admin dash.
  218. self._setup_admin_dash()
  219. def _enable_state(self) -> None:
  220. """Enable state for the app."""
  221. if not self.state:
  222. self.state = State
  223. self._setup_state()
  224. def _setup_state(self) -> None:
  225. """Set up the state for the app.
  226. Raises:
  227. RuntimeError: If the socket server is invalid.
  228. """
  229. if not self.state:
  230. return
  231. config = get_config()
  232. # Set up the state manager.
  233. self._state_manager = StateManager.create(state=self.state)
  234. # Set up the Socket.IO AsyncServer.
  235. if not self.sio:
  236. self.sio = AsyncServer(
  237. async_mode="asgi",
  238. cors_allowed_origins=(
  239. "*"
  240. if config.cors_allowed_origins == ["*"]
  241. else config.cors_allowed_origins
  242. ),
  243. cors_credentials=True,
  244. max_http_buffer_size=constants.POLLING_MAX_HTTP_BUFFER_SIZE,
  245. ping_interval=constants.Ping.INTERVAL,
  246. ping_timeout=constants.Ping.TIMEOUT,
  247. )
  248. elif getattr(self.sio, "async_mode", "") != "asgi":
  249. raise RuntimeError(
  250. f"Custom `sio` must use `async_mode='asgi'`, not '{self.sio.async_mode}'."
  251. )
  252. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  253. socket_app = ASGIApp(self.sio, socketio_path="")
  254. namespace = config.get_event_namespace()
  255. # Create the event namespace and attach the main app. Not related to any paths.
  256. self.event_namespace = EventNamespace(namespace, self)
  257. # Register the event namespace with the socket.
  258. self.sio.register_namespace(self.event_namespace)
  259. # Mount the socket app with the API.
  260. self.api.mount(str(constants.Endpoint.EVENT), socket_app)
  261. def __repr__(self) -> str:
  262. """Get the string representation of the app.
  263. Returns:
  264. The string representation of the app.
  265. """
  266. return f"<App state={self.state.__name__ if self.state else None}>"
  267. def __call__(self) -> FastAPI:
  268. """Run the backend api instance.
  269. Returns:
  270. The backend api.
  271. """
  272. return self.api
  273. def _add_default_endpoints(self):
  274. """Add default api endpoints (ping)."""
  275. # To test the server.
  276. self.api.get(str(constants.Endpoint.PING))(ping)
  277. def _add_optional_endpoints(self):
  278. """Add optional api endpoints (_upload)."""
  279. # To upload files.
  280. if Upload.is_used:
  281. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  282. # To access uploaded files.
  283. self.api.mount(
  284. str(constants.Endpoint.UPLOAD),
  285. StaticFiles(directory=get_upload_dir()),
  286. name="uploaded_files",
  287. )
  288. if codespaces.is_running_in_codespaces():
  289. self.api.get(str(constants.Endpoint.AUTH_CODESPACE))(
  290. codespaces.auth_codespace
  291. )
  292. def _add_cors(self):
  293. """Add CORS middleware to the app."""
  294. self.api.add_middleware(
  295. cors.CORSMiddleware,
  296. allow_credentials=True,
  297. allow_methods=["*"],
  298. allow_headers=["*"],
  299. allow_origins=["*"],
  300. )
  301. @property
  302. def state_manager(self) -> StateManager:
  303. """Get the state manager.
  304. Returns:
  305. The initialized state manager.
  306. Raises:
  307. ValueError: if the state has not been initialized.
  308. """
  309. if self._state_manager is None:
  310. raise ValueError("The state manager has not been initialized.")
  311. return self._state_manager
  312. async def _preprocess(self, state: BaseState, event: Event) -> StateUpdate | None:
  313. """Preprocess the event.
  314. This is where middleware can modify the event before it is processed.
  315. Each middleware is called in the order it was added to the app.
  316. If a middleware returns an update, the event is not processed and the
  317. update is returned.
  318. Args:
  319. state: The state to preprocess.
  320. event: The event to preprocess.
  321. Returns:
  322. An optional state to return.
  323. """
  324. for middleware in self.middleware:
  325. if asyncio.iscoroutinefunction(middleware.preprocess):
  326. out = await middleware.preprocess(app=self, state=state, event=event) # type: ignore
  327. else:
  328. out = middleware.preprocess(app=self, state=state, event=event) # type: ignore
  329. if out is not None:
  330. return out # type: ignore
  331. async def _postprocess(
  332. self, state: BaseState, event: Event, update: StateUpdate
  333. ) -> StateUpdate:
  334. """Postprocess the event.
  335. This is where middleware can modify the delta after it is processed.
  336. Each middleware is called in the order it was added to the app.
  337. Args:
  338. state: The state to postprocess.
  339. event: The event to postprocess.
  340. update: The current state update.
  341. Returns:
  342. The state update to return.
  343. """
  344. for middleware in self.middleware:
  345. if asyncio.iscoroutinefunction(middleware.postprocess):
  346. out = await middleware.postprocess(
  347. app=self, # type: ignore
  348. state=state,
  349. event=event,
  350. update=update,
  351. )
  352. else:
  353. out = middleware.postprocess(
  354. app=self, # type: ignore
  355. state=state,
  356. event=event,
  357. update=update,
  358. )
  359. if out is not None:
  360. return out # type: ignore
  361. return update
  362. def add_middleware(self, middleware: Middleware, index: int | None = None):
  363. """Add middleware to the app.
  364. Args:
  365. middleware: The middleware to add.
  366. index: The index to add the middleware at.
  367. """
  368. if index is None:
  369. self.middleware.append(middleware)
  370. else:
  371. self.middleware.insert(index, middleware)
  372. @staticmethod
  373. def _generate_component(component: Component | ComponentCallable) -> Component:
  374. """Generate a component from a callable.
  375. Args:
  376. component: The component function to call or Component to return as-is.
  377. Returns:
  378. The generated component.
  379. Raises:
  380. VarOperationTypeError: When an invalid component var related function is passed.
  381. TypeError: When an invalid component function is passed.
  382. exceptions.MatchTypeError: If the return types of match cases in rx.match are different.
  383. """
  384. from reflex.utils.exceptions import VarOperationTypeError
  385. try:
  386. return component if isinstance(component, Component) else component()
  387. except exceptions.MatchTypeError:
  388. raise
  389. except TypeError as e:
  390. message = str(e)
  391. if "BaseVar" in message or "ComputedVar" in message:
  392. raise VarOperationTypeError(
  393. "You may be trying to use an invalid Python function on a state var. "
  394. "When referencing a var inside your render code, only limited var operations are supported. "
  395. "See the var operation docs here: https://reflex.dev/docs/vars/var-operations/"
  396. ) from e
  397. raise e
  398. def add_page(
  399. self,
  400. component: Component | ComponentCallable,
  401. route: str | None = None,
  402. title: str | None = None,
  403. description: str | None = None,
  404. image: str = constants.DefaultPage.IMAGE,
  405. on_load: (
  406. EventHandler | EventSpec | list[EventHandler | EventSpec] | None
  407. ) = None,
  408. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  409. ):
  410. """Add a page to the app.
  411. If the component is a callable, by default the route is the name of the
  412. function. Otherwise, a route must be provided.
  413. Args:
  414. component: The component to display at the page.
  415. route: The route to display the component at.
  416. title: The title of the page.
  417. description: The description of the page.
  418. image: The image to display on the page.
  419. on_load: The event handler(s) that will be called each time the page load.
  420. meta: The metadata of the page.
  421. Raises:
  422. ValueError: When the specified route name already exists.
  423. """
  424. # If the route is not set, get it from the callable.
  425. if route is None:
  426. assert isinstance(
  427. component, Callable
  428. ), "Route must be set if component is not a callable."
  429. # Format the route.
  430. route = format.format_route(component.__name__)
  431. else:
  432. route = format.format_route(route, format_case=False)
  433. # Check if the route given is valid
  434. verify_route_validity(route)
  435. if route in self.pages and os.getenv(constants.RELOAD_CONFIG):
  436. # when the app is reloaded(typically for app harness tests), we should maintain
  437. # the latest render function of a route.This applies typically to decorated pages
  438. # since they are only added when app._compile is called.
  439. self.pages.pop(route)
  440. if route in self.pages:
  441. route_name = (
  442. f"`{route}` or `/`"
  443. if route == constants.PageNames.INDEX_ROUTE
  444. else f"`{route}`"
  445. )
  446. raise ValueError(
  447. f"Duplicate page route {route_name} already exists. Make sure you do not have two"
  448. f" pages with the same route"
  449. )
  450. # Setup dynamic args for the route.
  451. # this state assignment is only required for tests using the deprecated state kwarg for App
  452. state = self.state if self.state else State
  453. state.setup_dynamic_args(get_route_args(route))
  454. # Generate the component if it is a callable.
  455. component = self._generate_component(component)
  456. # unpack components that return tuples in an rx.fragment.
  457. if isinstance(component, tuple):
  458. component = Fragment.create(*component)
  459. # Ensure state is enabled if this page uses state.
  460. if self.state is None:
  461. if on_load or component._has_stateful_event_triggers():
  462. self._enable_state()
  463. else:
  464. for var in component._get_vars(include_children=True):
  465. if not var._var_data:
  466. continue
  467. if not var._var_data.state:
  468. continue
  469. self._enable_state()
  470. break
  471. component = OverlayFragment.create(component)
  472. meta_args = {
  473. "title": (
  474. title
  475. if title is not None
  476. else format.make_default_page_title(get_config().app_name, route)
  477. ),
  478. "image": image,
  479. "meta": meta,
  480. }
  481. if description is not None:
  482. meta_args["description"] = description
  483. # Add meta information to the component.
  484. compiler_utils.add_meta(
  485. component,
  486. **meta_args,
  487. )
  488. # Add the page.
  489. self._check_routes_conflict(route)
  490. self.pages[route] = component
  491. # Add the load events.
  492. if on_load:
  493. if not isinstance(on_load, list):
  494. on_load = [on_load]
  495. self.load_events[route] = on_load
  496. def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
  497. """Get the load events for a route.
  498. Args:
  499. route: The route to get the load events for.
  500. Returns:
  501. The load events for the route.
  502. """
  503. route = route.lstrip("/")
  504. if route == "":
  505. route = constants.PageNames.INDEX_ROUTE
  506. return self.load_events.get(route, [])
  507. def _check_routes_conflict(self, new_route: str):
  508. """Verify if there is any conflict between the new route and any existing route.
  509. Based on conflicts that NextJS would throw if not intercepted.
  510. Raises:
  511. RouteValueError: exception showing which conflict exist with the route to be added
  512. Args:
  513. new_route: the route being newly added.
  514. """
  515. from reflex.utils.exceptions import RouteValueError
  516. if "[" not in new_route:
  517. return
  518. segments = (
  519. constants.RouteRegex.SINGLE_SEGMENT,
  520. constants.RouteRegex.DOUBLE_SEGMENT,
  521. constants.RouteRegex.SINGLE_CATCHALL_SEGMENT,
  522. constants.RouteRegex.DOUBLE_CATCHALL_SEGMENT,
  523. )
  524. for route in self.pages:
  525. replaced_route = replace_brackets_with_keywords(route)
  526. for rw, r, nr in zip(
  527. replaced_route.split("/"), route.split("/"), new_route.split("/")
  528. ):
  529. if rw in segments and r != nr:
  530. # If the slugs in the segments of both routes are not the same, then the route is invalid
  531. raise RouteValueError(
  532. f"You cannot use different slug names for the same dynamic path in {route} and {new_route} ('{r}' != '{nr}')"
  533. )
  534. elif rw not in segments and r != nr:
  535. # if the section being compared in both routes is not a dynamic segment(i.e not wrapped in brackets)
  536. # then we are guaranteed that the route is valid and there's no need checking the rest.
  537. # eg. /posts/[id]/info/[slug1] and /posts/[id]/info1/[slug1] is always going to be valid since
  538. # info1 will break away into its own tree.
  539. break
  540. def add_custom_404_page(
  541. self,
  542. component: Component | ComponentCallable | None = None,
  543. title: str = constants.Page404.TITLE,
  544. image: str = constants.Page404.IMAGE,
  545. description: str = constants.Page404.DESCRIPTION,
  546. on_load: (
  547. EventHandler | EventSpec | list[EventHandler | EventSpec] | None
  548. ) = None,
  549. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  550. ):
  551. """Define a custom 404 page for any url having no match.
  552. If there is no page defined on 'index' route, add the 404 page to it.
  553. If there is no global catchall defined, add the 404 page with a catchall.
  554. Args:
  555. component: The component to display at the page.
  556. title: The title of the page.
  557. description: The description of the page.
  558. image: The image to display on the page.
  559. on_load: The event handler(s) that will be called each time the page load.
  560. meta: The metadata of the page.
  561. """
  562. if component is None:
  563. component = Default404Page.create()
  564. self.add_page(
  565. component=wait_for_client_redirect(self._generate_component(component)),
  566. route=constants.Page404.SLUG,
  567. title=title or constants.Page404.TITLE,
  568. image=image or constants.Page404.IMAGE,
  569. description=description or constants.Page404.DESCRIPTION,
  570. on_load=on_load,
  571. meta=meta,
  572. )
  573. def _setup_admin_dash(self):
  574. """Setup the admin dash."""
  575. # Get the admin dash.
  576. admin_dash = self.admin_dash
  577. if admin_dash and admin_dash.models:
  578. # Build the admin dashboard
  579. admin = (
  580. admin_dash.admin
  581. if admin_dash.admin
  582. else Admin(
  583. engine=Model.get_db_engine(),
  584. title="Reflex Admin Dashboard",
  585. logo_url="https://reflex.dev/Reflex.svg",
  586. )
  587. )
  588. for model in admin_dash.models:
  589. view = admin_dash.view_overrides.get(model, ModelView)
  590. admin.add_view(view(model))
  591. admin.mount_to(self.api)
  592. def _get_frontend_packages(self, imports: Dict[str, set[ImportVar]]):
  593. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  594. Args:
  595. imports: A dictionary containing the imports used in the current page.
  596. Example:
  597. >>> _get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  598. """
  599. page_imports = {
  600. i
  601. for i, tags in imports.items()
  602. if i not in constants.PackageJson.DEPENDENCIES
  603. and i not in constants.PackageJson.DEV_DEPENDENCIES
  604. and not any(i.startswith(prefix) for prefix in ["/", ".", "next/"])
  605. and i != ""
  606. and any(tag.install for tag in tags)
  607. }
  608. frontend_packages = get_config().frontend_packages
  609. _frontend_packages = []
  610. for package in frontend_packages:
  611. if package in (get_config().tailwind or {}).get("plugins", []): # type: ignore
  612. console.warn(
  613. f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`"
  614. )
  615. continue
  616. if package in page_imports:
  617. console.warn(
  618. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  619. )
  620. continue
  621. _frontend_packages.append(package)
  622. page_imports.update(_frontend_packages)
  623. prerequisites.install_frontend_packages(page_imports, get_config())
  624. def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component:
  625. for component in tuple(app_wrappers.values()):
  626. app_wrappers.update(component._get_all_app_wrap_components())
  627. order = sorted(app_wrappers, key=lambda k: k[0], reverse=True)
  628. root = parent = copy.deepcopy(app_wrappers[order[0]])
  629. for key in order[1:]:
  630. child = copy.deepcopy(app_wrappers[key])
  631. parent.children.append(child)
  632. parent = child
  633. return root
  634. def _should_compile(self) -> bool:
  635. """Check if the app should be compiled.
  636. Returns:
  637. Whether the app should be compiled.
  638. """
  639. # Check the environment variable.
  640. if should_skip_compile():
  641. return False
  642. nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
  643. # Check the nocompile file.
  644. if nocompile.exists():
  645. # Delete the nocompile file
  646. nocompile.unlink()
  647. return False
  648. # By default, compile the app.
  649. return True
  650. def _add_overlay_to_component(self, component: Component) -> Component:
  651. if self.overlay_component is None:
  652. return component
  653. children = component.children
  654. overlay_component = self._generate_component(self.overlay_component)
  655. if children[0] == overlay_component:
  656. return component
  657. # recreate OverlayFragment with overlay_component as first child
  658. component = OverlayFragment.create(overlay_component, *children)
  659. return component
  660. def _setup_overlay_component(self):
  661. """If a State is not used and no overlay_component is specified, do not render the connection modal."""
  662. if self.state is None and self.overlay_component is default_overlay_component:
  663. self.overlay_component = None
  664. for k, component in self.pages.items():
  665. self.pages[k] = self._add_overlay_to_component(component)
  666. def _apply_decorated_pages(self):
  667. """Add @rx.page decorated pages to the app.
  668. This has to be done in the MainThread for py38 and py39 compatibility, so the
  669. decorated pages are added to the app before the app is compiled (in a thread)
  670. to workaround REF-2172.
  671. This can move back into `compile_` when py39 support is dropped.
  672. """
  673. # Add the @rx.page decorated pages to collect on_load events.
  674. for render, kwargs in DECORATED_PAGES[get_config().app_name]:
  675. self.add_page(render, **kwargs)
  676. def _validate_var_dependencies(
  677. self, state: Optional[Type[BaseState]] = None
  678. ) -> None:
  679. """Validate the dependencies of the vars in the app.
  680. Args:
  681. state: The state to validate the dependencies for.
  682. Raises:
  683. VarDependencyError: When a computed var has an invalid dependency.
  684. """
  685. if not self.state:
  686. return
  687. if not state:
  688. state = self.state
  689. for var in state.computed_vars.values():
  690. deps = var._deps(objclass=state)
  691. for dep in deps:
  692. if dep not in state.vars and dep not in state.backend_vars:
  693. raise exceptions.VarDependencyError(
  694. f"ComputedVar {var._var_name} on state {state.__name__} has an invalid dependency {dep}"
  695. )
  696. for substate in state.class_subclasses:
  697. self._validate_var_dependencies(substate)
  698. def _compile(self, export: bool = False):
  699. """Compile the app and output it to the pages folder.
  700. Args:
  701. export: Whether to compile the app for export.
  702. Raises:
  703. ReflexRuntimeError: When any page uses state, but no rx.State subclass is defined.
  704. """
  705. from reflex.utils.exceptions import ReflexRuntimeError
  706. def get_compilation_time() -> str:
  707. return str(datetime.now().time()).split(".")[0]
  708. # Render a default 404 page if the user didn't supply one
  709. if constants.Page404.SLUG not in self.pages:
  710. self.add_custom_404_page()
  711. # Add the optional endpoints (_upload)
  712. self._add_optional_endpoints()
  713. if not self._should_compile():
  714. return
  715. self._validate_var_dependencies()
  716. self._setup_overlay_component()
  717. # Create a progress bar.
  718. progress = Progress(
  719. *Progress.get_default_columns()[:-1],
  720. MofNCompleteColumn(),
  721. TimeElapsedColumn(),
  722. )
  723. # try to be somewhat accurate - but still not 100%
  724. adhoc_steps_without_executor = 6
  725. fixed_pages_within_executor = 5
  726. progress.start()
  727. task = progress.add_task(
  728. f"[{get_compilation_time()}] Compiling:",
  729. total=len(self.pages)
  730. + fixed_pages_within_executor
  731. + adhoc_steps_without_executor,
  732. )
  733. # Get the env mode.
  734. config = get_config()
  735. # Store the compile results.
  736. compile_results = []
  737. # Add the app wrappers.
  738. app_wrappers: Dict[tuple[int, str], Component] = {
  739. # Default app wrap component renders {children}
  740. (0, "AppWrap"): AppWrap.create()
  741. }
  742. if self.theme is not None:
  743. # If a theme component was provided, wrap the app with it
  744. app_wrappers[(20, "Theme")] = self.theme
  745. progress.advance(task)
  746. # Fix up the style.
  747. self.style = evaluate_style_namespaces(self.style)
  748. # Track imports and custom components found.
  749. all_imports = {}
  750. custom_components = set()
  751. for _route, component in self.pages.items():
  752. # Merge the component style with the app style.
  753. component._add_style_recursive(self.style, self.theme)
  754. # Add component._get_all_imports() to all_imports.
  755. all_imports.update(component._get_all_imports())
  756. # Add the app wrappers from this component.
  757. app_wrappers.update(component._get_all_app_wrap_components())
  758. # Add the custom components from the page to the set.
  759. custom_components |= component._get_all_custom_components()
  760. progress.advance(task)
  761. # Perform auto-memoization of stateful components.
  762. (
  763. stateful_components_path,
  764. stateful_components_code,
  765. page_components,
  766. ) = compiler.compile_stateful_components(self.pages.values())
  767. progress.advance(task)
  768. # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State.
  769. if code_uses_state_contexts(stateful_components_code) and self.state is None:
  770. raise ReflexRuntimeError(
  771. "To access rx.State in frontend components, at least one "
  772. "subclass of rx.State must be defined in the app."
  773. )
  774. compile_results.append((stateful_components_path, stateful_components_code))
  775. # Compile the root document before fork.
  776. compile_results.append(
  777. compiler.compile_document_root(
  778. self.head_components,
  779. html_lang=self.html_lang,
  780. html_custom_attrs=self.html_custom_attrs, # type: ignore
  781. )
  782. )
  783. # Compile the contexts before fork.
  784. compile_results.append(
  785. compiler.compile_contexts(self.state, self.theme),
  786. )
  787. # Fix #2992 by removing the top-level appearance prop
  788. if self.theme is not None:
  789. self.theme.appearance = None
  790. app_root = self._app_root(app_wrappers=app_wrappers)
  791. progress.advance(task)
  792. # Prepopulate the global ExecutorSafeFunctions class with input data required by the compile functions.
  793. # This is required for multiprocessing to work, in presence of non-picklable inputs.
  794. for route, component in zip(self.pages, page_components):
  795. ExecutorSafeFunctions.COMPILE_PAGE_ARGS_BY_ROUTE[route] = (
  796. route,
  797. component,
  798. self.state,
  799. )
  800. ExecutorSafeFunctions.COMPILE_APP_APP_ROOT = app_root
  801. ExecutorSafeFunctions.CUSTOM_COMPONENTS = custom_components
  802. ExecutorSafeFunctions.STYLE = self.style
  803. # Use a forking process pool, if possible. Much faster, especially for large sites.
  804. # Fallback to ThreadPoolExecutor as something that will always work.
  805. executor = None
  806. if (
  807. platform.system() in ("Linux", "Darwin")
  808. and os.environ.get("REFLEX_COMPILE_PROCESSES") is not None
  809. ):
  810. executor = concurrent.futures.ProcessPoolExecutor(
  811. max_workers=int(os.environ.get("REFLEX_COMPILE_PROCESSES", 0)) or None,
  812. mp_context=multiprocessing.get_context("fork"),
  813. )
  814. else:
  815. executor = concurrent.futures.ThreadPoolExecutor(
  816. max_workers=int(os.environ.get("REFLEX_COMPILE_THREADS", 0)) or None,
  817. )
  818. with executor:
  819. result_futures = []
  820. custom_components_future = None
  821. def _mark_complete(_=None):
  822. progress.advance(task)
  823. def _submit_work(fn, *args, **kwargs):
  824. f = executor.submit(fn, *args, **kwargs)
  825. f.add_done_callback(_mark_complete)
  826. result_futures.append(f)
  827. # Compile all page components.
  828. for route in self.pages:
  829. _submit_work(ExecutorSafeFunctions.compile_page, route)
  830. # Compile the app wrapper.
  831. _submit_work(ExecutorSafeFunctions.compile_app)
  832. # Compile the custom components.
  833. custom_components_future = executor.submit(
  834. ExecutorSafeFunctions.compile_custom_components,
  835. )
  836. custom_components_future.add_done_callback(_mark_complete)
  837. # Compile the root stylesheet with base styles.
  838. _submit_work(compiler.compile_root_stylesheet, self.stylesheets)
  839. # Compile the theme.
  840. _submit_work(ExecutorSafeFunctions.compile_theme)
  841. # Compile the Tailwind config.
  842. if config.tailwind is not None:
  843. config.tailwind["content"] = config.tailwind.get(
  844. "content", constants.Tailwind.CONTENT
  845. )
  846. _submit_work(compiler.compile_tailwind, config.tailwind)
  847. else:
  848. _submit_work(compiler.remove_tailwind_from_postcss)
  849. # Wait for all compilation tasks to complete.
  850. for future in concurrent.futures.as_completed(result_futures):
  851. compile_results.append(future.result())
  852. # Special case for custom_components, since we need the compiled imports
  853. # to install proper frontend packages.
  854. (
  855. *custom_components_result,
  856. custom_components_imports,
  857. ) = custom_components_future.result()
  858. compile_results.append(custom_components_result)
  859. all_imports.update(custom_components_imports)
  860. # Get imports from AppWrap components.
  861. all_imports.update(app_root._get_all_imports())
  862. progress.advance(task)
  863. # Empty the .web pages directory.
  864. compiler.purge_web_pages_dir()
  865. progress.advance(task)
  866. progress.stop()
  867. # Install frontend packages.
  868. self._get_frontend_packages(all_imports)
  869. # Setup the next.config.js
  870. transpile_packages = [
  871. package
  872. for package, import_vars in all_imports.items()
  873. if any(import_var.transpile for import_var in import_vars)
  874. ]
  875. prerequisites.update_next_config(
  876. export=export,
  877. transpile_packages=transpile_packages,
  878. )
  879. for output_path, code in compile_results:
  880. compiler_utils.write_page(output_path, code)
  881. @contextlib.asynccontextmanager
  882. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  883. """Modify the state out of band.
  884. Args:
  885. token: The token to modify the state for.
  886. Yields:
  887. The state to modify.
  888. Raises:
  889. RuntimeError: If the app has not been initialized yet.
  890. """
  891. if self.event_namespace is None:
  892. raise RuntimeError("App has not been initialized yet.")
  893. # Get exclusive access to the state.
  894. async with self.state_manager.modify_state(token) as state:
  895. # No other event handler can modify the state while in this context.
  896. yield state
  897. delta = state.get_delta()
  898. if delta:
  899. # When the state is modified reset dirty status and emit the delta to the frontend.
  900. state._clean()
  901. await self.event_namespace.emit_update(
  902. update=StateUpdate(delta=delta),
  903. sid=state.router.session.session_id,
  904. )
  905. def _process_background(
  906. self, state: BaseState, event: Event
  907. ) -> asyncio.Task | None:
  908. """Process an event in the background and emit updates as they arrive.
  909. Args:
  910. state: The state to process the event for.
  911. event: The event to process.
  912. Returns:
  913. Task if the event was backgroundable, otherwise None
  914. """
  915. substate, handler = state._get_event_handler(event)
  916. if not handler.is_background:
  917. return None
  918. async def _coro():
  919. """Coroutine to process the event and emit updates inside an asyncio.Task.
  920. Raises:
  921. RuntimeError: If the app has not been initialized yet.
  922. """
  923. if self.event_namespace is None:
  924. raise RuntimeError("App has not been initialized yet.")
  925. # Process the event.
  926. async for update in state._process_event(
  927. handler=handler, state=substate, payload=event.payload
  928. ):
  929. # Postprocess the event.
  930. update = await self._postprocess(state, event, update)
  931. # Send the update to the client.
  932. await self.event_namespace.emit_update(
  933. update=update,
  934. sid=state.router.session.session_id,
  935. )
  936. task = asyncio.create_task(_coro())
  937. self.background_tasks.add(task)
  938. # Clean up task from background_tasks set when complete.
  939. task.add_done_callback(self.background_tasks.discard)
  940. return task
  941. async def process(
  942. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  943. ) -> AsyncIterator[StateUpdate]:
  944. """Process an event.
  945. Args:
  946. app: The app to process the event for.
  947. event: The event to process.
  948. sid: The Socket.IO session id.
  949. headers: The client headers.
  950. client_ip: The client_ip.
  951. Raises:
  952. Exception: If a reflex specific error occurs during processing the event.
  953. Yields:
  954. The state updates after processing the event.
  955. """
  956. from reflex.utils import telemetry
  957. try:
  958. # Add request data to the state.
  959. router_data = event.router_data
  960. router_data.update(
  961. {
  962. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  963. constants.RouteVar.CLIENT_TOKEN: event.token,
  964. constants.RouteVar.SESSION_ID: sid,
  965. constants.RouteVar.HEADERS: headers,
  966. constants.RouteVar.CLIENT_IP: client_ip,
  967. }
  968. )
  969. # Get the state for the session exclusively.
  970. async with app.state_manager.modify_state(event.substate_token) as state:
  971. # re-assign only when the value is different
  972. if state.router_data != router_data:
  973. # assignment will recurse into substates and force recalculation of
  974. # dependent ComputedVar (dynamic route variables)
  975. state.router_data = router_data
  976. state.router = RouterData(router_data)
  977. # Preprocess the event.
  978. update = await app._preprocess(state, event)
  979. # If there was an update, yield it.
  980. if update is not None:
  981. yield update
  982. # Only process the event if there is no update.
  983. else:
  984. if app._process_background(state, event) is not None:
  985. # `final=True` allows the frontend send more events immediately.
  986. yield StateUpdate(final=True)
  987. return
  988. # Process the event synchronously.
  989. async for update in state._process(event):
  990. # Postprocess the event.
  991. update = await app._postprocess(state, event, update)
  992. # Yield the update.
  993. yield update
  994. except Exception as ex:
  995. telemetry.send_error(ex, context="backend")
  996. raise
  997. async def ping() -> str:
  998. """Test API endpoint.
  999. Returns:
  1000. The response.
  1001. """
  1002. return "pong"
  1003. def upload(app: App):
  1004. """Upload a file.
  1005. Args:
  1006. app: The app to upload the file for.
  1007. Returns:
  1008. The upload function.
  1009. """
  1010. async def upload_file(request: Request, files: List[UploadFile]):
  1011. """Upload a file.
  1012. Args:
  1013. request: The FastAPI request object.
  1014. files: The file(s) to upload.
  1015. Returns:
  1016. StreamingResponse yielding newline-delimited JSON of StateUpdate
  1017. emitted by the upload handler.
  1018. Raises:
  1019. UploadValueError: if there are no args with supported annotation.
  1020. UploadTypeError: if a background task is used as the handler.
  1021. HTTPException: when the request does not include token / handler headers.
  1022. """
  1023. from reflex.utils.exceptions import UploadTypeError, UploadValueError
  1024. token = request.headers.get("reflex-client-token")
  1025. handler = request.headers.get("reflex-event-handler")
  1026. if not token or not handler:
  1027. raise HTTPException(
  1028. status_code=400,
  1029. detail="Missing reflex-client-token or reflex-event-handler header.",
  1030. )
  1031. # Get the state for the session.
  1032. substate_token = _substate_key(token, handler.rpartition(".")[0])
  1033. state = await app.state_manager.get_state(substate_token)
  1034. # get the current session ID
  1035. # get the current state(parent state/substate)
  1036. path = handler.split(".")[:-1]
  1037. current_state = state.get_substate(path)
  1038. handler_upload_param = ()
  1039. # get handler function
  1040. func = getattr(type(current_state), handler.split(".")[-1])
  1041. # check if there exists any handler args with annotation, List[UploadFile]
  1042. if isinstance(func, EventHandler):
  1043. if func.is_background:
  1044. raise UploadTypeError(
  1045. f"@rx.background is not supported for upload handler `{handler}`.",
  1046. )
  1047. func = func.fn
  1048. if isinstance(func, functools.partial):
  1049. func = func.func
  1050. for k, v in get_type_hints(func).items():
  1051. if types.is_generic_alias(v) and types._issubclass(
  1052. get_args(v)[0],
  1053. UploadFile,
  1054. ):
  1055. handler_upload_param = (k, v)
  1056. break
  1057. if not handler_upload_param:
  1058. raise UploadValueError(
  1059. f"`{handler}` handler should have a parameter annotated as "
  1060. "List[rx.UploadFile]"
  1061. )
  1062. # Make a copy of the files as they are closed after the request.
  1063. # This behaviour changed from fastapi 0.103.0 to 0.103.1 as the
  1064. # AsyncExitStack was removed from the request scope and is now
  1065. # part of the routing function which closes this before the
  1066. # event is handled.
  1067. file_copies = []
  1068. for file in files:
  1069. content_copy = io.BytesIO()
  1070. content_copy.write(await file.read())
  1071. content_copy.seek(0)
  1072. file_copies.append(
  1073. UploadFile(
  1074. file=content_copy,
  1075. filename=file.filename,
  1076. size=file.size,
  1077. headers=file.headers,
  1078. )
  1079. )
  1080. event = Event(
  1081. token=token,
  1082. name=handler,
  1083. payload={handler_upload_param[0]: file_copies},
  1084. )
  1085. async def _ndjson_updates():
  1086. """Process the upload event, generating ndjson updates.
  1087. Yields:
  1088. Each state update as JSON followed by a new line.
  1089. """
  1090. # Process the event.
  1091. async with app.state_manager.modify_state(event.substate_token) as state:
  1092. async for update in state._process(event):
  1093. # Postprocess the event.
  1094. update = await app._postprocess(state, event, update)
  1095. yield update.json() + "\n"
  1096. # Stream updates to client
  1097. return StreamingResponse(
  1098. _ndjson_updates(),
  1099. media_type="application/x-ndjson",
  1100. )
  1101. return upload_file
  1102. class EventNamespace(AsyncNamespace):
  1103. """The event namespace."""
  1104. # The application object.
  1105. app: App
  1106. # Keep a mapping between socket ID and client token.
  1107. token_to_sid: dict[str, str] = {}
  1108. # Keep a mapping between client token and socket ID.
  1109. sid_to_token: dict[str, str] = {}
  1110. def __init__(self, namespace: str, app: App):
  1111. """Initialize the event namespace.
  1112. Args:
  1113. namespace: The namespace.
  1114. app: The application object.
  1115. """
  1116. super().__init__(namespace)
  1117. self.app = app
  1118. def on_connect(self, sid, environ):
  1119. """Event for when the websocket is connected.
  1120. Args:
  1121. sid: The Socket.IO session id.
  1122. environ: The request information, including HTTP headers.
  1123. """
  1124. pass
  1125. def on_disconnect(self, sid):
  1126. """Event for when the websocket disconnects.
  1127. Args:
  1128. sid: The Socket.IO session id.
  1129. """
  1130. disconnect_token = self.sid_to_token.pop(sid, None)
  1131. if disconnect_token:
  1132. self.token_to_sid.pop(disconnect_token, None)
  1133. async def emit_update(self, update: StateUpdate, sid: str) -> None:
  1134. """Emit an update to the client.
  1135. Args:
  1136. update: The state update to send.
  1137. sid: The Socket.IO session id.
  1138. """
  1139. # Creating a task prevents the update from being blocked behind other coroutines.
  1140. await asyncio.create_task(
  1141. self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  1142. )
  1143. async def on_event(self, sid, data):
  1144. """Event for receiving front-end websocket events.
  1145. Args:
  1146. sid: The Socket.IO session id.
  1147. data: The event data.
  1148. """
  1149. # Get the event.
  1150. event = Event.parse_raw(data)
  1151. self.token_to_sid[event.token] = sid
  1152. self.sid_to_token[sid] = event.token
  1153. # Get the event environment.
  1154. assert self.app.sio is not None
  1155. environ = self.app.sio.get_environ(sid, self.namespace)
  1156. assert environ is not None
  1157. # Get the client headers.
  1158. headers = {
  1159. k.decode("utf-8"): v.decode("utf-8")
  1160. for (k, v) in environ["asgi.scope"]["headers"]
  1161. }
  1162. # Get the client IP
  1163. try:
  1164. client_ip = environ["asgi.scope"]["client"][0]
  1165. except (KeyError, IndexError):
  1166. client_ip = environ.get("REMOTE_ADDR", "0.0.0.0")
  1167. # Process the events.
  1168. async for update in process(self.app, event, sid, headers, client_ip):
  1169. # Emit the update from processing the event.
  1170. await self.emit_update(update=update, sid=sid)
  1171. async def on_ping(self, sid):
  1172. """Event for testing the API endpoint.
  1173. Args:
  1174. sid: The Socket.IO session id.
  1175. """
  1176. # Emit the test event.
  1177. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)