如何在Python中进行简单的异步调用?

时间:2016-09-11 19:47:52

标签: python asynchronous

我在python中有一个异步函数调用,如下所示:

response = client.invoke(
    FunctionName='CreateCatSpot',
    Payload="Meow"
)

我将重复执行此调用,并且每当我想要使用async函数返回的响应变量执行某些操作时它将返回。这似乎是异步编程的一个非常简单的例子,但我不能在我的生活中找到一种在python中执行此操作的简单方法。我该怎么做?

2 个答案:

答案 0 :(得分:1)

import threading

def foo(client, function_name, payload):
    response = client.invoke(FunctioName=function_name, Payload=payload)
    # do something with the response

client = SomeClient()
values = [{"FunctionName": "...", "Payload": "..."}, {"FunctioName": "...", "Payload": "..."}, ...]
threads = [threading.Thread(target=foo, args=(client, v["FunctionName"], v["Payload"])) for v in values]
for t in threads:
    t.start()    # this will run foo() asynchronously

答案 1 :(得分:0)

如果您不介意使用线程在后台运行,而不是真正的异步消息循环,请查看concurrent.futures模块。它是Python3的标准,但是Python 2的后端可用。

您可以向在后台运行它们的执行程序提交调用。您可以稍后自己处理结果,也可以将结果回调绑定到调用完成后为您处理结果的结果。一些示例代码:

import concurrent.futures as futures
import time

def handle_result(future):
    print("Result:", future.result())


def slow_function(argument):
    time.sleep(2)
    return argument


with futures.ThreadPoolExecutor() as executor:
    async1 = executor.submit(slow_function, 1)
    async1.add_done_callback(handle_result)
    async2 = executor.submit(slow_function, 2)
    async2.add_done_callback(handle_result)
    async3 = executor.submit(slow_function, 3)
    async3.add_done_callback(handle_result)

    time.sleep(3)