app.py 69 KB

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