zoukankan      html  css  js  c++  java
  • python-用requests库处理form-data格式的参数

    工作中,有一个上传图片的接口。逻辑是这样的,先通过cid获取token,再通过token来上传图片。

    获取token这些步骤先忽略,我们来看下上传图片的接口参数格式

    POST data:
    -----------------------------7d159c1302d0y0
    Content-Disposition: form-data; name="message"
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: 8bit
    
    {"delay_time":0,"attachments":[{"area_id":2,"expiretype":1,"form_field":"first_object","metadata":{"alarmtime":"1617068785","alarmtype":3,"cid": 753383264,"devicename":"测试","deviceserial":"68731188250","id":"687311882501519870247"},"url":""}],"body":{},"channel_id":0,"subject":""}
    -----------------------------7d159c1302d0y0
    Content-Disposition: form-data; name="first_object"; filename="pengyuyan.jpg"
    Content-Type: image/jpeg
    Content-Transfer-Encoding: binary
    
    <actual file content, not shown here>
    -----------------------------7d159c1302d0y0--

    从格式中,可以看到有file文件上传。看具体实现代码

    file_path = "C:\Users\admin\Desktop\images\peng1.jpg"
    
    data = {'message': '{"delay_time":0,"attachments":[{"area_id":2,"expiretype":1,"form_field":"first_object","metadata":{"alarmtime":"1617088512","alarmtype":3,"cid":753376406,"devicename":"测试","deviceserial":"68731188250","id":"687311882501519870247"},"url":""}],"body":{},"channel_id":0,"subject":"", "topic_id": 2}'}
    files={
      'first_object':('pengyuyan',open(file_path,'rb'),'image/jpeg')  
    }
    #first_object格式:'first_object':(随意指定文件名,目标文件,文件类型) 
    
    
    res = requests.post(url=url,files=files,data=data) 

    print(res.text)

    参数中,不是文件参数的我们放到data里面,文件格式的,提取请求头name的值作为字典的键,文件键值按照这种格式组织:{'first_object':(随意指定文件名,目标文件,文件类型) }

    每天进步一点点!
  • 相关阅读:
    HTML和XHTML知识总结
    理解margin-left:-100%
    git clean的用法
    vue路由传参的三种基本方式
    vertical-align属性
    纯CSS制作各种图形(多图预警)
    css伪元素:before和:after用法详解
    前端注册登录的业务流程
    Vue-cli 中为单独页面设置背景图片铺满全屏的方法
    vscode 开启对 webpack alias(文件别名) 引入的智能提示
  • 原文地址:https://www.cnblogs.com/qianjunjun/p/14597861.html
Copyright © 2011-2022 走看看