【发布时间】:2019-04-18 11:46:53
【问题描述】:
所以我们的想法是收集 100 万个查询的响应并将它们存储在字典中。我希望它是异步的,因为 requests.post 每个查询需要 1 秒,我希望在等待响应时保持循环继续。经过一些研究,我有这样的东西。
async def get_response(id):
query_json = id2json_dict[id]
response = requests.post('some_url', json = query_json, verify=false)
return eval(response.text)
async def main(id_list):
for unique_id in id_list:
id2response_dict[unique_id] = get_response(unique_id)
我知道这不是异步的,如何在其中使用“await”使其真正异步?
【问题讨论】:
-
为此使用 locust.io。这比您自己构建整个 async/await 或基于 gevent 的解决方案要容易。
-
requests库不支持异步。对于异步 http,您可能需要查看 aiohttp。 -
你不能在异步代码中使用
requests,即使你把它放到executor中。因为线程可以更好地完成它。
标签: python asynchronous python-requests python-asyncio