python - 使用 Requests 库通过 Python 3.7 发出异步请求

标签 python python-3.x python-requests grequests

我需要制作 asynchronous requests使用请求库。在 Python 3.7 中,如果我尝试 from requests import async,我会得到 SyntaxError: invalid syntax

async 变成了 reserved with in Python 3.7 .我该如何解决这种情况?

最佳答案

负责请求库的 Lukasa 说:

At the current time there are no plans to support async and await. This is not because they aren't a good idea: they are. It's because to use them requires quite substantial code changes. Right now requests is a purely synchronous library that, at the bottom of its stack, uses httplib to send and receive data. We cannot move to an async model unless we replace httplib. The best we could do is provide a shorthand to run a request in a thread, but asyncio already has just such a shorthand, so I don't believe it would be valuable. Right now I am quietly looking at whether we can rewrite requests to work just as well in a synchronous environment as in an async one. However, the reality is that doing so will be a lot of work, involving rewriting a lot of our stack, and may not happen for many years, if ever.

不过不用担心 aiohttp 与请求非常相似。

这是一个例子。

import aiohttp
import asyncio

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

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://python.org')
        print(html)

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

关于python - 使用 Requests 库通过 Python 3.7 发出异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674751/

相关文章:

python - Statsmodels 混合线性模型预测

python - 物理卸载 Python 3.4 以使 pip3 将 "requests"包安装到 Python 3.5,如何解决随之而来的困惑?

python - 使用 python requests 模块登录基于 WordPress 的网站

python - json.dump() 在 Windows 和 Linux 上的不同行为

python - 类型是否在 python 中创建类 'Object'

python - 在 block 样式 yaml 文件 (ruamel.yaml) 中将来自 Python 的列表显示为流样式

python - 3D绘图: smooth plot on x axis

python - 如何通过Python中的pyautogui模块使用预定义的窗口(x,y)位置打开外部应用程序?

python - 如何使用 pandas 更改列值和排序?

python - 亚马逊文本提取我找不到 trp 模块