app.py 68 KB

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