【问题标题】:How to make multiple REST calls asynchronous in python3如何在python3中使多个REST调用异步
【发布时间】:2022-10-09 05:10:01
【问题描述】:

我有以下代码可以进行多个 REST 调用。基本上我有一个字典,其中键是字符串,值是 JSON 日期,我需要将其用作有效负载以传递给 REST API POST 方法。

目前,字典包含 10 个条目,所以我需要进行 10 次 REST 调用。

目前,我已经在 python3 中使用 requests 包实现了,它本质上是同步的。因此,在 1 次 REST 调用之后,它会等待其响应,同样,对于 10 次 REST 调用,它会等待 10 次来自 API 的响应。

def createCategories(BACKEND_URL, token, category):
    url = os.path.join(BACKEND_URL, 'api/v1/category-creation')

    category_dict = read_payloads(category)

    headers = {
        "token": f'{token}',
        "Content-Type": "application/json",
        "accept": "application/json"
    }

    for name, category_payload in category_dict.items():
        json_payload = json.dumps(category_payload)
        response = requests.request("POST", url, headers=headers, data=json_payload)
        ##########################
        ## Load as string and parsing
        response_data = json.loads(response.text)
        print(response_data)

        category_id = response_data['id']
        message = 'The entity with id: ' + str(category_id) + ' is created successfully. '
        logging.info(message)

    return "categories created successfully."

我读到我们需要使用 asyncio 来使这些异步。我需要进行哪些代码更改?

【问题讨论】:

  • 请问有什么意见吗?

标签: python-3.x python-requests python-asyncio aiohttp


【解决方案1】:

您可以继续使用requests 库。您需要使用threadingconcurrent.futures 模块同时发出多个请求。

另一种选择是使用一些async 库,如aiohttp 或其他一些库。

import requests

from threading import current_thread
from concurrent.futures import ThreadPoolExecutor, Future
from time import sleep, monotonic

URL = "https://api.github.com/events"


def make_request(url: str) -> int:
    r = requests.get(url)
    sleep(2.0)  # wait n seconds
    return r.status_code


def done_callback(fut: Future):
    if fut.exception():
        res = fut.exception()
        print(f"{current_thread().name}. Error: {res}")
    elif fut.cancelled():
        print(f"Task was canceled")
    else:
        print(f"{current_thread().name}. Result: {fut.result()}")


if __name__ == '__main__':
    urls = [URL for i in range(20)]  # 20 tasks

    start = monotonic()

    with ThreadPoolExecutor(5) as pool:
        for i in urls:
            future_obj = pool.submit(make_request, i)
            future_obj.add_done_callback(done_callback)

    print(f"Time passed: {monotonic() - start}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多