[QUESTION] Background Task with websocket
See original GitHub issueDescription
Is it possible to use BackgroundTasks with websockets?
I tried with a simple case:
def test():
print('test')
@router.post("/test")
async def send_notification(background_tasks: BackgroundTasks):
background_tasks.add_task(test)
return {"message": "Notification sent in the background"}
@router.websocket("/ws")
async def listen(websocket: WebSocket, background_tasks: BackgroundTasks):
await websocket.accept()
background_tasks.add_task(test)
The send_notification
http endpoint example works, but the listen
websocket endpoint doesn’t.
Thanks!
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (2 by maintainers)
Top Results From Across the Web
Background task for web socket server - python
Specifically, I'd like to continuously poll a sensor, process input from a web socket with reference to a variable and then run a...
Read more >Async / long running background task
for long running tasks I try to use tornado. some prototype. def tornadoSioWsServer():. # py4web.py run -s tornadoSioWsServer apps. import tornado.websocket.
Read more >WebSockets - FastAPI
When a WebSocket connection is closed, the await websocket.receive_text() will raise a WebSocketDisconnect exception, which you can then catch and handle like ...
Read more >Websocket connection in background without VOIP
We need our app to be able to send coordinates in background and hold ... something more reasonable (tens of seconds) using a...
Read more >WebSocket in Background transfer and NSURLSession ...
As per Apple's documentation, NSUrlSession allows to create a WebSocket task for the provided URL. Xamarin has a short guide about using ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Background tasks internally depend on a
Request
, and they are executed after returning the request to the client. In the case of a WebSocket, as the WebSocket is not really “finished” but is an ongoing connection, it wouldn’t be a background task.Nevertheless, you can make sure an async function is executed with
asyncio.ensure_future
: https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future@targhs Here is an example. This came late but hope it helps someone.