app.py 46 KB

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