python - 使用 asyncio 和 contextvars 在 python 中的两个异步程序之间共享状态

标签 python python-3.x python-asyncio python-contextvars

我当前有两个无限异步任务正在运行,并且希望在它们之间共享状态。一项任务是读取消息然后发送消息的 WebSocket 连接,另一项任务读取传入的光数据。我想在两个任务之间发送一个 bool 值,表明 websocket 连接是否成功。

这是我初始化上下文的方式。

client_connect_var = contextvars.ContextVar('client_connect',default = False)
client_connect_var.set(False)
ctx = contextvars.copy_context()
async def main():
  message = json.dumps({'payload': {
                        'payload'})
  loop = asyncio.get_event_loop()
  start_light = asyncio.create_task(calculate_idle(3))
  await asyncio.gather(init_connection(message), start_light)

ctx.run(asyncio.run(main()))

这是我的 init_connection 中的代码:

async def init_connection(message):
  async with websockets.connect(uri) as websocket:
      #This should set the global context variable to true
      client_connect_var.set(True)
      CLIENT_WS = websocket
      client_connect = client_connect_var.get()
    # send init message
    await websocket.send(message)
    print("Connection is open")
    while client_connect:
        await handleMessages(websocket, message)
    await websocket.close()

这里是它尝试获取灯光代码当前状态的地方

async def calculate_idle(t):
    orig_time = t
    while True:
        await asyncio.sleep(5)
        #This should be true, but it's false
        client_connect = client_connect_var.get()
        await asyncio.sleep(5)

在calculate_idle中,上下文中的变量仍然设置为false。我不确定如何从 init_connection 内部将其设置为 true。我想将其扩展为更新对象状态中的其他值。任何帮助将不胜感激!

最佳答案

ContextVar 的用途与您尝试使用它的目的相反:它用于任务本地的数据,类似于“任务本地”全局变量。

要在两个任务之间共享数据,您可以使用普通的 Python 共享机制,例如全局变量或普通可变值(例如字典或您选择的类的实例)。您还可以使用诸如 asyncio.Event ( https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event ) 之类的同步来在值更改时通知其他任务。

关于python - 使用 asyncio 和 contextvars 在 python 中的两个异步程序之间共享状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793952/

相关文章:

python - 如何在 Keras 中创建虚拟模型?

python - -> 在 python 函数定义中

Python 请求不响应正确的 html

Python asyncio : function or coroutine, 使用哪个?

python - 连接redis时异步代码失败

python - Python 是否需要深入了解继承链中的所有类?

python - 创建带有按钮的弹出窗口

python-3.x - 属性错误: type object 'numpy.ndarray' has no attribute '__array_function__' on import numpy 1. 15.4

python-asyncio - aiohttp 错误率随着连接数的增加而增加

python - 理解列表理解