[英]How to use Asyncio with while loop
每當輸入 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'))
沒有 asyncio,它一次只能創建+檢查一個訂單。 我希望代碼能夠同時和異步地創建+檢查許多不同的訂單。
當我通過嘗試兩個不同的產品 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>
在異步代碼中使用阻塞requests
庫是不好的。 您的程序將等待每個請求完成並且在此期間不會做任何事情。 您可以改用異步aiohttp
庫。
你不能只調用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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.