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字段(我们系统是这样,具体结合前端实际的字段为准),如图
2.字典value里面的对象:
1.filename(服务器最终存储的文件名)
2.filepath(具体的文件路径,注意转义),文件是以二进制的形式进行传输的,所以这里传输时以二进制的形式打开文件并传输
3.content_type:具体结合前端实际的字段为准:一般可定义为: 文本(text)/图片(image)等[/code][code]
3.tempPassword_data:为文件上传时的附带参数
strToDict方法:自己手写的一个字符串转dict的方法
遇到的问题:
这个错误是说,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相关源码:
4.请求时设置data为m,会输出一个MultipartEncoder对象:
方法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


猜你喜欢
- PyQt5安装在cmd下输入pip install PyQt5完成PyQt5安装,再安装qt designer,可以使用pip安装pip i
- 官方文档介绍链接:append方法介绍DataFrame.append(other, ignore_index=False, verify_
- 在机器学习过程中,通常会通过pandas读取csv文件,保持成dadaframe格式,然而有时候需要对dataframe中的时间字段进行数据
- Python 直接连接mongodb数据库进行查询操作1、安装所需模块使用到的是pymongo模块,安装方法:pip instal
- 新手小白,一直在为cmd窗口的暗白色文字感到苦恼,在网上找了许多方法(也就那两种吐舌头),现在稍微整理了一下,便于使用。效果图:import
- 下面通过代码给大家介绍python打包压缩指定目录下的指定类型文件,具体代码如下所示:import osimport datetimeimp
- JS 添加千分位,测试可以使用<script language="javascript" type="t
- 导言就计算机科学而言,caching就是将所需要的数据或信息的备份放在某个地方,便于快速访问的这样一个过程。以数据处理(data-drive
- 装饰器(decorator)是一种高级Python语法。装饰器可以对一个函数、方法或者类进行加工。在Python中,我们有多种方法对函数和类
- 1. 事务介绍MVCC之前,先介绍下事务:事务是为了保证数据库中数据的完整性和一致性。事务的4个基本要素:原子性(Atomicity):要么
- 开机运行:随系统启动的应用程序,当系统启动之后会自动加载的应用在注册表中添加启动项便可实现开机启动。代码如下:# -*- coding:ut
- 前提条件:1.安装好Wampserver64(版本不限)2.Wampserver64软件启动后 变为绿色如:3.在数据库里面创建好名为&am
- 找到对应页面,将Reopen last project on startup前面的勾去掉来源:https://blog.csdn.net/l
- 封装为了jq插件,如下drag.js;(function ($) { $.fn.dragDiv = function (options) {
- 例如:我们在百度中搜索 词典网,则网址后面的参数就是http://www.baidu.com/s?cl=3&wd=%B4%CA%B5
- 一、前言python在数组中随机取值有现成的方法,但是要给每个随机值被取到的概率加权重的话,可以参考下面这个方法二、实现方式import r
- 事件是javascript中的核心内容之一,在对事件的应用中不可避免的要涉及到一个重要的概念,那就是事件冒泡,在介绍事件冒泡之前,先介绍一下
- 在开发中我们经常遇到这样的需求,需要用户直接点击一个链接进入到一个页面,用户点击后链接后会触发401拦截返回登录界面,登录后又跳转到链接的页
- asp代码 如下:读取注册表信息使用了对象WScript.Shell<%Dim strPath strP
- CentOS安装Python1.CentOS已经自带安装了2.x版本,先尝试python命令检查已安装的版本.如果你使用rpm、yum或de