app.py 54 KB

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