每当输入product_id时,我的代码都会使用API创建一个订单。然后,它在定时间隔循环中检查订单是否已成功创建。我肯定没有正确使用asyncio,我希望有人能提供一些建议,或者甚至asyncio是不是适合这项工作的工具?
我在网上查看了文档和示例,但发现很难理解,很可能是因为我还在学习如何编码(初学者程序员w/ 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'))
如果不使用asyncio,一次只能对一个订单执行create+check。我希望代码能够为许多不同的订单同时和异步create+check。
当我尝试两个不同的产品I进行测试时,它给出了以下内容,但没有完成功能。
<coroutine object create_order at 0x7f657b4d6448>
>create_order('ID1234ABCD')
__main__:1: RuntimeWarning: coroutine 'create_order' was never awaited
<coroutine object create_order at 0x7f657b4d6748>
发布于 2019-02-14 17:39:21
在异步代码中使用阻塞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')
https://stackoverflow.com/questions/54686404
复制相似问题