[英]Python asynchronous call separate functions
I have 4 functions as follows, 3 of them call an external apis to fetch random data:我有如下 4 个函数,其中 3 个调用外部 api 来获取随机数据:
def get_external_data(zip_code, info_code):
data_url = MY_ENDPOINT_1.format(zip_code)
data_response = requests.request(
'GET',
url=data_url,
headers={
'content-Type': 'application/json',
'info-code': info_code
}
)
return data_response
def get_info(info_code):
info_url = INFO_URL.format(info_code)
info_response = requests.request(
'GET',
url=info_url,
headers={
'content-Type': 'application/json',
'info-code': info_code
}
)
return info_response
def get_zip(zip_code):
zip_url = zip_URL.format(zip_code)
zip_response = requests.request(
'GET',
url=zip_url,
headers={
'content-Type': 'application/json',
'zip-code': zip_code
}
)
return zip_response
def get_all_data(info_cd, zip_code):
data_response = get_external_data(zip_code, info_cd)
info_response = get_info(info_cd)
zip_response = get_zip(zip_code)
return data_response, info_response, zip_response
I am trying to achieve 3 asynchronous calls by calling the 3 data functions using concurrent.futures
in the get_all_data()
function.我试图通过使用
get_all_data()
function 中的concurrent.futures
调用 3 个数据函数来实现 3 个异步调用。 From the docs i understand that we can thread one function with a list of inputs as follows:从文档中我了解到,我们可以使用如下输入列表对一个 function 进行线程化:
resp_list = list()
# Asynchronous
with ThreadPoolExecutor(max_workers=3) as executor:
thread_responses = executor.map(self.get_info, info_list)
for x in thread_responses:
resp_list.append(x)
But how will i achieve 3 threads in this particular situation with 3 different functions with different inputs?但是,在这种特殊情况下,我将如何使用 3 个不同的函数和不同的输入来实现 3 个线程?
You can make each call in its own thread using executor.submit
, like this:您可以使用
executor.submit
在自己的线程中进行每个调用,如下所示:
with ThreadPoolExecutor(max_workers=3) as executor:
data_future = executor.submit(get_external_data, zip_code, info_cd)
info_future = executor.submit(get_info, info_cd)
zip_future = executor.submit(get_zip, zip_code)
# and then collect results
results = [
f.result()
for f in (data_future, info_future, zip_future)
]
See related docs: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.submit请参阅相关文档: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.submit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.