Process an event in the background and emit updates as they arrive. Args: state: The state to process the event for. event: The event to process. Returns: Task if the event was backgroundable, otherwise None
(
self, state: BaseState, event: Event
)
| 833 | ) |
| 834 | |
| 835 | def _process_background( |
| 836 | self, state: BaseState, event: Event |
| 837 | ) -> asyncio.Task | None: |
| 838 | """Process an event in the background and emit updates as they arrive. |
| 839 | |
| 840 | Args: |
| 841 | state: The state to process the event for. |
| 842 | event: The event to process. |
| 843 | |
| 844 | Returns: |
| 845 | Task if the event was backgroundable, otherwise None |
| 846 | """ |
| 847 | substate, handler = state._get_event_handler(event) |
| 848 | if not handler.is_background: |
| 849 | return None |
| 850 | |
| 851 | async def _coro(): |
| 852 | """Coroutine to process the event and emit updates inside an asyncio.Task. |
| 853 | |
| 854 | Raises: |
| 855 | RuntimeError: If the app has not been initialized yet. |
| 856 | """ |
| 857 | if self.event_namespace is None: |
| 858 | raise RuntimeError("App has not been initialized yet.") |
| 859 | |
| 860 | # Process the event. |
| 861 | async for update in state._process_event( |
| 862 | handler=handler, state=substate, payload=event.payload |
| 863 | ): |
| 864 | # Postprocess the event. |
| 865 | update = await self.postprocess(state, event, update) |
| 866 | |
| 867 | # Send the update to the client. |
| 868 | await self.event_namespace.emit_update( |
| 869 | update=update, |
| 870 | sid=state.router.session.session_id, |
| 871 | ) |
| 872 | |
| 873 | task = asyncio.create_task(_coro()) |
| 874 | self.background_tasks.add(task) |
| 875 | # Clean up task from background_tasks set when complete. |
| 876 | task.add_done_callback(self.background_tasks.discard) |
| 877 | return task |
| 878 | |
| 879 | |
| 880 | async def process( |
no test coverage detected