如何在Python中创建异步生成器?

Eri*_*and 12 python asynchronous generator async-await python-asyncio

我正在尝试将此Python2.7代码重写为新的异步世界顺序:

def get_api_results(func, iterable):
    pool = multiprocessing.Pool(5)
    for res in pool.map(func, iterable):
        yield res
Run Code Online (Sandbox Code Playgroud)

map()阻塞直到计算完所有结果,所以我试图将其重写为异步实现,一旦准备就会产生结果.同样map(),返回值必须按照与之相同的顺序返回iterable.我试过这个(我需要requests因为传统的身份验证要求):

import requests

def get(i):
    r = requests.get('https://example.com/api/items/%s' % i)
    return i, r.json()

async def get_api_results():
    loop = asyncio.get_event_loop()
    futures = []
    for n in range(1, 11):
        futures.append(loop.run_in_executor(None, get, n))
    async for f in futures:
        k, v = await f
        yield k, v

for r in get_api_results():
    print(r)
Run Code Online (Sandbox Code Playgroud)

但是使用Python 3.6我得到了:

  File "scratch.py", line 16, in <module>
    for r in get_api_results():
TypeError: 'async_generator' object is not iterable
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

Udi*_*Udi 12

关于旧的(2.7)代码 - 多处理被认为是更简单的线程模块的强大替代品,用于同时处理CPU密集型任务,其中线程不能很好地工作.您的代码可能不受CPU限制 - 因为它只需要发出HTTP请求 - 并且线程可能足以解决您的问题.

但是,threadingPython 3+没有直接使用,而是有一个名为concurrent.futures的漂亮模块,它通过很酷的Executor类提供更清晰的API .该模块也可用于python 2.7作为外部包.

以下代码适用于python 2和python 3:

# For python 2, first run:
#
#    pip install futures
#
from __future__ import print_function

import requests
from concurrent import futures

URLS = [
    'http://httpbin.org/delay/1',
    'http://httpbin.org/delay/3',
    'http://httpbin.org/delay/6',
    'http://www.foxnews.com/',
    'http://www.cnn.com/',
    'http://europe.wsj.com/',
    'http://www.bbc.co.uk/',
    'http://some-made-up-domain.coooom/',
]


def fetch(url):
    r = requests.get(url)
    r.raise_for_status()
    return r.content


def fetch_all(urls):
    with futures.ThreadPoolExecutor(max_workers=5) as executor:
        future_to_url = {executor.submit(fetch, url): url for url in urls}
        print("All URLs submitted.")
        for future in futures.as_completed(future_to_url):
            url = future_to_url[future]
            if future.exception() is None:
                yield url, future.result()
            else:
                # print('%r generated an exception: %s' % (
                # url, future.exception()))
                yield url, None


for url, s in fetch_all(URLS):
    status = "{:,.0f} bytes".format(len(s)) if s is not None else "Failed"
    print('{}: {}'.format(url, status))
Run Code Online (Sandbox Code Playgroud)

此代码futures.ThreadPoolExecutor基于线程使用.as_completed()这里使用了很多魔法.

你上面的python 3.6代码,用于run_in_executor()创建一个futures.ProcessPoolExecutor(),并没有真正使用异步IO!

如果您真的想继续使用asyncio,则需要使用支持asyncio的HTTP客户端,例如aiohttp.这是一个示例代码:

import asyncio

import aiohttp


async def fetch(session, url):
    print("Getting {}...".format(url))
    async with session.get(url) as resp:
        text = await resp.text()
    return "{}: Got {} bytes".format(url, len(text))


async def fetch_all():
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, "http://httpbin.org/delay/{}".format(delay))
                 for delay in (1, 1, 2, 3, 3)]
        for task in asyncio.as_completed(tasks):
            print(await task)
    return "Done."


loop = asyncio.get_event_loop()
resp = loop.run_until_complete(fetch_all())
print(resp)
loop.close()
Run Code Online (Sandbox Code Playgroud)

如您所见,asyncio还有一个as_completed(),现在使用真正的异步IO,在一个进程上只使用一个线程.


Mar*_*ers 6

您将事件循环放在另一个协同例程中.不要那样做.事件循环是异步代码的最外层"驱动程序",应该是同步运行的.

如果您需要处理获取的结果,请编写更多协程来执行此操作.他们可以从队列中获取数据,或者可以直接驱动提取.

您可以拥有一个获取和处理结果的主函数,例如:

async def main(loop): 
    for n in range(1, 11):
        future = loop.run_in_executor(None, get, n)
        k, v = await future
        # do something with the result

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
Run Code Online (Sandbox Code Playgroud)

get()也使用异步库使函数正确异步,aiohttp因此您根本不必使用执行程序.