app.py 55 KB

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