app.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  1. """The main Reflex app."""
  2. from __future__ import annotations
  3. import asyncio
  4. import concurrent.futures
  5. import contextlib
  6. import copy
  7. import dataclasses
  8. import functools
  9. import inspect
  10. import io
  11. import json
  12. import multiprocessing
  13. import platform
  14. import sys
  15. import traceback
  16. from datetime import datetime
  17. from pathlib import Path
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. AsyncIterator,
  22. Callable,
  23. Coroutine,
  24. Dict,
  25. Generic,
  26. List,
  27. Optional,
  28. Set,
  29. Type,
  30. Union,
  31. get_args,
  32. get_type_hints,
  33. )
  34. from fastapi import FastAPI, HTTPException, Request, UploadFile
  35. from fastapi.middleware import cors
  36. from fastapi.responses import JSONResponse, StreamingResponse
  37. from fastapi.staticfiles import StaticFiles
  38. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  39. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  40. from starlette_admin.contrib.sqla.admin import Admin
  41. from starlette_admin.contrib.sqla.view import ModelView
  42. from reflex import constants
  43. from reflex.admin import AdminDash
  44. from reflex.app_mixins import AppMixin, LifespanMixin, MiddlewareMixin
  45. from reflex.compiler import compiler
  46. from reflex.compiler import utils as compiler_utils
  47. from reflex.compiler.compiler import ExecutorSafeFunctions, compile_theme
  48. from reflex.components.base.app_wrap import AppWrap
  49. from reflex.components.base.error_boundary import ErrorBoundary
  50. from reflex.components.base.fragment import Fragment
  51. from reflex.components.component import (
  52. Component,
  53. ComponentStyle,
  54. evaluate_style_namespaces,
  55. )
  56. from reflex.components.core.banner import connection_pulser, connection_toaster
  57. from reflex.components.core.breakpoints import set_breakpoints
  58. from reflex.components.core.client_side_routing import (
  59. Default404Page,
  60. wait_for_client_redirect,
  61. )
  62. from reflex.components.core.upload import Upload, get_upload_dir
  63. from reflex.components.radix import themes
  64. from reflex.config import environment, get_config
  65. from reflex.event import (
  66. BASE_STATE,
  67. Event,
  68. EventHandler,
  69. EventSpec,
  70. EventType,
  71. IndividualEventType,
  72. 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 route in self.unevaluated_pages and environment.RELOAD_CONFIG.is_set():
  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, self.style, self.theme
  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[IndividualEventType[[], Any]]:
  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: EventType[[], BASE_STATE] | None = None,
  504. meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
  505. ):
  506. """Define a custom 404 page for any url having no match.
  507. If there is no page defined on 'index' route, add the 404 page to it.
  508. If there is no global catchall defined, add the 404 page with a catchall.
  509. Args:
  510. component: The component to display at the page.
  511. title: The title of the page.
  512. description: The description of the page.
  513. image: The image to display on the page.
  514. on_load: The event handler(s) that will be called each time the page load.
  515. meta: The metadata of the page.
  516. """
  517. if component is None:
  518. component = Default404Page.create()
  519. self.add_page(
  520. component=wait_for_client_redirect(self._generate_component(component)),
  521. route=constants.Page404.SLUG,
  522. title=title or constants.Page404.TITLE,
  523. image=image or constants.Page404.IMAGE,
  524. description=description or constants.Page404.DESCRIPTION,
  525. on_load=on_load,
  526. meta=meta,
  527. )
  528. def _setup_admin_dash(self):
  529. """Setup the admin dash."""
  530. # Get the admin dash.
  531. admin_dash = self.admin_dash
  532. if admin_dash and admin_dash.models:
  533. # Build the admin dashboard
  534. admin = (
  535. admin_dash.admin
  536. if admin_dash.admin
  537. else Admin(
  538. engine=Model.get_db_engine(),
  539. title="Reflex Admin Dashboard",
  540. logo_url="https://reflex.dev/Reflex.svg",
  541. )
  542. )
  543. for model in admin_dash.models:
  544. view = admin_dash.view_overrides.get(model, ModelView)
  545. admin.add_view(view(model))
  546. admin.mount_to(self.api)
  547. def _get_frontend_packages(self, imports: Dict[str, set[ImportVar]]):
  548. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  549. Args:
  550. imports: A dictionary containing the imports used in the current page.
  551. Example:
  552. >>> _get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  553. """
  554. page_imports = {
  555. i
  556. for i, tags in imports.items()
  557. if i not in constants.PackageJson.DEPENDENCIES
  558. and i not in constants.PackageJson.DEV_DEPENDENCIES
  559. and not any(i.startswith(prefix) for prefix in ["/", "$/", ".", "next/"])
  560. and i != ""
  561. and any(tag.install for tag in tags)
  562. }
  563. frontend_packages = get_config().frontend_packages
  564. _frontend_packages = []
  565. for package in frontend_packages:
  566. if package in (get_config().tailwind or {}).get("plugins", []): # type: ignore
  567. console.warn(
  568. f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`"
  569. )
  570. continue
  571. if package in page_imports:
  572. console.warn(
  573. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  574. )
  575. continue
  576. _frontend_packages.append(package)
  577. page_imports.update(_frontend_packages)
  578. prerequisites.install_frontend_packages(page_imports, get_config())
  579. def _app_root(self, app_wrappers: dict[tuple[int, str], Component]) -> Component:
  580. for component in tuple(app_wrappers.values()):
  581. app_wrappers.update(component._get_all_app_wrap_components())
  582. order = sorted(app_wrappers, key=lambda k: k[0], reverse=True)
  583. root = parent = copy.deepcopy(app_wrappers[order[0]])
  584. for key in order[1:]:
  585. child = copy.deepcopy(app_wrappers[key])
  586. parent.children.append(child)
  587. parent = child
  588. return root
  589. def _should_compile(self) -> bool:
  590. """Check if the app should be compiled.
  591. Returns:
  592. Whether the app should be compiled.
  593. """
  594. # Check the environment variable.
  595. if environment.REFLEX_SKIP_COMPILE.get():
  596. return False
  597. nocompile = prerequisites.get_web_dir() / constants.NOCOMPILE_FILE
  598. # Check the nocompile file.
  599. if nocompile.exists():
  600. # Delete the nocompile file
  601. nocompile.unlink()
  602. return False
  603. # By default, compile the app.
  604. return True
  605. def _add_overlay_to_component(self, component: Component) -> Component:
  606. if self.overlay_component is None:
  607. return component
  608. children = component.children
  609. overlay_component = self._generate_component(self.overlay_component)
  610. if children[0] == overlay_component:
  611. return component
  612. # recreate OverlayFragment with overlay_component as first child
  613. component = OverlayFragment.create(overlay_component, *children)
  614. return component
  615. def _setup_overlay_component(self):
  616. """If a State is not used and no overlay_component is specified, do not render the connection modal."""
  617. if self.state is None and self.overlay_component is default_overlay_component:
  618. self.overlay_component = None
  619. for k, component in self.pages.items():
  620. self.pages[k] = self._add_overlay_to_component(component)
  621. def _add_error_boundary_to_component(self, component: Component) -> Component:
  622. if self.error_boundary is None:
  623. return component
  624. component = self.error_boundary(*component.children)
  625. return component
  626. def _setup_error_boundary(self):
  627. """If a State is not used and no error_boundary is specified, do not render the error boundary."""
  628. if self.state is None and self.error_boundary is default_error_boundary:
  629. self.error_boundary = None
  630. for k, component in self.pages.items():
  631. # Skip the 404 page
  632. if k == constants.Page404.SLUG:
  633. continue
  634. self.pages[k] = self._add_error_boundary_to_component(component)
  635. def _apply_decorated_pages(self):
  636. """Add @rx.page decorated pages to the app.
  637. This has to be done in the MainThread for py38 and py39 compatibility, so the
  638. decorated pages are added to the app before the app is compiled (in a thread)
  639. to workaround REF-2172.
  640. This can move back into `compile_` when py39 support is dropped.
  641. """
  642. # Add the @rx.page decorated pages to collect on_load events.
  643. for render, kwargs in DECORATED_PAGES[get_config().app_name]:
  644. self.add_page(render, **kwargs)
  645. def _validate_var_dependencies(
  646. self, state: Optional[Type[BaseState]] = None
  647. ) -> None:
  648. """Validate the dependencies of the vars in the app.
  649. Args:
  650. state: The state to validate the dependencies for.
  651. Raises:
  652. VarDependencyError: When a computed var has an invalid dependency.
  653. """
  654. if not self.state:
  655. return
  656. if not state:
  657. state = self.state
  658. for var in state.computed_vars.values():
  659. if not var._cache:
  660. continue
  661. deps = var._deps(objclass=state)
  662. for dep in deps:
  663. if dep not in state.vars and dep not in state.backend_vars:
  664. raise exceptions.VarDependencyError(
  665. f"ComputedVar {var._js_expr} on state {state.__name__} has an invalid dependency {dep}"
  666. )
  667. for substate in state.class_subclasses:
  668. self._validate_var_dependencies(substate)
  669. def _compile(self, export: bool = False):
  670. """Compile the app and output it to the pages folder.
  671. Args:
  672. export: Whether to compile the app for export.
  673. Raises:
  674. ReflexRuntimeError: When any page uses state, but no rx.State subclass is defined.
  675. """
  676. from reflex.utils.exceptions import ReflexRuntimeError
  677. self.pages = {}
  678. def get_compilation_time() -> str:
  679. return str(datetime.now().time()).split(".")[0]
  680. # Render a default 404 page if the user didn't supply one
  681. if constants.Page404.SLUG not in self.unevaluated_pages:
  682. self.add_custom_404_page()
  683. # Fix up the style.
  684. self.style = evaluate_style_namespaces(self.style)
  685. # Add the app wrappers.
  686. app_wrappers: Dict[tuple[int, str], Component] = {
  687. # Default app wrap component renders {children}
  688. (0, "AppWrap"): AppWrap.create()
  689. }
  690. if self.theme is not None:
  691. # If a theme component was provided, wrap the app with it
  692. app_wrappers[(20, "Theme")] = self.theme
  693. for route in self.unevaluated_pages:
  694. console.debug(f"Evaluating page: {route}")
  695. self._compile_page(route)
  696. # Add the optional endpoints (_upload)
  697. self._add_optional_endpoints()
  698. if not self._should_compile():
  699. return
  700. self._validate_var_dependencies()
  701. self._setup_overlay_component()
  702. self._setup_error_boundary()
  703. # Create a progress bar.
  704. progress = Progress(
  705. *Progress.get_default_columns()[:-1],
  706. MofNCompleteColumn(),
  707. TimeElapsedColumn(),
  708. )
  709. # try to be somewhat accurate - but still not 100%
  710. adhoc_steps_without_executor = 6
  711. fixed_pages_within_executor = 5
  712. progress.start()
  713. task = progress.add_task(
  714. f"[{get_compilation_time()}] Compiling:",
  715. total=len(self.pages)
  716. + fixed_pages_within_executor
  717. + adhoc_steps_without_executor,
  718. )
  719. # Get the env mode.
  720. config = get_config()
  721. # Store the compile results.
  722. compile_results = []
  723. progress.advance(task)
  724. # Track imports and custom components found.
  725. all_imports = {}
  726. custom_components = set()
  727. # This has to happen before compiling stateful components as that
  728. # prevents recursive functions from reaching all components.
  729. for component in self.pages.values():
  730. # Add component._get_all_imports() to all_imports.
  731. all_imports.update(component._get_all_imports())
  732. # Add the app wrappers from this component.
  733. app_wrappers.update(component._get_all_app_wrap_components())
  734. # Add the custom components from the page to the set.
  735. custom_components |= component._get_all_custom_components()
  736. # Perform auto-memoization of stateful components.
  737. (
  738. stateful_components_path,
  739. stateful_components_code,
  740. page_components,
  741. ) = compiler.compile_stateful_components(self.pages.values())
  742. progress.advance(task)
  743. # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State.
  744. if code_uses_state_contexts(stateful_components_code) and self.state is None:
  745. raise ReflexRuntimeError(
  746. "To access rx.State in frontend components, at least one "
  747. "subclass of rx.State must be defined in the app."
  748. )
  749. compile_results.append((stateful_components_path, stateful_components_code))
  750. progress.advance(task)
  751. # Compile the root document before fork.
  752. compile_results.append(
  753. compiler.compile_document_root(
  754. self.head_components,
  755. html_lang=self.html_lang,
  756. html_custom_attrs=self.html_custom_attrs, # type: ignore
  757. )
  758. )
  759. progress.advance(task)
  760. # Use a forking process pool, if possible. Much faster, especially for large sites.
  761. # Fallback to ThreadPoolExecutor as something that will always work.
  762. executor = None
  763. if (
  764. platform.system() in ("Linux", "Darwin")
  765. and (number_of_processes := environment.REFLEX_COMPILE_PROCESSES.get())
  766. is not None
  767. ):
  768. executor = concurrent.futures.ProcessPoolExecutor(
  769. max_workers=number_of_processes,
  770. mp_context=multiprocessing.get_context("fork"),
  771. )
  772. else:
  773. executor = concurrent.futures.ThreadPoolExecutor(
  774. max_workers=environment.REFLEX_COMPILE_THREADS.get()
  775. )
  776. for route, component in zip(self.pages, page_components):
  777. ExecutorSafeFunctions.COMPONENTS[route] = component
  778. ExecutorSafeFunctions.STATE = self.state
  779. with executor:
  780. result_futures = []
  781. def _submit_work(fn, *args, **kwargs):
  782. f = executor.submit(fn, *args, **kwargs)
  783. # f = executor.apipe(fn, *args, **kwargs)
  784. result_futures.append(f)
  785. # Compile the pre-compiled pages.
  786. for route in self.pages:
  787. _submit_work(
  788. ExecutorSafeFunctions.compile_page,
  789. route,
  790. )
  791. # Compile the root stylesheet with base styles.
  792. _submit_work(compiler.compile_root_stylesheet, self.stylesheets)
  793. # Compile the theme.
  794. _submit_work(compile_theme, self.style)
  795. # Compile the Tailwind config.
  796. if config.tailwind is not None:
  797. config.tailwind["content"] = config.tailwind.get(
  798. "content", constants.Tailwind.CONTENT
  799. )
  800. _submit_work(compiler.compile_tailwind, config.tailwind)
  801. else:
  802. _submit_work(compiler.remove_tailwind_from_postcss)
  803. # Wait for all compilation tasks to complete.
  804. for future in concurrent.futures.as_completed(result_futures):
  805. compile_results.append(future.result())
  806. progress.advance(task)
  807. app_root = self._app_root(app_wrappers=app_wrappers)
  808. # Get imports from AppWrap components.
  809. all_imports.update(app_root._get_all_imports())
  810. progress.advance(task)
  811. # Compile the contexts.
  812. compile_results.append(
  813. compiler.compile_contexts(self.state, self.theme),
  814. )
  815. if self.theme is not None:
  816. # Fix #2992 by removing the top-level appearance prop
  817. self.theme.appearance = None
  818. progress.advance(task)
  819. # Compile the app root.
  820. compile_results.append(
  821. compiler.compile_app(app_root),
  822. )
  823. progress.advance(task)
  824. # Compile custom components.
  825. *custom_components_result, custom_components_imports = (
  826. compiler.compile_components(custom_components)
  827. )
  828. compile_results.append(custom_components_result)
  829. all_imports.update(custom_components_imports)
  830. progress.advance(task)
  831. progress.stop()
  832. # Install frontend packages.
  833. self._get_frontend_packages(all_imports)
  834. # Setup the next.config.js
  835. transpile_packages = [
  836. package
  837. for package, import_vars in all_imports.items()
  838. if any(import_var.transpile for import_var in import_vars)
  839. ]
  840. prerequisites.update_next_config(
  841. export=export,
  842. transpile_packages=transpile_packages,
  843. )
  844. if is_prod_mode():
  845. # Empty the .web pages directory.
  846. compiler.purge_web_pages_dir()
  847. else:
  848. # In dev mode, delete removed pages and update existing pages.
  849. keep_files = [Path(output_path) for output_path, _ in compile_results]
  850. for p in Path(prerequisites.get_web_dir() / constants.Dirs.PAGES).rglob(
  851. "*"
  852. ):
  853. if p.is_file() and p not in keep_files:
  854. # Remove pages that are no longer in the app.
  855. p.unlink()
  856. for output_path, code in compile_results:
  857. compiler_utils.write_page(output_path, code)
  858. @contextlib.asynccontextmanager
  859. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  860. """Modify the state out of band.
  861. Args:
  862. token: The token to modify the state for.
  863. Yields:
  864. The state to modify.
  865. Raises:
  866. RuntimeError: If the app has not been initialized yet.
  867. """
  868. if self.event_namespace is None:
  869. raise RuntimeError("App has not been initialized yet.")
  870. # Get exclusive access to the state.
  871. async with self.state_manager.modify_state(token) as state:
  872. # No other event handler can modify the state while in this context.
  873. yield state
  874. delta = state.get_delta()
  875. if delta:
  876. # When the state is modified reset dirty status and emit the delta to the frontend.
  877. state._clean()
  878. await self.event_namespace.emit_update(
  879. update=StateUpdate(delta=delta),
  880. sid=state.router.session.session_id,
  881. )
  882. def _process_background(
  883. self, state: BaseState, event: Event
  884. ) -> asyncio.Task | None:
  885. """Process an event in the background and emit updates as they arrive.
  886. Args:
  887. state: The state to process the event for.
  888. event: The event to process.
  889. Returns:
  890. Task if the event was backgroundable, otherwise None
  891. """
  892. substate, handler = state._get_event_handler(event)
  893. if not handler.is_background:
  894. return None
  895. async def _coro():
  896. """Coroutine to process the event and emit updates inside an asyncio.Task.
  897. Raises:
  898. RuntimeError: If the app has not been initialized yet.
  899. """
  900. if self.event_namespace is None:
  901. raise RuntimeError("App has not been initialized yet.")
  902. # Process the event.
  903. async for update in state._process_event(
  904. handler=handler, state=substate, payload=event.payload
  905. ):
  906. # Postprocess the event.
  907. update = await self._postprocess(state, event, update)
  908. # Send the update to the client.
  909. await self.event_namespace.emit_update(
  910. update=update,
  911. sid=state.router.session.session_id,
  912. )
  913. task = asyncio.create_task(_coro())
  914. self.background_tasks.add(task)
  915. # Clean up task from background_tasks set when complete.
  916. task.add_done_callback(self.background_tasks.discard)
  917. return task
  918. def _validate_exception_handlers(self):
  919. """Validate the custom event exception handlers for front- and backend.
  920. Raises:
  921. ValueError: If the custom exception handlers are invalid.
  922. """
  923. FRONTEND_ARG_SPEC = {
  924. "exception": Exception,
  925. }
  926. BACKEND_ARG_SPEC = {
  927. "exception": Exception,
  928. }
  929. for handler_domain, handler_fn, handler_spec in zip(
  930. ["frontend", "backend"],
  931. [self.frontend_exception_handler, self.backend_exception_handler],
  932. [
  933. FRONTEND_ARG_SPEC,
  934. BACKEND_ARG_SPEC,
  935. ],
  936. ):
  937. if hasattr(handler_fn, "__name__"):
  938. _fn_name = handler_fn.__name__
  939. else:
  940. _fn_name = handler_fn.__class__.__name__
  941. if isinstance(handler_fn, functools.partial):
  942. raise ValueError(
  943. f"Provided custom {handler_domain} exception handler `{_fn_name}` is a partial function. Please provide a named function instead."
  944. )
  945. if not callable(handler_fn):
  946. raise ValueError(
  947. f"Provided custom {handler_domain} exception handler `{_fn_name}` is not a function."
  948. )
  949. # Allow named functions only as lambda functions cannot be introspected
  950. if _fn_name == "<lambda>":
  951. raise ValueError(
  952. f"Provided custom {handler_domain} exception handler `{_fn_name}` is a lambda function. Please use a named function instead."
  953. )
  954. # Check if the function has the necessary annotations and types in the right order
  955. argspec = inspect.getfullargspec(handler_fn)
  956. arg_annotations = {
  957. k: eval(v) if isinstance(v, str) else v
  958. for k, v in argspec.annotations.items()
  959. if k not in ["args", "kwargs", "return"]
  960. }
  961. for required_arg_index, required_arg in enumerate(handler_spec):
  962. if required_arg not in arg_annotations:
  963. raise ValueError(
  964. f"Provided custom {handler_domain} exception handler `{_fn_name}` does not take the required argument `{required_arg}`"
  965. )
  966. elif (
  967. not list(arg_annotations.keys())[required_arg_index] == required_arg
  968. ):
  969. raise ValueError(
  970. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong argument order."
  971. f"Expected `{required_arg}` as the {required_arg_index+1} argument but got `{list(arg_annotations.keys())[required_arg_index]}`"
  972. )
  973. if not issubclass(arg_annotations[required_arg], Exception):
  974. raise ValueError(
  975. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong type for {required_arg} argument."
  976. f"Expected to be `Exception` but got `{arg_annotations[required_arg]}`"
  977. )
  978. # Check if the return type is valid for backend exception handler
  979. if handler_domain == "backend":
  980. sig = inspect.signature(self.backend_exception_handler)
  981. return_type = (
  982. eval(sig.return_annotation)
  983. if isinstance(sig.return_annotation, str)
  984. else sig.return_annotation
  985. )
  986. valid = bool(
  987. return_type == EventSpec
  988. or return_type == Optional[EventSpec]
  989. or return_type == List[EventSpec]
  990. or return_type == inspect.Signature.empty
  991. or return_type is None
  992. )
  993. if not valid:
  994. raise ValueError(
  995. f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong return type."
  996. f"Expected `Union[EventSpec, List[EventSpec], None]` but got `{return_type}`"
  997. )
  998. async def process(
  999. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  1000. ) -> AsyncIterator[StateUpdate]:
  1001. """Process an event.
  1002. Args:
  1003. app: The app to process the event for.
  1004. event: The event to process.
  1005. sid: The Socket.IO session id.
  1006. headers: The client headers.
  1007. client_ip: The client_ip.
  1008. Raises:
  1009. Exception: If a reflex specific error occurs during processing the event.
  1010. Yields:
  1011. The state updates after processing the event.
  1012. """
  1013. from reflex.utils import telemetry
  1014. try:
  1015. # Add request data to the state.
  1016. router_data = event.router_data
  1017. router_data.update(
  1018. {
  1019. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  1020. constants.RouteVar.CLIENT_TOKEN: event.token,
  1021. constants.RouteVar.SESSION_ID: sid,
  1022. constants.RouteVar.HEADERS: headers,
  1023. constants.RouteVar.CLIENT_IP: client_ip,
  1024. }
  1025. )
  1026. # Get the state for the session exclusively.
  1027. async with app.state_manager.modify_state(event.substate_token) as state:
  1028. # re-assign only when the value is different
  1029. if state.router_data != router_data:
  1030. # assignment will recurse into substates and force recalculation of
  1031. # dependent ComputedVar (dynamic route variables)
  1032. state.router_data = router_data
  1033. state.router = RouterData(router_data)
  1034. # Preprocess the event.
  1035. update = await app._preprocess(state, event)
  1036. # If there was an update, yield it.
  1037. if update is not None:
  1038. yield update
  1039. # Only process the event if there is no update.
  1040. else:
  1041. if app._process_background(state, event) is not None:
  1042. # `final=True` allows the frontend send more events immediately.
  1043. yield StateUpdate(final=True)
  1044. return
  1045. # Process the event synchronously.
  1046. async for update in state._process(event):
  1047. # Postprocess the event.
  1048. update = await app._postprocess(state, event, update)
  1049. # Yield the update.
  1050. yield update
  1051. except Exception as ex:
  1052. telemetry.send_error(ex, context="backend")
  1053. app.backend_exception_handler(ex)
  1054. raise
  1055. async def ping() -> str:
  1056. """Test API endpoint.
  1057. Returns:
  1058. The response.
  1059. """
  1060. return "pong"
  1061. async def health() -> JSONResponse:
  1062. """Health check endpoint to assess the status of the database and Redis services.
  1063. Returns:
  1064. JSONResponse: A JSON object with the health status:
  1065. - "status" (bool): Overall health, True if all checks pass.
  1066. - "db" (bool or str): Database status - True, False, or "NA".
  1067. - "redis" (bool or str): Redis status - True, False, or "NA".
  1068. """
  1069. health_status = {"status": True}
  1070. status_code = 200
  1071. db_status, redis_status = await asyncio.gather(
  1072. get_db_status(), prerequisites.get_redis_status()
  1073. )
  1074. health_status["db"] = db_status
  1075. if redis_status is None:
  1076. health_status["redis"] = False
  1077. else:
  1078. health_status["redis"] = redis_status
  1079. if not health_status["db"] or (
  1080. not health_status["redis"] and redis_status is not None
  1081. ):
  1082. health_status["status"] = False
  1083. status_code = 503
  1084. return JSONResponse(content=health_status, status_code=status_code)
  1085. def upload(app: App):
  1086. """Upload a file.
  1087. Args:
  1088. app: The app to upload the file for.
  1089. Returns:
  1090. The upload function.
  1091. """
  1092. async def upload_file(request: Request, files: List[UploadFile]):
  1093. """Upload a file.
  1094. Args:
  1095. request: The FastAPI request object.
  1096. files: The file(s) to upload.
  1097. Returns:
  1098. StreamingResponse yielding newline-delimited JSON of StateUpdate
  1099. emitted by the upload handler.
  1100. Raises:
  1101. UploadValueError: if there are no args with supported annotation.
  1102. UploadTypeError: if a background task is used as the handler.
  1103. HTTPException: when the request does not include token / handler headers.
  1104. """
  1105. from reflex.utils.exceptions import UploadTypeError, UploadValueError
  1106. token = request.headers.get("reflex-client-token")
  1107. handler = request.headers.get("reflex-event-handler")
  1108. if not token or not handler:
  1109. raise HTTPException(
  1110. status_code=400,
  1111. detail="Missing reflex-client-token or reflex-event-handler header.",
  1112. )
  1113. # Get the state for the session.
  1114. substate_token = _substate_key(token, handler.rpartition(".")[0])
  1115. state = await app.state_manager.get_state(substate_token)
  1116. # get the current session ID
  1117. # get the current state(parent state/substate)
  1118. path = handler.split(".")[:-1]
  1119. current_state = state.get_substate(path)
  1120. handler_upload_param = ()
  1121. # get handler function
  1122. func = getattr(type(current_state), handler.split(".")[-1])
  1123. # check if there exists any handler args with annotation, List[UploadFile]
  1124. if isinstance(func, EventHandler):
  1125. if func.is_background:
  1126. raise UploadTypeError(
  1127. f"@rx.event(background=True) is not supported for upload handler `{handler}`.",
  1128. )
  1129. func = func.fn
  1130. if isinstance(func, functools.partial):
  1131. func = func.func
  1132. for k, v in get_type_hints(func).items():
  1133. if types.is_generic_alias(v) and types._issubclass(
  1134. get_args(v)[0],
  1135. UploadFile,
  1136. ):
  1137. handler_upload_param = (k, v)
  1138. break
  1139. if not handler_upload_param:
  1140. raise UploadValueError(
  1141. f"`{handler}` handler should have a parameter annotated as "
  1142. "List[rx.UploadFile]"
  1143. )
  1144. # Make a copy of the files as they are closed after the request.
  1145. # This behaviour changed from fastapi 0.103.0 to 0.103.1 as the
  1146. # AsyncExitStack was removed from the request scope and is now
  1147. # part of the routing function which closes this before the
  1148. # event is handled.
  1149. file_copies = []
  1150. for file in files:
  1151. content_copy = io.BytesIO()
  1152. content_copy.write(await file.read())
  1153. content_copy.seek(0)
  1154. file_copies.append(
  1155. UploadFile(
  1156. file=content_copy,
  1157. filename=file.filename,
  1158. size=file.size,
  1159. headers=file.headers,
  1160. )
  1161. )
  1162. event = Event(
  1163. token=token,
  1164. name=handler,
  1165. payload={handler_upload_param[0]: file_copies},
  1166. )
  1167. async def _ndjson_updates():
  1168. """Process the upload event, generating ndjson updates.
  1169. Yields:
  1170. Each state update as JSON followed by a new line.
  1171. """
  1172. # Process the event.
  1173. async with app.state_manager.modify_state(event.substate_token) as state:
  1174. async for update in state._process(event):
  1175. # Postprocess the event.
  1176. update = await app._postprocess(state, event, update)
  1177. yield update.json() + "\n"
  1178. # Stream updates to client
  1179. return StreamingResponse(
  1180. _ndjson_updates(),
  1181. media_type="application/x-ndjson",
  1182. )
  1183. return upload_file
  1184. class EventNamespace(AsyncNamespace):
  1185. """The event namespace."""
  1186. # The application object.
  1187. app: App
  1188. # Keep a mapping between socket ID and client token.
  1189. token_to_sid: dict[str, str]
  1190. # Keep a mapping between client token and socket ID.
  1191. sid_to_token: dict[str, str]
  1192. def __init__(self, namespace: str, app: App):
  1193. """Initialize the event namespace.
  1194. Args:
  1195. namespace: The namespace.
  1196. app: The application object.
  1197. """
  1198. super().__init__(namespace)
  1199. self.token_to_sid = {}
  1200. self.sid_to_token = {}
  1201. self.app = app
  1202. def on_connect(self, sid, environ):
  1203. """Event for when the websocket is connected.
  1204. Args:
  1205. sid: The Socket.IO session id.
  1206. environ: The request information, including HTTP headers.
  1207. """
  1208. pass
  1209. def on_disconnect(self, sid):
  1210. """Event for when the websocket disconnects.
  1211. Args:
  1212. sid: The Socket.IO session id.
  1213. """
  1214. disconnect_token = self.sid_to_token.pop(sid, None)
  1215. if disconnect_token:
  1216. self.token_to_sid.pop(disconnect_token, None)
  1217. async def emit_update(self, update: StateUpdate, sid: str) -> None:
  1218. """Emit an update to the client.
  1219. Args:
  1220. update: The state update to send.
  1221. sid: The Socket.IO session id.
  1222. """
  1223. # Creating a task prevents the update from being blocked behind other coroutines.
  1224. await asyncio.create_task(
  1225. self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  1226. )
  1227. async def on_event(self, sid, data):
  1228. """Event for receiving front-end websocket events.
  1229. Raises:
  1230. RuntimeError: If the Socket.IO is badly initialized.
  1231. Args:
  1232. sid: The Socket.IO session id.
  1233. data: The event data.
  1234. """
  1235. fields = json.loads(data)
  1236. # Get the event.
  1237. event = Event(
  1238. **{k: v for k, v in fields.items() if k not in ("handler", "event_actions")}
  1239. )
  1240. self.token_to_sid[event.token] = sid
  1241. self.sid_to_token[sid] = event.token
  1242. # Get the event environment.
  1243. if self.app.sio is None:
  1244. raise RuntimeError("Socket.IO is not initialized.")
  1245. environ = self.app.sio.get_environ(sid, self.namespace)
  1246. if environ is None:
  1247. raise RuntimeError("Socket.IO environ is not initialized.")
  1248. # Get the client headers.
  1249. headers = {
  1250. k.decode("utf-8"): v.decode("utf-8")
  1251. for (k, v) in environ["asgi.scope"]["headers"]
  1252. }
  1253. # Get the client IP
  1254. try:
  1255. client_ip = environ["asgi.scope"]["client"][0]
  1256. except (KeyError, IndexError):
  1257. client_ip = environ.get("REMOTE_ADDR", "0.0.0.0")
  1258. # Process the events.
  1259. async for update in process(self.app, event, sid, headers, client_ip):
  1260. # Emit the update from processing the event.
  1261. await self.emit_update(update=update, sid=sid)
  1262. async def on_ping(self, sid):
  1263. """Event for testing the API endpoint.
  1264. Args:
  1265. sid: The Socket.IO session id.
  1266. """
  1267. # Emit the test event.
  1268. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)