zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    zip
    sublime 3 注册码
    css3 文本控制自动换行
    ST3 package control
    cf1139D-Steps to One
    2019-2020 ACM-ICPC, Asia Xuzhou Regional Contest
    2018-2019 ACM-ICPC, Asia Jiaozuo Regional Contest
    Tree
    B
    多源对多源最短路
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/11407709.html
Copyright © 2011-2022 走看看