python异步调用
A synchronous program is executed one step at a time. Even with conditional branching, loops and function calls, you can still think about the code in terms of taking one execution step at a time. When each step is complete, the program moves on to the next one.
同步程序一次执行一次。 即使有条件分支,循环和函数调用,您仍可以一次执行一个步骤来考虑代码。 完成每个步骤后,程序将继续进行下一个步骤。
An asynchronous program behaves differently. It still takes one execution step at a time. The difference is that the system may not wait for an execution step to be completed before moving on to the next one.
异步程序的行为有所不同。 一次仍然需要执行一个步骤。 不同之处在于,系统在继续执行下一个步骤之前可能不会等待执行步骤完成。
Although here we will implement asynchronous program that will execute 15 different instance parallelly rather than waiting for every instance to be completed.
尽管这里我们将实现异步程序,该程序将并行执行15个不同的实例,而不是等待每个实例完成。
Let’s jump to the implementation.
让我们跳到实现。
First, we will see how synchronous program reacts
首先,我们将了解同步程序的React
import requests from timeit import default_timer def request(session): url = "https://jsonplaceholder.typicode.com/photos" with session.get(url) as response: data = response.text if response.status_code != 200: print("FAILURE::{0}".format(url)) return data def start_sync_process(): with requests.session() as session: print("{0:<30} {1:>20}".format("No", "Completed at")) start_time = default_timer() for i in range(15): request(session) elapsed_time = default_timer() - start_time completed_at = "{:5.2f}s".format(elapsed_time) print("{0:<30} {1:>20}".format(i, completed_at)) if __name__ == "__main__": start_sync_process() Sync Program Output 同步程序输出Here we are calling a API 15 times one by one . One API call starts only after previous API call finishes. If you look at output, it takes 16.67 secs to complete 15 API calls. This is synchronous approach where next process starts when previous process ends. This type approach sometime costs heavy in real time project.
在这里,我们一一调用API 15次。 仅在先前的API调用完成后才开始一个API调用。 如果查看输出,则需要16.67秒才能完成15个API调用。 这是同步方法,其中上一个过程结束时下一个过程开始。 这种类型的方法有时会在实时项目中付出沉重的代价。
Now same we will implement same using async approach where we will make 15 API calls parallelly.
现在,我们将使用异步方法来实现相同的方法,其中我们将并行进行15个API调用。
import requests import asyncio from timeit import default_timer from concurrent.futures import ThreadPoolExecutor START_TIME = default_timer() def request(session, i): url = "https://jsonplaceholder.typicode.com/photos" with session.get(url) as response: data = response.text if response.status_code != 200: print("FAILURE::{0}".format(url)) elapsed_time = default_timer() - START_TIME completed_at = "{:5.2f}s".format(elapsed_time) print("{0:<30} {1:>20}".format(i, completed_at)) return data async def start_async_process(): print("{0:<30} {1:>20}".format("No", "Completed at")) with ThreadPoolExecutor(max_workers=10) as executor: with requests.Session() as session: loop = asyncio.get_event_loop() START_TIME = default_timer() tasks = [ loop.run_in_executor( executor, request, *(session,i) ) for i in range(15) ] for response in await asyncio.gather(*tasks): pass if __name__ == "__main__": loop = asyncio.get_event_loop() future = asyncio.ensure_future(start_async_process()) loop.run_until_complete(future) Async ProgramOutput 异步程序输出The max time taken to complete 2.45 secs.
完成2.45秒所需的最长时间。
The main advantage of using parallel execution is that code runs more efficiently and saves time.
使用并行执行的主要优点是代码可以更高效地运行并节省时间。
This is it. If you are having any doubts, have a comment below
就是这个。 如果您有任何疑问,请在下面发表评论
Check GitHub Repo for source code
检查GitHub Repo以获取源代码
Full Stack Developer, Code Quotient | Tech Writer and Social Media Handler at BlogMarch
全栈开发人员,代码商| BlogMarch的技术作家和社交媒体处理程序
Find me on Linkedin 😃 and Github 😅
在Linkedin和Github上找到我
翻译自: https://medium.com/@sankhadip/parallel-asynchronous-api-call-in-python-f6aa663206c6
python异步调用
相关资源:四史答题软件安装包exe