1
0

app.py 50 KB

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