178

我想在 中执行并行 http 请求任务asyncio,但我发现这python-requests会阻塞asyncio. 我找到了 aiohttp但它无法使用 http 代理提供 http 请求的服务。

所以我想知道是否有办法在asyncio.

4

7 回答 7

217

要将请求(或任何其他阻塞库)与 asyncio 一起使用,您可以使用BaseEventLoop.run_in_executor在另一个线程中运行函数并从中获取结果。例如:

import asyncio
import requests

@asyncio.coroutine
def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = yield from future1
    response2 = yield from future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

这将同时获得两个响应。

使用 python 3.5,您可以使用新的await/async语法:

import asyncio
import requests

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = await future1
    response2 = await future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

有关更多信息,请参阅PEP0492

于 2014-03-14T20:06:16.730 回答
102

aiohttp已经可以与 HTTP 代理一起使用:

import asyncio
import aiohttp


@asyncio.coroutine
def do_request():
    proxy_url = 'http://localhost:8118'  # your proxy address
    response = yield from aiohttp.request(
        'GET', 'http://google.com',
        proxy=proxy_url,
    )
    return response

loop = asyncio.get_event_loop()
loop.run_until_complete(do_request())
于 2014-05-21T13:30:47.190 回答
76

上面的答案仍然使用旧的 Python 3.4 风格的协程。如果你有 Python 3.5+,这是你会写的。

aiohttp 现在支持http代理

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
            'http://python.org',
            'https://google.com',
            'http://yifei.me'
        ]
    tasks = []
    async with aiohttp.ClientSession() as session:
        for url in urls:
            tasks.append(fetch(session, url))
        htmls = await asyncio.gather(*tasks)
        for html in htmls:
            print(html[:100])

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

还有一个httpx库,它是支持请求的替代品async/await

于 2018-05-13T05:17:33.183 回答
14

Requests 目前不支持asyncio,也没有计划提供此类支持。您可能可以实现一个知道如何使用的自定义“传输适配器”(如此asyncio所述) 。

如果我发现自己有一段时间,我可能会真正研究一下,但我不能保证任何事情。

于 2014-03-05T10:56:57.310 回答
12

在 Pimin Konstantin Kefaloukos 的文章中,有一个很好的 async/await 循环和线程案例 使用 Python 和 asyncio 轻松并行 HTTP 请求

为了最小化总完成时间,我们可以增加线程池的大小以匹配我们必须发出的请求数。幸运的是,这很容易做到,我们将在接下来看到。下面的代码清单是一个示例,说明如何使用包含 20 个工作线程的线程池发出 20 个异步 HTTP 请求:

# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
于 2017-11-30T11:17:03.990 回答
3

考虑到 aiohttp 是功能齐全的 Web 框架,我建议使用更轻量级的东西,例如支持异步请求的httpx ( https://www.python-httpx.org/ )。它具有与请求几乎相同的 api:

>>> async with httpx.AsyncClient() as client:
...     r = await client.get('https://www.example.com/')
...
>>> r
<Response [200 OK]>
于 2021-10-01T17:16:47.830 回答
2

免责声明:Following code creates different threads for each function.

这可能对某些情况有用,因为它更易于使用。但是要知道它不是异步的,而是使用多个线程产生异步的错觉,即使装饰器建议这样做。

要使任何函数非阻塞,只需复制装饰器并使用回调函数作为参数装饰任何函数。回调函数将接收函数返回的数据。

import asyncio
import requests


def run_async(callback):
    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return asyncio.get_event_loop().run_in_executor(None, __exec)

        return wrapper

    return inner


def _callback(*args):
    print(args)


# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
    return requests.get(url)


get("https://google.com")
print("Non blocking code ran !!")
于 2020-12-28T16:20:53.957 回答