【问题标题】:RuntimeWarning: coroutine 'some_xyz_method' was never awaitedRuntimeWarning:从未等待协程“some_xyz_method”
【发布时间】:2021-01-13 05:48:23
【问题描述】:

在方法 1 中,我希望先执行 try 块,然后希望执行 call_ordercreate 方法,尝试使用 asyncio 但得到错误输出,如描述中所示,我该如何解决这个问题?

方法#1


@app.route("/slack/message_actions", methods=[ "POST" ])
def message_actions():

        if (payload[ "type" ] == "view_submission" and payload[ "view" ][ "callback_id" ] == "sthpush"):
            print("entered push")
            call_ordercreate(thread_ts, user_name)  **# Run this method after executing try block** 
            try:
                return jsonify(
                    {
                        "response_action": "push",
                        "view": orderwaitmessage,
                    }
                )
            except SlackApiError as e:
                code = e.response[ "error" ]
                return make_response(f"Failed to open a modal due to {code}", 200)

方法#2

async def call_ordercreate(thread_ts, user_name):
    await asyncio.sleep(4)
    url_list1 = CONST_ORDERCREATE_API  
    r = requests.get(url)

错误输出

C:/Users/PycharmProjects/iptautobot-events/newapp.py:263: RuntimeWarning: coroutine 'call_ordercreate' was never awaited
call_ordercreate(thread_ts, user_name)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

【问题讨论】:

    标签: python asynchronous flask


    【解决方案1】:

    这里的问题是你试图从一个正常的同步函数中调用一个异步函数。您应该使用asyncio.run 方法来运行该函数。这不会引起RuntimeWarning。所以您的代码将如下所示:

    @app.route("/slack/message_actions", methods=[ "POST" ])
    def message_actions():
    
            if (payload[ "type" ] == "view_submission" and payload[ "view" ][ "callback_id" ] == "sthpush"):
                print("entered push")
                asyncio.run(call_ordercreate(thread_ts, user_name))
                try:
                    return jsonify(
                        {
                            "response_action": "push",
                            "view": orderwaitmessage,
                        }
                    )
                except SlackApiError as e:
                    code = e.response[ "error" ]
                    return make_response(f"Failed to open a modal due to {code}", 200)
    

    但是,您似乎想在将响应返回给用户后运行call_ordercreate。恐怕这是不可能的,因为一旦您return,整个请求上下文就会被破坏。此外,flask(我假设它的 flask)是一个 WSGI 服务器,这意味着它以同步方式处理请求。这就是为什么使用asyncio.run 是调用异步函数的唯一方法。不足之处?它等待任务完成,这绝对不是你想要实现的。

    【讨论】:

    • 感谢您解释解决此问题的任何替代方法?
    猜你喜欢
    • 2018-10-26
    • 2021-10-22
    • 2019-12-15
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2020-10-10
    • 2022-01-20
    相关资源
    最近更新 更多