app.py 67 KB

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