@@ -159,6 +159,42 @@ def performance(self):
159159 print ("酷炫滑板" )
160160
161161
162+ # 回调在异步中的应用
163+ # =======================================================================================================================
164+ import requests
165+ # 引入Http请求模块
166+ from threading import Thread
167+ # 引入线程模块
168+
169+ class DownloadThread (Thread ):
170+ """下载文件的线程"""
171+
172+ # 每次写文件的缓冲大小
173+ CHUNK_SIZE = 1024 * 512
174+
175+ def __init__ (self , fileName , url , savePath , callBackProgerss , callBackFinished ):
176+ super ().__init__ ()
177+ self .__fileName = fileName
178+ self .__url = url
179+ self .__savePath = savePath
180+ self .__callbackProgress = callBackProgerss
181+ self .__callBackFionished = callBackFinished
182+
183+ def run (self ):
184+ readSize = 0
185+ r = requests .get (self .__url , stream = True )
186+ totalSize = int (r .headers .get ('Content-Length' ))
187+ print ("[下载%s] 文件大小:%d" % (self .__fileName , totalSize ))
188+ with open (self .__savePath , "wb" ) as file :
189+ for chunk in r .iter_content (chunk_size = self .CHUNK_SIZE ):
190+ if chunk :
191+ file .write (chunk )
192+ readSize += self .CHUNK_SIZE
193+ self .__callbackProgress (self .__fileName , readSize , totalSize )
194+ self .__callBackFionished (self .__fileName )
195+
196+
197+
162198# Test
163199#=======================================================================================================================
164200
@@ -201,7 +237,36 @@ def testFilter():
201237 print ("所有的偶数:" , list1 )
202238 print ("大于10的数:" , list2 )
203239
240+
241+
242+
243+ def testDownload ():
244+ def downloadProgress (fileName , readSize , totalSize ):
245+ """定义下载进度的回调函数"""
246+ percent = (readSize / totalSize ) * 100
247+ print ("[下载%s] 下载进度:%.2f%%" % (fileName , percent ))
248+
249+ def downloadFinished (fileName ):
250+ """定义下载完成后的回调函数"""
251+ print ("[下载%s] 文件下载完成!" % fileName )
252+
253+ print ("开始下载TestForDownload1.pdf......" )
254+ downloadUrl1 = "http://pe9hg91q8.bkt.clouddn.com/TestForDownload1.pdf"
255+ download1 = DownloadThread ("TestForDownload1" , downloadUrl1 , "./download/TestForDownload1.pdf" , downloadProgress ,
256+ downloadFinished )
257+ download1 .start ()
258+ print ("开始下载TestForDownload2.zip......" )
259+ downloadUrl2 = "http://pe9hg91q8.bkt.clouddn.com/TestForDownload2.zip"
260+ download2 = DownloadThread ("TestForDownload2" , downloadUrl2 , "./download/TestForDownload2.zip" , downloadProgress ,
261+ downloadFinished )
262+ download2 .start ()
263+ print ("执行其它的任务......" )
264+
265+
204266# testSkill()
205- testStrategySkill ()
267+ # testStrategySkill()
206268# testCallback()
207- # testFilter()
269+ # testFilter()
270+
271+
272+ testDownload ()
0 commit comments