python實現斷點續傳下載文件


最近的任務里有一個功能是要我從日志服務器實時跟新日志到本地,日志在不斷新增內容就需要我隔一段時間從上次下載的位置繼續下載,並寫入本地文件上次寫完的位置后面。

 

[python]  view plain  copy
 
  1. headers = {'Range': 'bytes=%d-' % local_file_dict.get(packet_path+k)}  
  2. web_log = requests.get(packet_web_path+k, stream=True, headers=headers)  
  3. with open(packet_path+k, 'ab') as local_file:  
  4.     for chunk in web_log.iter_content(chunk_size=1024):  
  5.         if chunk:  
  6.             local_file.write(chunk)  
  7.             local_file.flush()  


這里用的是requests.get()和他的一些參數

 

 

[python]  view plain  copy
 
  1. requests.get(url, stream=True, headers=headers)  

要實現斷點續傳,get()的stream參數要設為True在遠程打開的是一個流,而headers里放的是續傳的一些參數,這里的

 

 

[python]  view plain  copy
 
  1. headers = {'Range': 'bytes=%d-' % local_file_size}  

就是獲得本地文件的大小作為續傳的起點,還有就是按bytes

 

然后以

 

[python]  view plain  copy
 
  1. iter_content(chunk_size=xxx)  

 

的方式逐chunk_size地遍歷數據,並寫入local_file

 

 

[python]  view plain  copy
 
  1. local_file.flush()  

 

刷新也很重要,實時保證一點點的寫入。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM