每当输入product_id时,我的代码都会使用API创建一个订单。然后,它在定时间隔循环中检查是否成功创建了订单。我绝对不是正确地使用asyncio,并希望有人提供提示或什至asyncio是完成这项工作的正确工具?
我在线检查了文档和示例,但发现它很难理解,很可能是因为我仍在学习如何编码(使用Python 3.7.1的初学者)
import asyncio
import requests
import time
#creates order when a product id is entered
async def create_order(product_id):
url = "https://api.url.com/"
payload = """{\r\n \"any_other_field\": [\"any value\"]\r\n }\r\n}"""
headers = {
'cache-control': "no-cache",
}
response = requests.request("POST", url, data=payload, headers=headers)
result = response.json()
request_id = result['request_id']
result = asyncio.ensure_future(check_orderloop('request_id'))
return result
#loops and check the status of the order.
async def check_orderloop(request_id):
print("checking loop: " + request_id)
result = check_order(request_id)
while result["code"] == "processing request":
while time.time() % 120 == 0:
await asyncio.sleep(120)
result = check_order(request_id)
print('check_orderloop: ' + result["code"])
if result["code"] != "processing request":
if result["code"] == "order_status":
return result
else:
return result
#checks the status of the order with request_id
async def check_order(request_id):
print("checking order id: " + request_id)
url = "https://api.url.com/" + request_id
headers = {
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers)
result = response.json()
return result
asyncio.run(create_order('product_id'))
不带异步,它一次只能创建+检查一个订单。我希望代码能够同时异步创建和检查许多不同的订单。
当我尝试使用两个不同的产品ID进行测试时,它给出了以下内容,但没有完成功能。
<coroutine object create_order at 0x7f657b4d6448>
>create_order('ID1234ABCD')
__main__:1: RuntimeWarning: coroutine 'create_order' was never awaited
<coroutine object create_order at 0x7f657b4d6748>
答案 0 :(得分:1)
在异步代码中使用阻塞requests
库很不好。您的程序将等待每个请求完成,同时不会执行任何操作。您可以改用async aiohttp
library。
您不能只调用async
函数并期望它被执行,它只会返回一个coroutine
对象。您必须通过asyncio.run()
将此协程添加到事件循环中,方法与在代码中的操作相同:
>>> asyncio.run(create_order('ID1234ABCD'))
或者如果您想同时运行多个协程:
>>> asyncio.run(
asyncio.wait([
create_order('ID1234ABCD'),
create_order('ID1234ABCD')
])
)
如果您想方便地从REPL测试async
函数,则可以使用IPython,它可以直接从REPL运行异步函数(仅适用于7.0以上的版本)。
安装:
pip3 install ipython
运行:
ipython
现在您可以等待异步功能了:
In [1]: await create_order('ID1234ABCD')