app.py 28 KB

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