event.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. """Define event classes to connect the frontend and backend."""
  2. from __future__ import annotations
  3. import inspect
  4. from types import FunctionType
  5. from typing import (
  6. TYPE_CHECKING,
  7. Any,
  8. Callable,
  9. Dict,
  10. List,
  11. Optional,
  12. Tuple,
  13. Type,
  14. Union,
  15. )
  16. from reflex import constants
  17. from reflex.base import Base
  18. from reflex.utils import console, format
  19. from reflex.utils.types import ArgsSpec
  20. from reflex.vars import BaseVar, Var
  21. if TYPE_CHECKING:
  22. from reflex.state import BaseState
  23. class Event(Base):
  24. """An event that describes any state change in the app."""
  25. # The token to specify the client that the event is for.
  26. token: str
  27. # The event name.
  28. name: str
  29. # The routing data where event occurred
  30. router_data: Dict[str, Any] = {}
  31. # The event payload.
  32. payload: Dict[str, Any] = {}
  33. BACKGROUND_TASK_MARKER = "_reflex_background_task"
  34. def background(fn):
  35. """Decorator to mark event handler as running in the background.
  36. Args:
  37. fn: The function to decorate.
  38. Returns:
  39. The same function, but with a marker set.
  40. Raises:
  41. TypeError: If the function is not a coroutine function or async generator.
  42. """
  43. if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn):
  44. raise TypeError("Background task must be async function or generator.")
  45. setattr(fn, BACKGROUND_TASK_MARKER, True)
  46. return fn
  47. def _no_chain_background_task(
  48. state_cls: Type["BaseState"], name: str, fn: Callable
  49. ) -> Callable:
  50. """Protect against directly chaining a background task from another event handler.
  51. Args:
  52. state_cls: The state class that the event handler is in.
  53. name: The name of the background task.
  54. fn: The background task coroutine function / generator.
  55. Returns:
  56. A compatible coroutine function / generator that raises a runtime error.
  57. Raises:
  58. TypeError: If the background task is not async.
  59. """
  60. call = f"{state_cls.__name__}.{name}"
  61. message = (
  62. f"Cannot directly call background task {name!r}, use "
  63. f"`yield {call}` or `return {call}` instead."
  64. )
  65. if inspect.iscoroutinefunction(fn):
  66. async def _no_chain_background_task_co(*args, **kwargs):
  67. raise RuntimeError(message)
  68. return _no_chain_background_task_co
  69. if inspect.isasyncgenfunction(fn):
  70. async def _no_chain_background_task_gen(*args, **kwargs):
  71. yield
  72. raise RuntimeError(message)
  73. return _no_chain_background_task_gen
  74. raise TypeError(f"{fn} is marked as a background task, but is not async.")
  75. class EventActionsMixin(Base):
  76. """Mixin for DOM event actions."""
  77. # Whether to `preventDefault` or `stopPropagation` on the event.
  78. event_actions: Dict[str, bool] = {}
  79. @property
  80. def stop_propagation(self):
  81. """Stop the event from bubbling up the DOM tree.
  82. Returns:
  83. New EventHandler-like with stopPropagation set to True.
  84. """
  85. return self.copy(
  86. update={"event_actions": {"stopPropagation": True, **self.event_actions}},
  87. )
  88. @property
  89. def prevent_default(self):
  90. """Prevent the default behavior of the event.
  91. Returns:
  92. New EventHandler-like with preventDefault set to True.
  93. """
  94. return self.copy(
  95. update={"event_actions": {"preventDefault": True, **self.event_actions}},
  96. )
  97. class EventHandler(EventActionsMixin):
  98. """An event handler responds to an event to update the state."""
  99. # The function to call in response to the event.
  100. fn: Any
  101. class Config:
  102. """The Pydantic config."""
  103. # Needed to allow serialization of Callable.
  104. frozen = True
  105. @property
  106. def is_background(self) -> bool:
  107. """Whether the event handler is a background task.
  108. Returns:
  109. True if the event handler is marked as a background task.
  110. """
  111. return getattr(self.fn, BACKGROUND_TASK_MARKER, False)
  112. def __call__(self, *args: Var) -> EventSpec:
  113. """Pass arguments to the handler to get an event spec.
  114. This method configures event handlers that take in arguments.
  115. Args:
  116. *args: The arguments to pass to the handler.
  117. Returns:
  118. The event spec, containing both the function and args.
  119. Raises:
  120. TypeError: If the arguments are invalid.
  121. """
  122. # Get the function args.
  123. fn_args = inspect.getfullargspec(self.fn).args[1:]
  124. fn_args = (Var.create_safe(arg) for arg in fn_args)
  125. # Construct the payload.
  126. values = []
  127. for arg in args:
  128. # Special case for file uploads.
  129. if isinstance(arg, FileUpload):
  130. return arg.as_event_spec(handler=self)
  131. # Otherwise, convert to JSON.
  132. try:
  133. values.append(Var.create(arg, _var_is_string=type(arg) is str))
  134. except TypeError as e:
  135. raise TypeError(
  136. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  137. ) from e
  138. payload = tuple(zip(fn_args, values))
  139. # Return the event spec.
  140. return EventSpec(
  141. handler=self, args=payload, event_actions=self.event_actions.copy()
  142. )
  143. class EventSpec(EventActionsMixin):
  144. """An event specification.
  145. Whereas an Event object is passed during runtime, a spec is used
  146. during compile time to outline the structure of an event.
  147. """
  148. # The event handler.
  149. handler: EventHandler
  150. # The handler on the client to process event.
  151. client_handler_name: str = ""
  152. # The arguments to pass to the function.
  153. args: Tuple[Tuple[Var, Var], ...] = ()
  154. class Config:
  155. """The Pydantic config."""
  156. # Required to allow tuple fields.
  157. frozen = True
  158. def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
  159. """Copy the event spec, with updated args.
  160. Args:
  161. args: The new args to pass to the function.
  162. Returns:
  163. A copy of the event spec, with the new args.
  164. """
  165. return type(self)(
  166. handler=self.handler,
  167. client_handler_name=self.client_handler_name,
  168. args=args,
  169. event_actions=self.event_actions.copy(),
  170. )
  171. class CallableEventSpec(EventSpec):
  172. """Decorate an EventSpec-returning function to act as both a EventSpec and a function.
  173. This is used as a compatibility shim for replacing EventSpec objects in the
  174. API with functions that return a family of EventSpec.
  175. """
  176. fn: Optional[Callable[..., EventSpec]] = None
  177. def __init__(self, fn: Callable[..., EventSpec] | None = None, **kwargs):
  178. """Initialize a CallableEventSpec.
  179. Args:
  180. fn: The function to decorate.
  181. **kwargs: The kwargs to pass to pydantic initializer
  182. """
  183. if fn is not None:
  184. default_event_spec = fn()
  185. super().__init__(
  186. fn=fn, # type: ignore
  187. **dict(default_event_spec),
  188. **kwargs,
  189. )
  190. else:
  191. super().__init__(**kwargs)
  192. def __call__(self, *args, **kwargs) -> EventSpec:
  193. """Call the decorated function.
  194. Args:
  195. *args: The args to pass to the function.
  196. **kwargs: The kwargs to pass to the function.
  197. Returns:
  198. The EventSpec returned from calling the function.
  199. Raises:
  200. TypeError: If the CallableEventSpec has no associated function.
  201. """
  202. if self.fn is None:
  203. raise TypeError("CallableEventSpec has no associated function.")
  204. return self.fn(*args, **kwargs)
  205. class EventChain(EventActionsMixin):
  206. """Container for a chain of events that will be executed in order."""
  207. events: List[EventSpec]
  208. args_spec: Optional[Callable]
  209. # These chains can be used for their side effects when no other events are desired.
  210. stop_propagation = EventChain(events=[], args_spec=lambda: []).stop_propagation
  211. prevent_default = EventChain(events=[], args_spec=lambda: []).prevent_default
  212. class Target(Base):
  213. """A Javascript event target."""
  214. checked: bool = False
  215. value: Any = None
  216. class FrontendEvent(Base):
  217. """A Javascript event."""
  218. target: Target = Target()
  219. key: str = ""
  220. value: Any = None
  221. class FileUpload(Base):
  222. """Class to represent a file upload."""
  223. upload_id: Optional[str] = None
  224. on_upload_progress: Optional[Union[EventHandler, Callable]] = None
  225. @staticmethod
  226. def on_upload_progress_args_spec(_prog: dict[str, int | float | bool]):
  227. """Args spec for on_upload_progress event handler.
  228. Returns:
  229. The arg mapping passed to backend event handler
  230. """
  231. return [_prog]
  232. def as_event_spec(self, handler: EventHandler) -> EventSpec:
  233. """Get the EventSpec for the file upload.
  234. Args:
  235. handler: The event handler.
  236. Returns:
  237. The event spec for the handler.
  238. Raises:
  239. ValueError: If the on_upload_progress is not a valid event handler.
  240. """
  241. from reflex.components.forms.upload import (
  242. DEFAULT_UPLOAD_ID,
  243. upload_files_context_var_data,
  244. )
  245. upload_id = self.upload_id or DEFAULT_UPLOAD_ID
  246. spec_args = [
  247. (
  248. Var.create_safe("files"),
  249. Var.create_safe(f"filesById.{upload_id}")._replace(
  250. _var_data=upload_files_context_var_data
  251. ),
  252. ),
  253. (
  254. Var.create_safe("upload_id"),
  255. Var.create_safe(upload_id, _var_is_string=True),
  256. ),
  257. ]
  258. if self.on_upload_progress is not None:
  259. on_upload_progress = self.on_upload_progress
  260. if isinstance(on_upload_progress, EventHandler):
  261. events = [
  262. call_event_handler(
  263. on_upload_progress,
  264. self.on_upload_progress_args_spec,
  265. ),
  266. ]
  267. elif isinstance(on_upload_progress, Callable):
  268. # Call the lambda to get the event chain.
  269. events = call_event_fn(on_upload_progress, self.on_upload_progress_args_spec) # type: ignore
  270. else:
  271. raise ValueError(f"{on_upload_progress} is not a valid event handler.")
  272. on_upload_progress_chain = EventChain(
  273. events=events,
  274. args_spec=self.on_upload_progress_args_spec,
  275. )
  276. formatted_chain = str(format.format_prop(on_upload_progress_chain))
  277. spec_args.append(
  278. (
  279. Var.create_safe("on_upload_progress"),
  280. BaseVar(
  281. _var_name=formatted_chain.strip("{}"),
  282. _var_type=EventChain,
  283. ),
  284. ),
  285. )
  286. return EventSpec(
  287. handler=handler,
  288. client_handler_name="uploadFiles",
  289. args=tuple(spec_args),
  290. event_actions=handler.event_actions.copy(),
  291. )
  292. # Alias for rx.upload_files
  293. upload_files = FileUpload
  294. # Special server-side events.
  295. def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
  296. """A server-side event.
  297. Args:
  298. name: The name of the event.
  299. sig: The function signature of the event.
  300. **kwargs: The arguments to pass to the event.
  301. Returns:
  302. An event spec for a server-side event.
  303. """
  304. def fn():
  305. return None
  306. fn.__qualname__ = name
  307. fn.__signature__ = sig
  308. return EventSpec(
  309. handler=EventHandler(fn=fn),
  310. args=tuple(
  311. (Var.create_safe(k), Var.create_safe(v, _var_is_string=type(v) is str))
  312. for k, v in kwargs.items()
  313. ),
  314. )
  315. def redirect(path: str | Var[str], external: Optional[bool] = False) -> EventSpec:
  316. """Redirect to a new path.
  317. Args:
  318. path: The path to redirect to.
  319. external: Whether to open in new tab or not.
  320. Returns:
  321. An event to redirect to the path.
  322. """
  323. return server_side(
  324. "_redirect", get_fn_signature(redirect), path=path, external=external
  325. )
  326. def console_log(message: str | Var[str]) -> EventSpec:
  327. """Do a console.log on the browser.
  328. Args:
  329. message: The message to log.
  330. Returns:
  331. An event to log the message.
  332. """
  333. return server_side("_console", get_fn_signature(console_log), message=message)
  334. def window_alert(message: str | Var[str]) -> EventSpec:
  335. """Create a window alert on the browser.
  336. Args:
  337. message: The message to alert.
  338. Returns:
  339. An event to alert the message.
  340. """
  341. return server_side("_alert", get_fn_signature(window_alert), message=message)
  342. def set_focus(ref: str) -> EventSpec:
  343. """Set focus to specified ref.
  344. Args:
  345. ref: The ref.
  346. Returns:
  347. An event to set focus on the ref
  348. """
  349. return server_side(
  350. "_set_focus",
  351. get_fn_signature(set_focus),
  352. ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
  353. )
  354. def set_value(ref: str, value: Any) -> EventSpec:
  355. """Set the value of a ref.
  356. Args:
  357. ref: The ref.
  358. value: The value to set.
  359. Returns:
  360. An event to set the ref.
  361. """
  362. return server_side(
  363. "_set_value",
  364. get_fn_signature(set_value),
  365. ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
  366. value=value,
  367. )
  368. def remove_cookie(key: str, options: dict[str, Any] | None = None) -> EventSpec:
  369. """Remove a cookie on the frontend.
  370. Args:
  371. key: The key identifying the cookie to be removed.
  372. options: Support all the cookie options from RFC 6265
  373. Returns:
  374. EventSpec: An event to remove a cookie.
  375. """
  376. options = options or {}
  377. options["path"] = options.get("path", "/")
  378. return server_side(
  379. "_remove_cookie",
  380. get_fn_signature(remove_cookie),
  381. key=key,
  382. options=options,
  383. )
  384. def clear_local_storage() -> EventSpec:
  385. """Set a value in the local storage on the frontend.
  386. Returns:
  387. EventSpec: An event to clear the local storage.
  388. """
  389. return server_side(
  390. "_clear_local_storage",
  391. get_fn_signature(clear_local_storage),
  392. )
  393. def remove_local_storage(key: str) -> EventSpec:
  394. """Set a value in the local storage on the frontend.
  395. Args:
  396. key: The key identifying the variable in the local storage to remove.
  397. Returns:
  398. EventSpec: An event to remove an item based on the provided key in local storage.
  399. """
  400. return server_side(
  401. "_remove_local_storage",
  402. get_fn_signature(remove_local_storage),
  403. key=key,
  404. )
  405. def set_clipboard(content: str) -> EventSpec:
  406. """Set the text in content in the clipboard.
  407. Args:
  408. content: The text to add to clipboard.
  409. Returns:
  410. EventSpec: An event to set some content in the clipboard.
  411. """
  412. return server_side(
  413. "_set_clipboard",
  414. get_fn_signature(set_clipboard),
  415. content=content,
  416. )
  417. def download(url: str | Var, filename: Optional[str | Var] = None) -> EventSpec:
  418. """Download the file at a given path.
  419. Args:
  420. url : The URL to the file to download.
  421. filename : The name that the file should be saved as after download.
  422. Raises:
  423. ValueError: If the URL provided is invalid.
  424. Returns:
  425. EventSpec: An event to download the associated file.
  426. """
  427. if isinstance(url, Var) and filename is None:
  428. filename = ""
  429. if isinstance(url, str):
  430. if not url.startswith("/"):
  431. raise ValueError("The URL argument should start with a /")
  432. # if filename is not provided, infer it from url
  433. if filename is None:
  434. filename = url.rpartition("/")[-1]
  435. return server_side(
  436. "_download",
  437. get_fn_signature(download),
  438. url=url,
  439. filename=filename,
  440. )
  441. def _callback_arg_spec(eval_result):
  442. """ArgSpec for call_script callback function.
  443. Args:
  444. eval_result: The result of the javascript execution.
  445. Returns:
  446. Args for the callback function
  447. """
  448. return [eval_result]
  449. def call_script(
  450. javascript_code: str,
  451. callback: EventHandler | Callable | None = None,
  452. ) -> EventSpec:
  453. """Create an event handler that executes arbitrary javascript code.
  454. Args:
  455. javascript_code: The code to execute.
  456. callback: EventHandler that will receive the result of evaluating the javascript code.
  457. Returns:
  458. EventSpec: An event that will execute the client side javascript.
  459. Raises:
  460. ValueError: If the callback is not a valid event handler.
  461. """
  462. callback_kwargs = {}
  463. if callback is not None:
  464. arg_name = parse_args_spec(_callback_arg_spec)[0]._var_name
  465. if isinstance(callback, EventHandler):
  466. event_spec = call_event_handler(callback, _callback_arg_spec)
  467. elif isinstance(callback, FunctionType):
  468. event_spec = call_event_fn(callback, _callback_arg_spec)[0]
  469. else:
  470. raise ValueError("Cannot use {callback!r} as a call_script callback.")
  471. callback_kwargs = {
  472. "callback": f"({arg_name}) => queueEvents([{format.format_event(event_spec)}], {constants.CompileVars.SOCKET})"
  473. }
  474. return server_side(
  475. "_call_script",
  476. get_fn_signature(call_script),
  477. javascript_code=javascript_code,
  478. **callback_kwargs,
  479. )
  480. def get_event(state, event):
  481. """Get the event from the given state.
  482. Args:
  483. state: The state.
  484. event: The event.
  485. Returns:
  486. The event.
  487. """
  488. return f"{state.get_name()}.{event}"
  489. def get_hydrate_event(state) -> str:
  490. """Get the name of the hydrate event for the state.
  491. Args:
  492. state: The state.
  493. Returns:
  494. The name of the hydrate event.
  495. """
  496. return get_event(state, constants.CompileVars.HYDRATE)
  497. def call_event_handler(
  498. event_handler: EventHandler, arg_spec: Union[Var, ArgsSpec]
  499. ) -> EventSpec:
  500. """Call an event handler to get the event spec.
  501. This function will inspect the function signature of the event handler.
  502. If it takes in an arg, the arg will be passed to the event handler.
  503. Otherwise, the event handler will be called with no args.
  504. Args:
  505. event_handler: The event handler.
  506. arg_spec: The lambda that define the argument(s) to pass to the event handler.
  507. Raises:
  508. ValueError: if number of arguments expected by event_handler doesn't match the spec.
  509. Returns:
  510. The event spec from calling the event handler.
  511. """
  512. args = inspect.getfullargspec(event_handler.fn).args
  513. # handle new API using lambda to define triggers
  514. if isinstance(arg_spec, ArgsSpec):
  515. parsed_args = parse_args_spec(arg_spec) # type: ignore
  516. if len(args) == len(["self", *parsed_args]):
  517. return event_handler(*parsed_args) # type: ignore
  518. else:
  519. source = inspect.getsource(arg_spec) # type: ignore
  520. raise ValueError(
  521. f"number of arguments in {event_handler.fn.__qualname__} "
  522. f"doesn't match the definition of the event trigger '{source.strip().strip(',')}'"
  523. )
  524. else:
  525. console.deprecate(
  526. feature_name="EVENT_ARG API for triggers",
  527. reason="Replaced by new API using lambda allow arbitrary number of args",
  528. deprecation_version="0.2.8",
  529. removal_version="0.4.0",
  530. )
  531. if len(args) == 1:
  532. return event_handler()
  533. assert (
  534. len(args) == 2
  535. ), f"Event handler {event_handler.fn} must have 1 or 2 arguments."
  536. return event_handler(arg_spec) # type: ignore
  537. def parse_args_spec(arg_spec: ArgsSpec):
  538. """Parse the args provided in the ArgsSpec of an event trigger.
  539. Args:
  540. arg_spec: The spec of the args.
  541. Returns:
  542. The parsed args.
  543. """
  544. spec = inspect.getfullargspec(arg_spec)
  545. return arg_spec(
  546. *[
  547. BaseVar(
  548. _var_name=f"_{l_arg}",
  549. _var_type=spec.annotations.get(l_arg, FrontendEvent),
  550. _var_is_local=True,
  551. )
  552. for l_arg in spec.args
  553. ]
  554. )
  555. def call_event_fn(fn: Callable, arg: Union[Var, ArgsSpec]) -> list[EventSpec]:
  556. """Call a function to a list of event specs.
  557. The function should return either a single EventSpec or a list of EventSpecs.
  558. If the function takes in an arg, the arg will be passed to the function.
  559. Otherwise, the function will be called with no args.
  560. Args:
  561. fn: The function to call.
  562. arg: The argument to pass to the function.
  563. Returns:
  564. The event specs from calling the function.
  565. Raises:
  566. ValueError: If the lambda has an invalid signature.
  567. """
  568. # Import here to avoid circular imports.
  569. from reflex.event import EventHandler, EventSpec
  570. # Get the args of the lambda.
  571. args = inspect.getfullargspec(fn).args
  572. if isinstance(arg, ArgsSpec):
  573. out = fn(*parse_args_spec(arg)) # type: ignore
  574. else:
  575. # Call the lambda.
  576. if len(args) == 0:
  577. out = fn()
  578. elif len(args) == 1:
  579. out = fn(arg)
  580. else:
  581. raise ValueError(f"Lambda {fn} must have 0 or 1 arguments.")
  582. # Convert the output to a list.
  583. if not isinstance(out, List):
  584. out = [out]
  585. # Convert any event specs to event specs.
  586. events = []
  587. for e in out:
  588. # Convert handlers to event specs.
  589. if isinstance(e, EventHandler):
  590. if len(args) == 0:
  591. e = e()
  592. elif len(args) == 1:
  593. e = e(arg) # type: ignore
  594. # Make sure the event spec is valid.
  595. if not isinstance(e, EventSpec):
  596. raise ValueError(f"Lambda {fn} returned an invalid event spec: {e}.")
  597. # Add the event spec to the chain.
  598. events.append(e)
  599. # Return the events.
  600. return events
  601. def get_handler_args(event_spec: EventSpec) -> tuple[tuple[Var, Var], ...]:
  602. """Get the handler args for the given event spec.
  603. Args:
  604. event_spec: The event spec.
  605. Returns:
  606. The handler args.
  607. """
  608. args = inspect.getfullargspec(event_spec.handler.fn).args
  609. return event_spec.args if len(args) > 1 else tuple()
  610. def fix_events(
  611. events: list[EventHandler | EventSpec] | None,
  612. token: str,
  613. router_data: dict[str, Any] | None = None,
  614. ) -> list[Event]:
  615. """Fix a list of events returned by an event handler.
  616. Args:
  617. events: The events to fix.
  618. token: The user token.
  619. router_data: The optional router data to set in the event.
  620. Returns:
  621. The fixed events.
  622. """
  623. # If the event handler returns nothing, return an empty list.
  624. if events is None:
  625. return []
  626. # If the handler returns a single event, wrap it in a list.
  627. if not isinstance(events, List):
  628. events = [events]
  629. # Fix the events created by the handler.
  630. out = []
  631. for e in events:
  632. if isinstance(e, Event):
  633. # If the event is already an event, append it to the list.
  634. out.append(e)
  635. continue
  636. if not isinstance(e, (EventHandler, EventSpec)):
  637. e = EventHandler(fn=e)
  638. # Otherwise, create an event from the event spec.
  639. if isinstance(e, EventHandler):
  640. e = e()
  641. assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
  642. name = format.format_event_handler(e.handler)
  643. payload = {k._var_name: v._decode() for k, v in e.args} # type: ignore
  644. # Filter router_data to reduce payload size
  645. event_router_data = {
  646. k: v
  647. for k, v in (router_data or {}).items()
  648. if k in constants.route.ROUTER_DATA_INCLUDE
  649. }
  650. # Create an event and append it to the list.
  651. out.append(
  652. Event(
  653. token=token,
  654. name=name,
  655. payload=payload,
  656. router_data=event_router_data,
  657. )
  658. )
  659. return out
  660. def get_fn_signature(fn: Callable) -> inspect.Signature:
  661. """Get the signature of a function.
  662. Args:
  663. fn: The function.
  664. Returns:
  665. The signature of the function.
  666. """
  667. signature = inspect.signature(fn)
  668. new_param = inspect.Parameter(
  669. "state", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
  670. )
  671. return signature.replace(parameters=(new_param, *signature.parameters.values()))