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

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

import asyncio
import requests
import json
import time
from datetime import datetime

async 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 asyncio
import requests
import json
import time
import uuid
from datetime import datetime

loop = 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

https://ithelp.ithome.com.tw/upload/images/20210905/201414148w6AuRNiv0.png

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


<<:  新新新手阅读 Angular 文件 - Day02

>>:  Golang 安装

[经典回顾]网路异常疑机房失火,老板:「不是有防火墙?」

资料来源: 为什麽没有「防火墙」? 火灾袭「是方电讯」!某天然呆老板:不是有防火墙吗? 内湖机房失...

Day 27 - 到客户端执行弱点扫瞄并修复的心得分享 第十四天

弱点修补专案已进行第14天了,中风险等级也快要全修补完了。 今天修补了以下弱点。 弱点名称: SSH...

英雄列表范例:载入资料

接下来我要用一个小应用来介绍基本的 CRUD 实作:复仇者英雄列表。它的功能如下: 新增英雄到列表中...

Transactions (5-2) - Serializability Isolation - SSI & Summary

续 Day 6。 强列建议阅读本文之前要先去看 Day 4 - Snapshot Isolatio...

[Day16] THM Tomghost

网址 : https://tryhackme.com/room/tomghost IP : 10....