异步调用另一个函数,从不等待它在 Python 内完成

Calling another function asynchronously and never wait it to finish in Python

我正在开发一个聊天机器人,在回复用户之前,我会进行数据库调用以将聊天记录保存在 table 中。每次用户键入内容时都会执行此操作,这会增加响应时间。

所以为了减少响应时间,我们需要调用这个asynchronously

如何在 Python 3 中执行此操作?

我已经阅读了 asyncio 库的教程,但没有完全理解它,也无法理解如何让它工作。

另一种解决方法是使用排队系统,但这听起来有点矫枉过正。

示例:

request = get_request_from_chat
res = call_some_function_to_prepare_response()
save_data() # this will be call asynchronously
reply() # this should not wait save_data() to finish

欢迎提出任何建议。

使用 loop.create_task(some_async_function()) 到 运行 异步函数 "in the background"。例如, 展示了在简单的客户端-服务器通信的情况下如何做到这一点。

在您的情况下,伪代码如下所示:

request = await get_request_from_chat()
res = call_some_function_to_prepare_response()
loop = asyncio.get_event_loop()
loop.create_task(save_data()) # runs in the "background"
reply() # doesn't wait for save_data() to finish

当然,要实现这一点,程序必须是为 asyncio 编写的,并且 save_data 必须是协程。对于聊天服务器来说,这是一个很好的方法,所以我建议给 asyncio 一个机会。

因为你提到了

Another workaround is to use queuing system, but that sounds like an overkill.

我假设您对其他解决方案持开放态度,因此我将提出多线程方法:

from concurrent.futures import ThreadPoolExecutor
from time import sleep


def long_runnig_funciton(param1):
    print(param1)
    sleep(10)
    return "Complete"



with ThreadPoolExecutor(max_workers=10) as executor:
    future = executor.submit(long_runnig_funciton,["Param1"])


print(future.result(timeout=12))

步骤:

1) 您创建一个ThreadPoolExecutor并定义最大并发任务数。

2) 您提交一个带有所需参数的函数

3) 当您需要结果时,您在 submit() 的 return 值上调用 result()

请注意,如果在提交的函数中抛出异常,result() 可能会抛出异常

您还可以使用 future.done() which returns TrueFalse

检查您的通话结果是否准备就绪