【发布时间】: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