app.py 54 KB

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