首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在while循环中使用Asyncio

如何在while循环中使用Asyncio
EN

Stack Overflow用户
提问于 2019-02-14 16:50:46
回答 1查看 1.4K关注 0票数 1

每当输入product_id时,我的代码都会使用API创建一个订单。然后,它在定时间隔循环中检查订单是否已成功创建。我肯定没有正确使用asyncio,我希望有人能提供一些建议,或者甚至asyncio是不是适合这项工作的工具?

我在网上查看了文档和示例,但发现很难理解,很可能是因为我还在学习如何编码(初学者程序员w/ Python 3.7.1)

代码语言:javascript
运行
复制
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进行测试时,它给出了以下内容,但没有完成功能。

代码语言:javascript
运行
复制
<coroutine object create_order at 0x7f657b4d6448>
>create_order('ID1234ABCD')
__main__:1: RuntimeWarning: coroutine 'create_order' was never awaited
<coroutine object create_order at 0x7f657b4d6748>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-14 17:39:21

在异步代码中使用阻塞requests库是不好的。您的程序将等待每个请求完成,并且在此期间不会执行任何操作。您可以改用async aiohttp library

你不能仅仅调用async函数并期望它被执行,它只会返回一个coroutine对象。你必须通过asyncio.run()将这个协程添加到事件循环中,就像你在代码中所做的那样:

代码语言:javascript
运行
复制
>>> asyncio.run(create_order('ID1234ABCD'))

或者如果你想同时运行多个协程:

代码语言:javascript
运行
复制
>>> asyncio.run(
    asyncio.wait([
        create_order('ID1234ABCD'),
        create_order('ID1234ABCD')
    ])
)

此外,如果你想从REPL中轻松地测试你的async函数,你可以使用IPython,它可以直接从REPL中运行异步函数(仅适用于7.0以上的版本)。

安装:

代码语言:javascript
运行
复制
pip3 install ipython

运行:

代码语言:javascript
运行
复制
ipython

现在你可以等待你的异步函数了:

代码语言:javascript
运行
复制
In [1]: await create_order('ID1234ABCD')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54686404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档