app.py 53 KB

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