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

作者:wan了个蛋 时间:2023-09-30 01:42:05 

方法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())

来源:https://www.cnblogs.com/qtclm/p/12684360.html

标签:Python,requests,上传
0
投稿

猜你喜欢

  • MySQL全文索引实现简单版搜索引擎实例代码

    2024-01-25 20:30:19
  • python对Excel的读取的示例代码

    2023-03-27 17:55:06
  • 《色彩解答》系列之二 色彩比例

    2008-02-17 14:38:00
  • iscroll动态加载数据完美解决方法

    2024-04-10 13:59:01
  • Python 函数list&read&seek详解

    2022-02-14 03:04:21
  • 在Windows系统上搭建Nginx+Python+MySQL环境的教程

    2024-01-24 08:04:40
  • Pycharm学习教程(2) 代码风格

    2022-03-21 08:38:31
  • 不拘小节的中文字体设计

    2009-05-21 10:44:00
  • python 根据时间来生成唯一的字符串方法

    2022-12-25 14:49:48
  • 获取url中用&隔开的参数实例(分享)

    2024-05-28 15:40:46
  • python对gif图压缩的完美解决方案

    2021-06-19 03:09:00
  • 网站大改版=壮烈的死亡 ?

    2009-04-03 14:09:00
  • Python实现五子棋联机对战小游戏

    2023-10-21 05:25:42
  • mysql如何查询日期与时间

    2024-01-26 02:03:17
  • 深入了解Golang中的格式化输出

    2024-04-26 17:35:27
  • 浅谈微信小程序之官方UI框架we-ui使用教程

    2024-04-16 09:52:43
  • 如何用vue实现网页截图你知道吗

    2024-04-27 15:51:31
  • Pthon批量处理将pdb文件生成dssp文件

    2021-10-07 13:11:04
  • sqlserver、Mysql、Oracle三种数据库的优缺点总结

    2024-01-22 10:33:56
  • Python实现ATM简单功能的示例详解

    2021-07-17 12:06:46
  • asp之家 网络编程 m.aspxhome.com