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的类变量和成员变量用法实例教程
Aug 25 Python
Python用GET方法上传文件
Mar 10 Python
Python的SQLalchemy模块连接与操作MySQL的基础示例
Jul 11 Python
PyQt5每天必学之QSplitter实现窗口分隔
Apr 19 Python
Django中使用 Closure Table 储存无限分级数据
Jun 06 Python
把django中admin后台界面的英文修改为中文显示的方法
Jul 26 Python
Python列表的切片实例讲解
Aug 20 Python
浅谈Python 递归算法指归
Aug 22 Python
利用Python小工具实现3秒钟将视频转换为音频
Oct 29 Python
python实现拉普拉斯特征图降维示例
Nov 25 Python
python numpy数组中的复制知识解析
Feb 03 Python
基于Tensorflow批量数据的输入实现方式
Feb 05 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中的串行化变量和序列化对象
2006/09/05 PHP
PHP 图片上传实现代码 带详细注释
2010/04/29 PHP
php 5.3.5安装memcache注意事项小结
2011/04/12 PHP
PHP获取当前相对于域名目录的方法
2015/06/26 PHP
php nginx 实时输出的简单实现方法
2018/01/21 PHP
PHP get_html_translation_table()函数用法讲解
2019/02/16 PHP
laravel返回统一格式错误码问题
2019/11/04 PHP
jQuery 注意事项 与原因分析
2009/04/24 Javascript
基于JQuery的一句代码实现表格的简单筛选
2010/07/26 Javascript
Raphael带文本标签可拖动的图形实现代码
2013/02/20 Javascript
jquery indexOf使用方法
2013/08/19 Javascript
ie浏览器使用js导出网页到excel并打印
2014/03/11 Javascript
jQuery实现的简单百分比进度条效果示例
2016/08/01 Javascript
从零开始学习Node.js系列教程六:EventEmitter发送和接收事件的方法示例
2017/04/13 Javascript
详解vue+vueRouter+webpack的简单实例
2017/06/17 Javascript
使用angular-cli webpack创建多个包的方法
2018/10/16 Javascript
详解Vue 单文件组件的三种写法
2020/02/19 Javascript
Vue使用预渲染代替SSR的方法
2020/07/02 Javascript
JavaScript实现拖拽和缩放效果
2020/08/24 Javascript
[02:41]DOTA2亚洲邀请赛小组赛第三日 赛事回顾
2015/02/01 DOTA
[50:34]VGJ.T vs Fnatic 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
浅谈Python程序与C++程序的联合使用
2015/04/07 Python
在Python中处理字符串之isdigit()方法的使用
2015/05/18 Python
python如何实现一个刷网页小程序
2018/11/27 Python
关于Pycharm无法debug问题的总结
2019/01/19 Python
详解pandas使用drop_duplicates去除DataFrame重复项参数
2019/08/01 Python
python json.dumps中文乱码问题解决
2020/04/01 Python
pycharm使用技巧之自动调整代码格式总结
2020/11/04 Python
python如何调用php文件中的函数详解
2020/12/29 Python
使用phonegap进行本地存储的实现方法
2017/03/31 HTML / CSS
西班牙最好的在线购买葡萄酒的商店:Vinoseleccion
2019/10/30 全球购物
《藏戏》教学反思
2014/02/11 职场文书
公司应聘求职信
2014/06/21 职场文书
go xorm框架的使用
2021/05/22 Golang
Python利用capstone实现反汇编
2022/04/06 Python
python画条形图的具体代码
2022/04/20 Python