websocket 使用python运行后台任务

brjng4g3  于 9个月前  发布在  Python
关注(0)|答案(1)|浏览(128)

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

import socketio
import threading
import json
from sqs_handler import SQSQueue

sio = socketio.AsyncServer(async_mode='asgi')
app = socketio.ASGIApp(sio, static_files={"/": "./"})

@sio.event
async def connect(sid, environ):
    print(sid, "connected")

@sio.event
async def disconnect(sid):
    print(sid, "disconnected")

@sio.event
async def item_removed(sid, data):

    await sio.emit("item_removed", data)

async def background_task():
    queue = SQSQueue()
    while True:
        message = queue.get_next_message_from_sqs()
        data = json.loads(message.body)
        await sio.emit('item_added', data)

background_thread = threading.Thread(target=background_task)
background_thread.daemon = True
background_thread.start()

字符串

ui7jx7zq

ui7jx7zq1#

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

相关问题