zoukankan      html  css  js  c++  java
  • requests通过接口下载文件

    利用requsts请求接口下载文件的操作

    测试接口如图:

    fiddler抓包信息如下:请求头里面需要传递登录成功的token,才能去访问excel导出的接口。

    思路就是先登录获取token,再去请求excel导出接口:

    import requests
    
    
    def login():
        login_url = 'https://gateway-boss-test.bgyfw.com/erp/boss/users/login'
        json = {"password":"123456",
                "loginName":"admin"}
        headers = {"Content-Type": "application/json",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
                   }
        res = requests.post(login_url,json=json,headers=headers)
        # print(res.status_code)
        login_token = res.json()['data']['token']
        return login_token
    
    def download_file():
        download_url = 'https://gateway-boss-test.bgyfw.com/rc/boss-app-fees/estate/cognizance/exportRoomExcel'
    
        headers = {
            "Content-Type": "application/json",
            "Access-Token": login()
        }
        json = {"commId":"","regionId":"","roomSnum":"","roomIsLock":"","roomState":"","regionName":"","chargePro":"","roomId":"","roomSign":""}
        r = requests.post(url=download_url,json=json,headers=headers,stream=False)
        print(r.status_code)
        # print(r.encoding)
        # encoding='utf-8'
        print(r.content.decode('GBK','ignore'))
        with open(r'E:\new.xls','wb') as f:
            if r.status_code==200:
                for chunk in r.iter_content(chunk_size=1):   # todo iter_content循环读取信息写入,chunk_size设置文件大小
                    f.write(chunk)
    if __name__ == '__main__':
        download_file()

    requests中stream参数的作用:

    iter_content循环读取文件内容写入到excel里面去:

    运行结果如下:

    打开excel如下:

    下面再来看我自己本地写的一个下载接口:

    页面如图,根据传递的图片名称,下载文件:

    抓包信息如图:

    前端html页面如图,通过filename参数传递文件名到后端,接口先判断文件名格式是否正常,在判断文件是否存在:

    通过request请求接口下载图片:

    import requests
    
    def download_picture():
        url = 'http://127.0.0.1:8000/download/'
        data = {"filename":500}
        r = requests.post(url,data=data)
        print(r.status_code)
        print(r.text)
        if r.status_code == 200:
            if r.text:   # TODO 判断文件内容是否为空
                with open(r'E:\new.png', 'wb') as f:
                        for chunk in r.iter_content(chunk_size=1):  # todo iter_content循环读取信息写入,chunk_size设置文件大小
                            f.write(chunk)
            else:
                print("文件为空")
    
    download_picture()

    运行之后如图:

    E盘下载的图片:

  • 相关阅读:
    构建之法阅读笔记03
    构建之法阅读笔记02
    构建之法阅读笔记01
    人月神话阅读笔记03
    人月神话阅读笔记02
    人月神话阅读笔记01
    关于APP“跑跑”
    软件设计模式24
    软件构造9
    软件构造8
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/12623954.html
Copyright © 2011-2022 走看看