Python基于requests实现模拟上传文件


Posted in Python onApril 21, 2020

方法1:

1.安装requests_toolbelt依赖库

#代码实现
def upload(self):
    login_token = self.token.loadTokenList()
    for token in login_token:
      tempPassword_url = self.config['crm_test_api']+'/document/upload'
      tempPassword_data = self.data_to_str.strToDict('''title:1.png
      course_name_id:63
      course_id:1112
      desc:7
      doc_type:1
      is_public:1''',value_type='str')
      files={'file': ('1.png', open('C:\\Users\\Acer\\Pictures\\Screenshots\\1.png', 'rb'), 'image/png')}
      tempPassword_data.update(files)
      m = MultipartEncoder(
        fields=tempPassword_data
      )
      tempPassword_headers = {"Content-Type": m.content_type, "token": token}
      tempPassword_request = requests.post(url=tempPassword_url,data=m,headers=tempPassword_headers)
      print(tempPassword_request.content)

2.组装MultipartEncoder对象需要的参数:将tempPassword_data的字段合并至files

1.files参数介绍:

1.字典key对应file字段(我们系统是这样,具体结合前端实际的字段为准),如图

Python基于requests实现模拟上传文件

2.字典value里面的对象:

1.filename(服务器最终存储的文件名)

2.filepath(具体的文件路径,注意转义),文件是以二进制的形式进行传输的,所以这里传输时以二进制的形式打开文件并传输

3.content_type:具体结合前端实际的字段为准:一般可定义为: 文本(text)/图片(image)等[/code][code]

3.tempPassword_data:为文件上传时的附带参数

strToDict方法:自己手写的一个字符串转dict的方法

遇到的问题:

Python基于requests实现模拟上传文件

这个错误是说,int对象不能被编码,所以需要手动将int对象转换为str,所以我在此方法中定义了value_type这个参数,用于将字典中的所有value转换为str类型

#具体代码实现,仅供参考
def strToDict(str_in,value_type=None):
    # value_type:转换字典的value为指定的类型,未防止异常,目前仅支持str
    # '''将str转换为dict输出'''
    # '''将带有time关键字的参数放到字符串末尾'''
    # print(str_in)
    if str_in:
      match_str = ':'
      split_str = '\n'
      split_list = str_in.split(split_str)
      str_in_dict = {}
      for i in split_list:
        colon_str_index = i.find(match_str)
        if colon_str_index == -1:
          # '''处理firefox复制出来的参数'''
          match_str = '\t' or ' '
          colon_str_index = i.find(match_str)
        # '''去掉key、value的空格,key中的引号'''
        str_in_key = i[:colon_str_index].strip()
        str_in_key = str_in_key.replace('"','')
        str_in_key = str_in_key.replace("'",'')
        # 正则过滤无用key,只保留key第一位为字母数据获取[]_
        str_sign = re.search('[^a-zA-Z0-9\_\[\]+]', str_in_key[0])
        if str_sign is None:
          # 处理value中的空格与转义符
          str_in_value = i[colon_str_index + 1:].strip()
          str_in_value=str_in_value.replace('\\','')
          try:
            # 遇到是object类型的数据转换一下
            str_in_value=eval(str_in_value)
          except BaseException as error:
            str_in_value=str_in_value
          if value_type in ['str','string']:
            str_in_value=str(str_in_value)
          else:
            str_in_value=str_in_value
          str_in_dict[str_in_key] = str_in_value
      return str_in_dict
    else:
      print("参数都没有,还处理个球嘛")
      return None

3.请求时将headers的content设置为m.content_type,会设置headers的content_type为form—data,类型为str:

MultipartEncoder相关源码:

Python基于requests实现模拟上传文件

Python基于requests实现模拟上传文件

4.请求时设置data为m,会输出一个MultipartEncoder对象:

Python基于requests实现模拟上传文件

方法2:

直接使用requests,无需依赖requests_toolbelt库

过程大同小异,也是需要将字典的value转换为str

注意:headers不要传content_type字段,headers不要传content_type字段,headers不要传content_type字段

请求时:data对应附加参数,files对应files对象

