app.py 48 KB

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