Python 回撥函式實現非同步處理
阿新 • • 發佈:2020-12-07
說到非同步處理大家應該會聯想到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自動化測試等,微信搜尋公眾號:“無量測試之道”,或掃描下方二維碼:
新增關注,讓我們一起共同成長!