websocket 使用python运行后台任务

brjng4g3  于 2024-01-09  发布在  Python
关注(0)|答案(1)|浏览(307)

我正在构建一个WebSocket服务器,其中我希望有一个后台任务,从SQS接收消息,并将其发送到客户端,同时不阻止其余的事件。
但是当我用uvicorn RuntimeWarning: coroutine 'background_task' was never awaited.运行服务器时,
我怎样才能让它连续地向客户端发送数据而不阻塞其余的事件呢?

  1. import socketio
  2. import threading
  3. import json
  4. from sqs_handler import SQSQueue
  5. sio = socketio.AsyncServer(async_mode='asgi')
  6. app = socketio.ASGIApp(sio, static_files={"/": "./"})
  7. @sio.event
  8. async def connect(sid, environ):
  9. print(sid, "connected")
  10. @sio.event
  11. async def disconnect(sid):
  12. print(sid, "disconnected")
  13. @sio.event
  14. async def item_removed(sid, data):
  15. await sio.emit("item_removed", data)
  16. async def background_task():
  17. queue = SQSQueue()
  18. while True:
  19. message = queue.get_next_message_from_sqs()
  20. data = json.loads(message.body)
  21. await sio.emit('item_added', data)
  22. background_thread = threading.Thread(target=background_task)
  23. background_thread.daemon = True
  24. background_thread.start()

字符串

ui7jx7zq

ui7jx7zq1#

import asyncio添加到您的导入中,并将线程创建行更改为:
background_thread = threading.Thread(target=asyncio.run, args=(background_task,))
(Pay注意双括号和尾随逗号)。
如果它是一个cnrc函数,它必须在cnrc循环中运行-asyncio.run是创建默认循环并执行协同例程的方便快捷方式,已经在进程中“等待”它。

相关问题