
import requests
import traceback
import os

headers = {
    # 'Host': 'jzsc.mohurd.gov.cn',
    # 'Referer': 'http://jzsc.mohurd.gov.cn/data/company',
    # 'accessToken':'jkFXxgu9TcpocIyCKmJ+tfpxe/45B9dbWMUXhdY7vLWEBMapxpV5A4nnWpZ/I6DrhpUUKvcMtoMqfGfwdLCb8g==',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
def download(_url,file_pname,timeout=20,chunk_size=1024*4,max_size=300*1024*1024):
    try:

        # _res = requests.session().get(_url,stream=True,headers=headers,timeout=timeout)
        # if _res.status_code==200:
        #     return True,_res.content
        # else:
        #     return False,""

        response_data_file = requests.get(_url, stream=True,headers=headers,timeout=timeout)
        if response_data_file.status_code==200:
            total_chunk = 0
            with open(file_pname, 'wb') as f:

                for chunk in response_data_file.iter_content(chunk_size=chunk_size):
                    if chunk:
                        total_chunk+= chunk_size
                        if total_chunk>max_size:
                            break
                        f.write(chunk)
            if total_chunk>max_size:
                if os.path.exists(file_pname):
                    os.remove(file_pname)
            return True,""
        else:
            return False,""

    except Exception as e:
        traceback.print_exc()
        return False,""

if __name__=="__main__":
    print(download("http://www.e-jy.com.cn/ejyzx/eWebEditor/uploadfile/20200916170453409002.xlsx","1.fl"))