app.py 57 KB

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