zoukankan      html  css  js  c++  java
  • requests库入门12-文件上传和下载

    因为找不到可以演示上传接口,所以只能纯代码了

    文件上传

    上传文件是在请求中使用files参数,files需要指向一个dict,然后dict里面的键是接口中对应文件名的字段,而值就是打开这个文件读取到内存的内容

    以上图中这个字段举例

    path = 文件路径

    file = {'templateFile':open(path.'rb')}

    一般上传文件是post请求

    r = requests.post(url,files = file)

    文件下载

    默认情况下,使用requests库在进行请求,响应体是会被立即下载的,所以需要使用stream这个参数覆盖这个行为,然后content来下载这个被推迟的响应体,如果不使用stream参数,是下载不到东西,肯定是空的

    r = requests.get(url,stream = True)
    
    path = 文件保存路径
    
    with open(path,'wb) as f:
    
        f.write(r.content)

    我们现在以下载图片来做个示例,就以requests最新的logo

    对着requests官方中文api文档左边的logo右键,复制图片地址

    地址是这个:http://docs.python-requests.org/zh_CN/latest/_static/requests-sidebar.png

    import requests
    url = 'http://docs.python-requests.org/zh_CN/latest/_static/requests-sidebar.png'
    path = 'C:/Users/ms/Downloads/test.jpg'
    r = requests.get(url,stream = True)
    print(r.status_code)
    with open(path,'wb') as f:
        f.write(r.content)

    path是存放路径,请换成自己想要存放的路径

    可以看到文件夹中有代码中下载下来的test.jpg

    打开看下,确实是requests的logo

  • 相关阅读:
    uva 12426 Counting Triangles 计算几何
    poj 1195 Mobile phones 二维树状数组
    poj 1039 Pipe 计算几何
    poj 3580 SuperMemo 数据结构
    poj 1031 Fence 计算几何
    ArcEngine 无法嵌入互操作类型
    IDL 读取显示HDF文件
    Sql Server 2005 Com+ 警告处理办法
    C# 自定义控件开发
    ArcEngine 获取HDF文件中的子文件
  • 原文地址:https://www.cnblogs.com/myal/p/9337380.html
Copyright © 2011-2022 走看看