【问题标题】:Asynchronous python requests.post()异步python requests.post()
【发布时间】: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


【解决方案1】:

requests-async pacakge 为requests 提供异步支持...https://github.com/encode/requests-async

或者使用aiohttp

【讨论】:

    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2016-01-29
    • 2022-11-19
    • 1970-01-01
    • 2017-01-30
    • 2011-06-04
    相关资源
    最近更新 更多