Skip to content

Commit

Permalink
Fixes #77: Pass task_id into background handler of WS endpoint for ea…
Browse files Browse the repository at this point in the history
…sy redefinition of on_receive
  • Loading branch information
dolamroth authored and DmitryBurnaev committed Mar 14, 2023
1 parent d2fdf66 commit 0f161b5
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
7 changes: 4 additions & 3 deletions docs/receipts/websockets.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,10 @@ data manager.
task group and cancels all tasks within that scope. Simply return inside background
handler, if you want to cancel a single task.

**AVOID** stuff like this https://stackoverflow.com/a/60675826
and, in general, passing event-handling primitives between tasks,
other than class-level anyio.Lock()
**NOT RECOMMENDED** to use stuff like this https://stackoverflow.com/a/60675826.
However, should you need to do so, you may redefine method
`starlette_web.common.ws.base_endpoint.BaseWSEndpoint.on_receive` to use
`anyio.TaskGroup.start` and return `CancelScope` from within background handler.

## Manually calling websocket.receive

Expand Down
6 changes: 3 additions & 3 deletions starlette_web/common/ws/base_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ async def on_connect(self, websocket: WebSocket) -> None:

async def on_receive(self, websocket: WebSocket, data: Any) -> None:
cleaned_data = self._validate(data)
self.task_group.start_soon(self._background_handler_wrap, websocket, cleaned_data)
task_id = get_random_string(50)
self.task_group.start_soon(self._background_handler_wrap, task_id, websocket, cleaned_data)

async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:
if self.task_group:
Expand All @@ -79,8 +80,7 @@ async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:

logger.debug("WS connection has been closed.")

async def _background_handler_wrap(self, websocket: WebSocket, data: Dict):
task_id = get_random_string(50)
async def _background_handler_wrap(self, task_id: str, websocket: WebSocket, data: Dict):
task_result = None

try:
Expand Down

0 comments on commit 0f161b5

Please sign in to comment.