app.py 41 KB

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