說到異步處理大家應該會聯想到Ajax 處理,那我們先來說說什么是Ajax 請求。
Ajax 就相當於是模擬了一個信息發送請求,你可以在很多網站上注冊的時候會發現,比如用戶名輸入“123”,那么它可能會提示你該用戶已經存在,而給你的感覺是頁面並沒刷新,也就是並沒有提交表單,而用戶名又是存放在數據庫內的,也就是說要查詢用戶名是否存在,就必須得發送表單的里的用戶名,然后再在數據庫中去查詢。
而這個過程就是用了Ajax 來處理的,用戶輸入用戶名,當表單的焦點發生變化的時候,則會觸發Ajax,然后Ajax 發送一個GET或者POST請求給服務器,服務器就會處理傳遞過來的數據!
今天給大家分享的是在Python 里面通過回調函數來實現異步的處理。
示例代碼如下所示:
import threading import time import datetime #第一個請求 def request_1(): print("the request 1 is start") io(callback) print("the request 1 is end") #第二個請求 def request_2(): print("the request 2 is start") time.sleep(2) print("the request 2 is end") #獲取數據請求類的操作,如:從db讀取數據,循環耗時,調用其他api等 def io(callback): def run(call): print("the run is start") time.sleep(5) print("the run is end") conn_db=[x for x in range(10000)] #模擬從db獲取數據 call(conn_db) # 這里是啟動一個線程去處理這個io操作,不用阻塞程序的處理 threading.Thread(target=run,args=(callback,)).start() #回調函數 def callback(data): print("the callback is start") print("the response of callback is:",data) print("the callback is end") if __name__ == '__main__': start_time=datetime.datetime.now() request_1() request_2() end_time=datetime.datetime.now() #這里是在統計總耗時,從打印的結果可以看到是異步處理的。 print("the spend of total time is:",(end_time-start_time).seconds)
輸出內容如下:
the request 1 is start the run is start the request 1 is end the request 2 is start the request 2 is end the spend of total time is: 2 the run is end the callback is start the response of callback is:[0, 1,...] the callback is end Process finished with exit code 0
總結:
異常的處理就是在我們需要等待一個io 耗時處理時,可以不用排隊等待而去做其他的可以處理的事情,這樣就提高了系統的處理效率,這對於一個系統來說是非常重要的。
歡迎關注【無量測試之道】公眾號,回復【領取資源】,
Python編程學習資源干貨、
Python+Appium框架APP的UI自動化、
Python+Selenium框架Web的UI自動化、
Python+Unittest框架API自動化、
資源和代碼 免費送啦~
文章下方有公眾號二維碼,可直接微信掃一掃關注即可。
備注:我的個人公眾號已正式開通,致力於測試技術的分享,包含:大數據測試、功能測試,測試開發,API接口自動化、測試運維、UI自動化測試等,微信搜索公眾號:“無量測試之道”,或掃描下方二維碼:
添加關注,讓我們一起共同成長!