request---文件的下載


1.按流得方式下載

2.下載好以后,會放在一個文件中

'''
響應體內容工作流:
默認情況下,當你進行網絡請求后,響應體會立即被下載。你可以通過 stream 參數覆蓋這個行為,推遲下載響應體直到訪問
Response.content 屬性:
r=requests.get(request_url,stream=True)
此時僅有響應頭被下載下來了,連接保持打開狀態,因此允許我們根據條件獲取內容:
if int(r.headers['content-length])<TOO_Long:
content=r.content
你可以進一步使用 Response.iter_content 和 Response.iter_lines 方法來控制工作流,或者以 Response.raw 從底
層 urllib3 的 urllib3.HTTPResponse <urllib3.response.HTTPResponse 讀取未解碼的相應體
如果你在請求中把 stream 設為 True,Requests 無法將連接釋放回連接池,除非你 消耗了所有的數據,或者調用了
Response.close。 這樣會帶來連接效率低下的問題。如果你發現你在使用 stream=True 的同時還在部分讀取請求的
body(或者完全沒有讀取 body),那么你就應該考慮使用 with 語句發送請求,這樣可以保證請求一定會被關閉:
with 接口案例.get('http://httpbin.org/get',stream=True) as r:
#再此處處理響應
'''


import requests
import shutil

def headers():
headers={"Content-Type":"application/vnd.ms-excel; charset=utf8"}

def login():
headers={
'Content-Type':'application/json; charset=UTF-8',
'Parkingwang-Client-Source':'ParkingWangAPIClientWeb'}
data={"username":"999333","mall_id":11,"password":"91b4d142823f7d20c5f08df69122de43f35f057a988d9619f6d3138485c9a203"}
r=requests.post(url='http://154.90.40.52:9094/v4/login',
json=data,
headers=headers)
return r.json()['data']['token']



def doanload_file(doanload_path):
r=requests.get(
url='http://154.90.40.52:9094/v4/download?per_page=10&type=&ex_type=&vpl=&page=1&stime=1522512000&etime=1523589565&memo1=&memo2=&memo3=&_=0.034775238593485414&token={0}&down=issue'.format(
login()),
headers=headers(), stream=True)
if r.status_code==200:
with open(doanload_path,'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
return

def doanload_file_raw(doanload_path):
r=requests.get(
url='http://154.90.40.52:9094/v4/download?per_page=10&type=&ex_type=&vpl=&page=1&stime=1522512000&etime=1523589565&memo1=&memo2=&memo3=&_=0.034775238593485414&token={0}&down=issue'.format(
login()),
headers=headers(), stream=True)
if r.status_code==200:
with open(doanload_path,'wb') as f:
r.raw.decode_content=True
shutil.copyfileobj(r.raw,f)
return

doanload_file_raw('c:/ecp.xlsx')




免責聲明!

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



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