app.py 44 KB

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