python request 上传图片
项目中需要测试一个上传图片的接口,几经周折终于搞定了,把过程记录下来备忘。
需求
上传图片需要经过两步:
- 上传图片引擎 ,上传成功,会返回一个picId
- 同步到业务系统 ,这时使用返回的picId,请求业务系统的接口
实现
通过使用request库的post方法实现
格式:fields = {“file”: (file_name, file_handler, mime_type)}
其中
import requests
import filetype
import os
from requests_toolbelt import MultipartEncoder
from uuid import uuid4
# 文件名称
file_name = os.path.basename(file_path)
# 获取文件类型
file_type = filetype.guess(file_path)
mime_type = file_type.mime
# 读取文件内容
with open(file_path, 'rb') as f:
file_handler = f.read()
# 获取boundary
boundary_value = uuid4().hex
boundary = '--{0}'.format(boundary_value)
# 组装文件
fields = {"file": (