• requests--文件上传,文件下载


    文件上传

    在做接口自动化的时候,有时需要上传文件,比如更改头像等等,在request里,通过files参数来上传

    import requests
    
    base_url = 'http://httpbin.org'
    file = {'file': open(r'E:0.jpg', 'rb')}
    r = requests.post(base_url + '/post', files=file)
    print(r.text)

    文件下载

    第一种方式
    import requests
    
    
    def dowload_file(file_path):
        headers = {"Referer": "https://xx315.xx315.nex"}
        cookie = {"Cookie": "ASP.NET_SessionId=bij"}
        
        r = requests.get(url='https://xx315.xx315',
                         cookies=cookie,
                         headers=headers,
                         stream=True)
        
        if r.status_code == 200:
            with open(file_path, 'wb') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    f.write(chunk)
    
    
    dowload_file('F:\123.xlsx')

    注意:

    文件如果不存在,会在当前目录下生成一个文件,有内容会清空在写入

    第二种方式
    import requests
    import shutil
    
    
    def download_file_raw(file_path):
        url = 'https://xx315.xx315.net/Ashx/Export'
        cookie = {"Cookie": 'ASP.NET_SessionId=sjl8'}
        r = requests.get(url=url,
                         cookies=cookie,
                         stream=True
                         )
    
        if r.status_code == 200:
            with open(file_path, 'wb') as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)
    
    
    download_file_raw('F:\123.xlsx')
  • 相关阅读:
    Python介绍
    产品经理知识体系之产品运营
    go rabbitmq延时队列
    docker安装PHP7.2及扩展
    关于js初始化对象的时间点的笔记
    gorm学习随笔
    Ubuntu18.04 安装PHP7.3
    PHP 冒泡、选择、插入排序
    MySQL 间隙锁的一些个人理解
    小程序插件 wx.navigateTo路由url设置
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/11407709.html
Copyright © 2020-2023  润新知