[鱼刺-Python-1] asyncio 非同步呼叫POST Method方法

Python非同步需要使用到asyncio,简单测试如下

import asyncioimport requestsimport jsonimport timefrom datetime import datetimeasync def syncHello(delay):    print("Hello:",delay)    await asyncio.sleep(delay)    print("Bye:",delay)if __name__ == "__main__":    ts = [5,3,1    ]        now = lambda: time.time()    start = now()    tasks = [syncHello(i) for i in ts]    asyncio.run(asyncio.wait(tasks))    print('Total TIME:', now() - start)

代码执行后,在await时,就会转去执行其他task,然而实务上你直接用改成API呼叫是不会work的,因为呼叫API并没有使用到await,以至于没有效果(会卡住等待Response),所以这时候就要再多使用 loop.run_in_executor,让呼叫API时在等待Response时,转去继续执行其他task

话不多说,上代码!
方法如下:

import asyncioimport requestsimport jsonimport timeimport uuidfrom datetime import datetimeloop = asyncio.get_event_loop()async def doBuyBook(bookName):logkey = uuid.uuid4().hex[:6]print(f"[{logkey}] doBuyBook.start ==> {bookName}")req = {"BookName": bookName}#非同步执行r = await loop.run_in_executor(None, lambda: requests.post("http://127.0.0.1:8321/bookstore/buybook", json = req))response_data = json.loads(r.text)print(f"[{logkey}] response_data:{response_data}")print(f"[{logkey}] doBuyBook.end")if __name__ == "__main__":        bookNames = ["PYTHON_DEV","JAVA_DEV","GOLANG_DEV","C#_DEV"    ]        now = lambda: time.time()    start = now()        tasks = [loop.create_task(doBuyBook(i)) for i in bookNames]    loop.run_until_complete(asyncio.wait(tasks))        print('Total TIME: ', now() - start)

使用 get_event_loop 建立迴圈事件 loop,使用 run_in_executor 把呼叫API POST丢入线程池中执行,在await时,就会转去执行下一个task,当API回应时间较慢时,会明显看到打印出来的LOG,会先全部打印出,然后才会依序打印出API的Response

http://img2.58codes.com/2024/201414148w6AuRNiv0.png

大概就是这样,Cheer!! 测试用的API如何建立写在下一篇


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章