app.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. """The main Reflex app."""
  2. from __future__ import annotations
  3. import asyncio
  4. import inspect
  5. import os
  6. from multiprocessing.pool import ThreadPool
  7. from typing import (
  8. Any,
  9. AsyncIterator,
  10. Callable,
  11. Coroutine,
  12. Dict,
  13. List,
  14. Optional,
  15. Type,
  16. Union,
  17. )
  18. from fastapi import FastAPI, UploadFile
  19. from fastapi.middleware import cors
  20. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  21. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  22. from starlette_admin.contrib.sqla.admin import Admin
  23. from starlette_admin.contrib.sqla.view import ModelView
  24. from reflex import constants
  25. from reflex.admin import AdminDash
  26. from reflex.base import Base
  27. from reflex.compiler import compiler
  28. from reflex.compiler import utils as compiler_utils
  29. from reflex.components import connection_modal
  30. from reflex.components.component import Component, ComponentStyle
  31. from reflex.components.layout.fragment import Fragment
  32. from reflex.components.navigation.client_side_routing import (
  33. Default404Page,
  34. wait_for_client_redirect,
  35. )
  36. from reflex.config import get_config
  37. from reflex.event import Event, EventHandler, EventSpec
  38. from reflex.middleware import HydrateMiddleware, Middleware
  39. from reflex.model import Model
  40. from reflex.page import (
  41. DECORATED_PAGES,
  42. )
  43. from reflex.route import (
  44. catchall_in_route,
  45. catchall_prefix,
  46. get_route_args,
  47. verify_route_validity,
  48. )
  49. from reflex.state import DefaultState, State, StateManager, StateUpdate
  50. from reflex.utils import console, format, prerequisites, types
  51. # Define custom types.
  52. ComponentCallable = Callable[[], Component]
  53. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  54. def default_overlay_component() -> Component:
  55. """Default overlay_component attribute for App.
  56. Returns:
  57. The default overlay_component, which is a connection_modal.
  58. """
  59. return connection_modal()
  60. class App(Base):
  61. """A Reflex application."""
  62. # A map from a page route to the component to render.
  63. pages: Dict[str, Component] = {}
  64. # A list of URLs to stylesheets to include in the app.
  65. stylesheets: List[str] = []
  66. # The backend API object.
  67. api: FastAPI = None # type: ignore
  68. # The Socket.IO AsyncServer.
  69. sio: Optional[AsyncServer] = None
  70. # The socket app.
  71. socket_app: Optional[ASGIApp] = None
  72. # The state class to use for the app.
  73. state: Type[State] = DefaultState
  74. # Class to manage many client states.
  75. state_manager: StateManager = StateManager()
  76. # The styling to apply to each component.
  77. style: ComponentStyle = {}
  78. # Middleware to add to the app.
  79. middleware: List[Middleware] = []
  80. # List of event handlers to trigger when a page loads.
  81. load_events: Dict[str, List[Union[EventHandler, EventSpec]]] = {}
  82. # Admin dashboard
  83. admin_dash: Optional[AdminDash] = None
  84. # The async server name space
  85. event_namespace: Optional[AsyncNamespace] = None
  86. # A component that is present on every page.
  87. overlay_component: Optional[
  88. Union[Component, ComponentCallable]
  89. ] = default_overlay_component
  90. def __init__(self, *args, **kwargs):
  91. """Initialize the app.
  92. Args:
  93. *args: Args to initialize the app with.
  94. **kwargs: Kwargs to initialize the app with.
  95. Raises:
  96. ValueError: If the event namespace is not provided in the config.
  97. Also, if there are multiple client subclasses of rx.State(Subclasses of rx.State should consist
  98. of the DefaultState and the client app state).
  99. """
  100. if "connect_error_component" in kwargs:
  101. raise ValueError(
  102. "`connect_error_component` is deprecated, use `overlay_component` instead"
  103. )
  104. super().__init__(*args, **kwargs)
  105. state_subclasses = State.__subclasses__()
  106. inferred_state = state_subclasses[-1]
  107. is_testing_env = constants.PYTEST_CURRENT_TEST in os.environ
  108. # Special case to allow test cases have multiple subclasses of rx.State.
  109. if not is_testing_env:
  110. # Only the default state and the client state should be allowed as subclasses.
  111. if len(state_subclasses) > 2:
  112. raise ValueError(
  113. "rx.State has been subclassed multiple times. Only one subclass is allowed"
  114. )
  115. # verify that provided state is valid
  116. if self.state not in [DefaultState, inferred_state]:
  117. console.warn(
  118. f"Using substate ({self.state.__name__}) as root state in `rx.App` is currently not supported."
  119. f" Defaulting to root state: ({inferred_state.__name__})"
  120. )
  121. self.state = inferred_state
  122. # Get the config
  123. config = get_config()
  124. # Add middleware.
  125. self.middleware.append(HydrateMiddleware())
  126. # Set up the state manager.
  127. self.state_manager.setup(state=self.state)
  128. # Set up the API.
  129. self.api = FastAPI()
  130. self.add_cors()
  131. self.add_default_endpoints()
  132. # Set up the Socket.IO AsyncServer.
  133. self.sio = AsyncServer(
  134. async_mode="asgi",
  135. cors_allowed_origins="*"
  136. if config.cors_allowed_origins == ["*"]
  137. else config.cors_allowed_origins,
  138. cors_credentials=True,
  139. max_http_buffer_size=constants.POLLING_MAX_HTTP_BUFFER_SIZE,
  140. ping_interval=constants.PING_INTERVAL,
  141. ping_timeout=constants.PING_TIMEOUT,
  142. )
  143. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  144. self.socket_app = ASGIApp(self.sio, socketio_path="")
  145. namespace = config.get_event_namespace()
  146. if not namespace:
  147. raise ValueError("event namespace must be provided in the config.")
  148. # Create the event namespace and attach the main app. Not related to any paths.
  149. self.event_namespace = EventNamespace(namespace, self)
  150. # Register the event namespace with the socket.
  151. self.sio.register_namespace(self.event_namespace)
  152. # Mount the socket app with the API.
  153. self.api.mount(str(constants.Endpoint.EVENT), self.socket_app)
  154. # Set up the admin dash.
  155. self.setup_admin_dash()
  156. # If a State is not used and no overlay_component is specified, do not render the connection modal
  157. if (
  158. self.state is DefaultState
  159. and self.overlay_component is default_overlay_component
  160. ):
  161. self.overlay_component = None
  162. def __repr__(self) -> str:
  163. """Get the string representation of the app.
  164. Returns:
  165. The string representation of the app.
  166. """
  167. return f"<App state={self.state.__name__}>"
  168. def __call__(self) -> FastAPI:
  169. """Run the backend api instance.
  170. Returns:
  171. The backend api.
  172. """
  173. return self.api
  174. def add_default_endpoints(self):
  175. """Add the default endpoints."""
  176. # To test the server.
  177. self.api.get(str(constants.Endpoint.PING))(ping)
  178. # To upload files.
  179. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  180. def add_cors(self):
  181. """Add CORS middleware to the app."""
  182. self.api.add_middleware(
  183. cors.CORSMiddleware,
  184. allow_credentials=True,
  185. allow_methods=["*"],
  186. allow_headers=["*"],
  187. allow_origins=["*"],
  188. )
  189. async def preprocess(self, state: State, event: Event) -> StateUpdate | None:
  190. """Preprocess the event.
  191. This is where middleware can modify the event before it is processed.
  192. Each middleware is called in the order it was added to the app.
  193. If a middleware returns an update, the event is not processed and the
  194. update is returned.
  195. Args:
  196. state: The state to preprocess.
  197. event: The event to preprocess.
  198. Returns:
  199. An optional state to return.
  200. """
  201. for middleware in self.middleware:
  202. if asyncio.iscoroutinefunction(middleware.preprocess):
  203. out = await middleware.preprocess(app=self, state=state, event=event)
  204. else:
  205. out = middleware.preprocess(app=self, state=state, event=event)
  206. if out is not None:
  207. return out # type: ignore
  208. async def postprocess(
  209. self, state: State, event: Event, update: StateUpdate
  210. ) -> StateUpdate:
  211. """Postprocess the event.
  212. This is where middleware can modify the delta after it is processed.
  213. Each middleware is called in the order it was added to the app.
  214. Args:
  215. state: The state to postprocess.
  216. event: The event to postprocess.
  217. update: The current state update.
  218. Returns:
  219. The state update to return.
  220. """
  221. for middleware in self.middleware:
  222. if asyncio.iscoroutinefunction(middleware.postprocess):
  223. out = await middleware.postprocess(
  224. app=self, state=state, event=event, update=update
  225. )
  226. else:
  227. out = middleware.postprocess(
  228. app=self, state=state, event=event, update=update
  229. )
  230. if out is not None:
  231. return out # type: ignore
  232. return update
  233. def add_middleware(self, middleware: Middleware, index: int | None = None):
  234. """Add middleware to the app.
  235. Args:
  236. middleware: The middleware to add.
  237. index: The index to add the middleware at.
  238. """
  239. if index is None:
  240. self.middleware.append(middleware)
  241. else:
  242. self.middleware.insert(index, middleware)
  243. @staticmethod
  244. def _generate_component(component: Component | ComponentCallable) -> Component:
  245. """Generate a component from a callable.
  246. Args:
  247. component: The component function to call or Component to return as-is.
  248. Returns:
  249. The generated component.
  250. Raises:
  251. TypeError: When an invalid component function is passed.
  252. """
  253. try:
  254. return component if isinstance(component, Component) else component()
  255. except TypeError as e:
  256. message = str(e)
  257. if "BaseVar" in message or "ComputedVar" in message:
  258. raise TypeError(
  259. "You may be trying to use an invalid Python function on a state var. "
  260. "When referencing a var inside your render code, only limited var operations are supported. "
  261. "See the var operation docs here: https://reflex.dev/docs/state/vars/#var-operations"
  262. ) from e
  263. raise e
  264. def add_page(
  265. self,
  266. component: Component | ComponentCallable,
  267. route: str | None = None,
  268. title: str = constants.DEFAULT_TITLE,
  269. description: str = constants.DEFAULT_DESCRIPTION,
  270. image=constants.DEFAULT_IMAGE,
  271. on_load: EventHandler
  272. | EventSpec
  273. | list[EventHandler | EventSpec]
  274. | None = None,
  275. meta: list[dict[str, str]] = constants.DEFAULT_META_LIST,
  276. script_tags: list[Component] | None = None,
  277. ):
  278. """Add a page to the app.
  279. If the component is a callable, by default the route is the name of the
  280. function. Otherwise, a route must be provided.
  281. Args:
  282. component: The component to display at the page.
  283. route: The route to display the component at.
  284. title: The title of the page.
  285. description: The description of the page.
  286. image: The image to display on the page.
  287. on_load: The event handler(s) that will be called each time the page load.
  288. meta: The metadata of the page.
  289. script_tags: List of script tags to be added to component
  290. """
  291. # If the route is not set, get it from the callable.
  292. if route is None:
  293. assert isinstance(
  294. component, Callable
  295. ), "Route must be set if component is not a callable."
  296. route = component.__name__
  297. # Check if the route given is valid
  298. verify_route_validity(route)
  299. # Apply dynamic args to the route.
  300. self.state.setup_dynamic_args(get_route_args(route))
  301. # Generate the component if it is a callable.
  302. component = self._generate_component(component)
  303. # Wrap the component in a fragment with optional overlay.
  304. if self.overlay_component is not None:
  305. component = Fragment.create(
  306. self._generate_component(self.overlay_component),
  307. component,
  308. )
  309. else:
  310. component = Fragment.create(component)
  311. # Add meta information to the component.
  312. compiler_utils.add_meta(
  313. component,
  314. title=title,
  315. image=image,
  316. description=description,
  317. meta=meta,
  318. )
  319. # Add script tags if given
  320. if script_tags:
  321. component.children.extend(script_tags)
  322. # Format the route.
  323. route = format.format_route(route)
  324. # Add the page.
  325. self._check_routes_conflict(route)
  326. self.pages[route] = component
  327. # Add the load events.
  328. if on_load:
  329. if not isinstance(on_load, list):
  330. on_load = [on_load]
  331. self.load_events[route] = on_load
  332. def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
  333. """Get the load events for a route.
  334. Args:
  335. route: The route to get the load events for.
  336. Returns:
  337. The load events for the route.
  338. """
  339. route = route.lstrip("/")
  340. if route == "":
  341. route = constants.INDEX_ROUTE
  342. return self.load_events.get(route, [])
  343. def _check_routes_conflict(self, new_route: str):
  344. """Verify if there is any conflict between the new route and any existing route.
  345. Based on conflicts that NextJS would throw if not intercepted.
  346. Raises:
  347. ValueError: exception showing which conflict exist with the route to be added
  348. Args:
  349. new_route: the route being newly added.
  350. """
  351. newroute_catchall = catchall_in_route(new_route)
  352. if not newroute_catchall:
  353. return
  354. for route in self.pages:
  355. route = "" if route == "index" else route
  356. if new_route.startswith(f"{route}/[[..."):
  357. raise ValueError(
  358. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  359. )
  360. route_catchall = catchall_in_route(route)
  361. if (
  362. route_catchall
  363. and newroute_catchall
  364. and catchall_prefix(route) == catchall_prefix(new_route)
  365. ):
  366. raise ValueError(
  367. f"You cannot use multiple catchall for the same dynamic route ({route} !== {new_route})"
  368. )
  369. def add_custom_404_page(
  370. self,
  371. component: Component | ComponentCallable | None = None,
  372. title: str = constants.TITLE_404,
  373. image: str = constants.FAVICON_404,
  374. description: str = constants.DESCRIPTION_404,
  375. on_load: EventHandler
  376. | EventSpec
  377. | list[EventHandler | EventSpec]
  378. | None = None,
  379. meta: list[dict[str, str]] = constants.DEFAULT_META_LIST,
  380. ):
  381. """Define a custom 404 page for any url having no match.
  382. If there is no page defined on 'index' route, add the 404 page to it.
  383. If there is no global catchall defined, add the 404 page with a catchall
  384. Args:
  385. component: The component to display at the page.
  386. title: The title of the page.
  387. description: The description of the page.
  388. image: The image to display on the page.
  389. on_load: The event handler(s) that will be called each time the page load.
  390. meta: The metadata of the page.
  391. """
  392. if component is None:
  393. component = Default404Page.create()
  394. self.add_page(
  395. component=wait_for_client_redirect(self._generate_component(component)),
  396. route=constants.SLUG_404,
  397. title=title or constants.TITLE_404,
  398. image=image or constants.FAVICON_404,
  399. description=description or constants.DESCRIPTION_404,
  400. on_load=on_load,
  401. meta=meta,
  402. )
  403. def setup_admin_dash(self):
  404. """Setup the admin dash."""
  405. # Get the admin dash.
  406. admin_dash = self.admin_dash
  407. if admin_dash and admin_dash.models:
  408. # Build the admin dashboard
  409. admin = (
  410. admin_dash.admin
  411. if admin_dash.admin
  412. else Admin(
  413. engine=Model.get_db_engine(),
  414. title="Reflex Admin Dashboard",
  415. logo_url="https://reflex.dev/Reflex.svg",
  416. )
  417. )
  418. for model in admin_dash.models:
  419. view = admin_dash.view_overrides.get(model, ModelView)
  420. admin.add_view(view(model))
  421. admin.mount_to(self.api)
  422. def get_frontend_packages(self, imports: Dict[str, str]):
  423. """Gets the frontend packages to be installed and filters out the unnecessary ones.
  424. Args:
  425. imports: A dictionary containing the imports used in the current page.
  426. Example:
  427. >>> get_frontend_packages({"react": "16.14.0", "react-dom": "16.14.0"})
  428. """
  429. page_imports = {
  430. i
  431. for i in imports
  432. if i not in compiler.DEFAULT_IMPORTS.keys()
  433. and i != "focus-visible/dist/focus-visible"
  434. and "next" not in i
  435. and not i.startswith("/")
  436. and i != ""
  437. }
  438. frontend_packages = get_config().frontend_packages
  439. _frontend_packages = []
  440. for package in frontend_packages:
  441. if package in get_config().tailwind.get("plugins", []): # type: ignore
  442. console.warn(
  443. f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`"
  444. )
  445. continue
  446. if package in page_imports:
  447. console.warn(
  448. f"React packages and their dependencies are inferred from Component.library and Component.lib_dependencies, remove `{package}` from `frontend_packages`"
  449. )
  450. continue
  451. _frontend_packages.append(package)
  452. page_imports.update(_frontend_packages)
  453. prerequisites.install_frontend_packages(page_imports)
  454. def compile(self):
  455. """Compile the app and output it to the pages folder."""
  456. if os.environ.get(constants.SKIP_COMPILE_ENV_VAR) == "yes":
  457. return
  458. # Create a progress bar.
  459. progress = Progress(
  460. *Progress.get_default_columns()[:-1],
  461. MofNCompleteColumn(),
  462. TimeElapsedColumn(),
  463. )
  464. for render, kwargs in DECORATED_PAGES:
  465. self.add_page(render, **kwargs)
  466. # Render a default 404 page if the user didn't supply one
  467. if constants.SLUG_404 not in self.pages:
  468. self.add_custom_404_page()
  469. task = progress.add_task("Compiling: ", total=len(self.pages))
  470. # TODO: include all work done in progress indicator, not just self.pages
  471. # Get the env mode.
  472. config = get_config()
  473. # Store the compile results.
  474. compile_results = []
  475. # Compile the pages in parallel.
  476. custom_components = set()
  477. # TODO Anecdotally, processes=2 works 10% faster (cpu_count=12)
  478. thread_pool = ThreadPool()
  479. all_imports = {}
  480. with progress:
  481. for route, component in self.pages.items():
  482. # TODO: this progress does not reflect actual threaded task completion
  483. progress.advance(task)
  484. component.add_style(self.style)
  485. compile_results.append(
  486. thread_pool.apply_async(
  487. compiler.compile_page,
  488. args=(
  489. route,
  490. component,
  491. self.state,
  492. ),
  493. )
  494. )
  495. # add component.get_imports() to all_imports
  496. all_imports.update(component.get_imports())
  497. # Add the custom components from the page to the set.
  498. custom_components |= component.get_custom_components()
  499. thread_pool.close()
  500. thread_pool.join()
  501. # Get the results.
  502. compile_results = [result.get() for result in compile_results]
  503. # TODO the compile tasks below may also benefit from parallelization too
  504. # Compile the custom components.
  505. compile_results.append(compiler.compile_components(custom_components))
  506. # Iterate through all the custom components and add their imports to the all_imports
  507. for component in custom_components:
  508. all_imports.update(component.get_imports())
  509. # Compile the root document with base styles and fonts
  510. compile_results.append(compiler.compile_document_root(self.stylesheets))
  511. # Compile the theme.
  512. compile_results.append(compiler.compile_theme(self.style))
  513. # Compile the contexts.
  514. compile_results.append(compiler.compile_contexts(self.state))
  515. # Compile the Tailwind config.
  516. if config.tailwind is not None:
  517. config.tailwind["content"] = config.tailwind.get(
  518. "content", constants.TAILWIND_CONTENT
  519. )
  520. compile_results.append(compiler.compile_tailwind(config.tailwind))
  521. # Empty the .web pages directory
  522. compiler.purge_web_pages_dir()
  523. # install frontend packages
  524. self.get_frontend_packages(all_imports)
  525. # Write the pages at the end to trigger the NextJS hot reload only once.
  526. thread_pool = ThreadPool()
  527. for output_path, code in compile_results:
  528. thread_pool.apply_async(compiler_utils.write_page, args=(output_path, code))
  529. thread_pool.close()
  530. thread_pool.join()
  531. async def process(
  532. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  533. ) -> AsyncIterator[StateUpdate]:
  534. """Process an event.
  535. Args:
  536. app: The app to process the event for.
  537. event: The event to process.
  538. sid: The Socket.IO session id.
  539. headers: The client headers.
  540. client_ip: The client_ip.
  541. Yields:
  542. The state updates after processing the event.
  543. """
  544. # Get the state for the session.
  545. state = app.state_manager.get_state(event.token)
  546. # Add request data to the state.
  547. router_data = event.router_data
  548. router_data.update(
  549. {
  550. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  551. constants.RouteVar.CLIENT_TOKEN: event.token,
  552. constants.RouteVar.SESSION_ID: sid,
  553. constants.RouteVar.HEADERS: headers,
  554. constants.RouteVar.CLIENT_IP: client_ip,
  555. }
  556. )
  557. # re-assign only when the value is different
  558. if state.router_data != router_data:
  559. # assignment will recurse into substates and force recalculation of
  560. # dependent ComputedVar (dynamic route variables)
  561. state.router_data = router_data
  562. # Preprocess the event.
  563. update = await app.preprocess(state, event)
  564. # If there was an update, yield it.
  565. if update is not None:
  566. yield update
  567. # Only process the event if there is no update.
  568. else:
  569. # Process the event.
  570. async for update in state._process(event):
  571. # Postprocess the event.
  572. update = await app.postprocess(state, event, update)
  573. # Yield the update.
  574. yield update
  575. # Set the state for the session.
  576. app.state_manager.set_state(event.token, state)
  577. async def ping() -> str:
  578. """Test API endpoint.
  579. Returns:
  580. The response.
  581. """
  582. return "pong"
  583. def upload(app: App):
  584. """Upload a file.
  585. Args:
  586. app: The app to upload the file for.
  587. Returns:
  588. The upload function.
  589. """
  590. async def upload_file(files: List[UploadFile]):
  591. """Upload a file.
  592. Args:
  593. files: The file(s) to upload.
  594. Raises:
  595. ValueError: if there are no args with supported annotation.
  596. """
  597. assert files[0].filename is not None
  598. token, handler = files[0].filename.split(":")[:2]
  599. for file in files:
  600. assert file.filename is not None
  601. file.filename = file.filename.split(":")[-1]
  602. # Get the state for the session.
  603. state = app.state_manager.get_state(token)
  604. # get the current session ID
  605. sid = state.get_sid()
  606. # get the current state(parent state/substate)
  607. path = handler.split(".")[:-1]
  608. current_state = state.get_substate(path)
  609. handler_upload_param = ()
  610. # get handler function
  611. func = getattr(current_state, handler.split(".")[-1])
  612. # check if there exists any handler args with annotation, List[UploadFile]
  613. for k, v in inspect.getfullargspec(
  614. func.fn if isinstance(func, EventHandler) else func
  615. ).annotations.items():
  616. if types.is_generic_alias(v) and types._issubclass(
  617. v.__args__[0], UploadFile
  618. ):
  619. handler_upload_param = (k, v)
  620. break
  621. if not handler_upload_param:
  622. raise ValueError(
  623. f"`{handler}` handler should have a parameter annotated as List["
  624. f"rx.UploadFile]"
  625. )
  626. event = Event(
  627. token=token,
  628. name=handler,
  629. payload={handler_upload_param[0]: files},
  630. )
  631. async for update in state._process(event):
  632. # Postprocess the event.
  633. update = await app.postprocess(state, event, update)
  634. # Send update to client
  635. await asyncio.create_task(
  636. app.event_namespace.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid) # type: ignore
  637. )
  638. # Set the state for the session.
  639. app.state_manager.set_state(event.token, state)
  640. return upload_file
  641. class EventNamespace(AsyncNamespace):
  642. """The event namespace."""
  643. # The application object.
  644. app: App
  645. def __init__(self, namespace: str, app: App):
  646. """Initialize the event namespace.
  647. Args:
  648. namespace: The namespace.
  649. app: The application object.
  650. """
  651. super().__init__(namespace)
  652. self.app = app
  653. def on_connect(self, sid, environ):
  654. """Event for when the websocket is connected.
  655. Args:
  656. sid: The Socket.IO session id.
  657. environ: The request information, including HTTP headers.
  658. """
  659. pass
  660. def on_disconnect(self, sid):
  661. """Event for when the websocket disconnects.
  662. Args:
  663. sid: The Socket.IO session id.
  664. """
  665. pass
  666. async def on_event(self, sid, data):
  667. """Event for receiving front-end websocket events.
  668. Args:
  669. sid: The Socket.IO session id.
  670. data: The event data.
  671. """
  672. # Get the event.
  673. event = Event.parse_raw(data)
  674. # Get the event environment.
  675. assert self.app.sio is not None
  676. environ = self.app.sio.get_environ(sid, self.namespace)
  677. assert environ is not None
  678. # Get the client headers.
  679. headers = {
  680. k.decode("utf-8"): v.decode("utf-8")
  681. for (k, v) in environ["asgi.scope"]["headers"]
  682. }
  683. # Get the client IP
  684. client_ip = environ["REMOTE_ADDR"]
  685. # Process the events.
  686. async for update in process(self.app, event, sid, headers, client_ip):
  687. # Emit the event.
  688. await asyncio.create_task(
  689. self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  690. )
  691. async def on_ping(self, sid):
  692. """Event for testing the API endpoint.
  693. Args:
  694. sid: The Socket.IO session id.
  695. """
  696. # Emit the test event.
  697. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)