gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:57:36 25 4
gpt4 key购买 nike

我需要制作 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com