#相关代码
def upload(self):
    login_token = self.token.loadTokenList()
    for token in login_token:
      tempPassword_url = self.config['crm_test_api']+'/document/upload'
      tempPassword_data = self.data_to_str.strToDict('''title:1.png
      course_name_id:63
      course_id:1112
      desc:7
      doc_type:1
      is_public:1''',value_type='str')
      files={'file': ('1.png', open('C:\\Users\\Acer\\Pictures\\Screenshots\\1.png', 'rb'), 'image/png')}
      tempPassword_headers = {"token": token}
      tempPassword_request = requests.post(url=tempPassword_url,data=tempPassword_data,files=files,headers=tempPassword_headers)
      print(tempPassword_request.json())

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python下进行UDP网络编程的教程
Apr 29 Python
python中 logging的使用详解
Oct 25 Python
python输出100以内的质数与合数实例代码
Jul 08 Python
python 实现A*算法的示例代码
Aug 13 Python
Python3实现的反转单链表算法示例
Mar 08 Python
Python实战之制作天气查询软件
May 14 Python
django formset实现数据表的批量操作的示例代码
Dec 06 Python
python基于三阶贝塞尔曲线的数据平滑算法
Dec 27 Python
tensorflow模型继续训练 fineturn实例
Jan 21 Python
python+opencv边缘提取与各函数参数解析
Mar 09 Python
Jupyter安装拓展nbextensions及解决官网下载慢的问题
Mar 03 Python
python如何正确使用yield
May 21 Python
Ubuntu中配置TensorFlow使用环境的方法
Apr 21 #Python
基于jupyter代码无法在pycharm中运行的解决方法
Apr 21 #Python
如何基于python对接钉钉并获取access_token
Apr 21 #Python
python用TensorFlow做图像识别的实现
Apr 21 #Python
jupyter notebook 添加kernel permission denied的操作
Apr 21 #Python
Jupyter Notebook的连接密码 token查询方式
Apr 21 #Python
Python 操作 PostgreSQL 数据库示例【连接、增删改查等】
Apr 21 #Python
You might like
基于PHP实现用户注册登录功能
2016/10/14 PHP
写出更好的JavaScript之undefined篇(上)
2009/11/22 Javascript
js控制鼠标事件移动及移出效果显示
2014/10/19 Javascript
轻松创建nodejs服务器(9):实现非阻塞操作
2014/12/18 NodeJs
JavaScript简单遍历DOM对象所有属性的实现方法
2015/10/21 Javascript
JS使用正则表达式除去字符串中重复字符的方法
2015/11/05 Javascript
js仿支付宝填写支付密码效果实现多方框输入密码
2016/03/09 Javascript
jQuery ztree实现动态树形多选菜单
2016/08/12 Javascript
微信小程序 获取当前地理位置和经纬度实例代码
2016/12/05 Javascript
JS中用try catch对代码运行的性能影响分析
2016/12/26 Javascript
12306 刷票脚本及稳固刷票脚本(防挂)
2017/01/04 Javascript
Bootstrap里的文件分别代表什么意思及其引用方法
2017/05/01 Javascript
vue2.0 computed 计算list循环后累加值的实例
2018/03/07 Javascript
vue.js使用v-if实现显示与隐藏功能示例
2018/07/06 Javascript
深入浅出理解JavaScript高级定时器原理与用法
2018/08/02 Javascript
springMvc 前端用json的方式向后台传递对象数组方法
2018/08/07 Javascript
javascript实现遮罩层动态效果实例
2019/05/14 Javascript
解决vue cli使用typescript后打包巨慢的问题
2019/09/30 Javascript
Vue中qs插件的使用详解
2020/02/07 Javascript
javascript单张多张图无缝滚动实例代码
2020/05/10 Javascript
[49:35]KG vs SECRET 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/19 DOTA
Python完全新手教程
2007/02/08 Python
Python数据分析之获取双色球历史信息的方法示例
2018/02/03 Python
简单了解python的break、continue、pass
2019/07/08 Python
python3.7 sys模块的具体使用
2019/07/22 Python
Python爬虫实现百度翻译功能过程详解
2020/05/29 Python
Staples英国官方网站:办公用品一站式采购
2017/10/06 全球购物
保加利亚服装和鞋类购物网站:Bibloo.bg
2020/11/08 全球购物
TCP/IP中的TCP和IP分别承担什么责任
2012/04/21 面试题
家长会演讲稿范文
2014/01/10 职场文书
保卫科工作岗位职责
2014/03/01 职场文书
党的群众路线教育实践活动剖析材料
2014/09/30 职场文书
四风问题原因分析及整改措施
2014/10/24 职场文书
2015年新教师工作总结
2015/04/28 职场文书
实习感想范文
2015/08/10 职场文书
教师听课学习心得体会
2016/01/15 职场文书