app.py 27 KB

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