Skip to main content
 首页 » 编程设计

python之异步/等待 : Continuously stream data from async method

2024年09月07日7JeffreyZhao

我正在使用 python 3.5 将数据从一种方法异步返回到另一种方法,如下所示:

async def A(): 
    # Need to get data here from B continuously 
    val = await B() 
 
async def B(): 
    # Need to get data here from C continuously as they get generated inside while loop of method C 
    data = await C() 
    # Modify and process the data and return to A 
    return await D(data) 
 
async def C(): 
    i = 0 
    while i < 5: 
        await asyncio.sleep(1) 
        # Return this data to method B one by one, Not sure how to do this ?? 
        return i 
 
async def D(val): 
    # Do some processing of val and return it 
    return val 

我想持续从方法 C 流式传输数据并将其返回给方法 B,在接收到每个项目时对其进行处理并将其返回给方法 A。

一种方法是使用asyncio queue 并将其从 A 传递给方法 B,再从那里进一步传递给 C。

  1. 方法C会一直写入队列中的内容。
  2. 方法 B 将从队列中读取、处理数据并更新队列。
  3. 方法 A 在最后读取队列以获取最终处理的数据。

我们能否以任何其他方式使用协程或异步方法本身来实现它?希望避免为每个请求连续读取和写入队列。

请您参考如下方法:

import asyncio 
from async_generator import async_generator, yield_, yield_from_ 
 
async def fun(n): 
    print("Finding %d-1" % n) 
    await asyncio.sleep(n/2) 
    result = n - 1 
    print("%d - 1 = %d" % (n, result)) 
    return result 
 
 
@async_generator 
async def main(l): 
    futures = [ fun(n) for n in l ] 
    for i, future in enumerate(asyncio.as_completed(futures)): 
        result = await future 
        print("inside the main..") 
        print(result) 
        await yield_(result) 
 
@async_generator 
async def dealer(): 
    l = [2, 4, 6] 
    gen = main(l) 
    async for item in gen: 
        print("inside the dealer....") 
        await yield_(item) 
 
async def dealer1(): 
    gen = dealer() 
    async for item in gen: 
        print("inside dealer 1") 
        print(item) 
 
if __name__ == "__main__": 
    loop = asyncio.get_event_loop() 
    #loop.run_until_complete(cc.main()) 
    loop.run_until_complete(dealer1()) 
    loop.close() 

您在 python3.6 中支持异步生成器。如果您使用的是 python 3.5,则可以使用 async_generator 库(https://pypi.python.org/pypi/async_generator/1.5)