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": (file_name, file_handler, mime_type)}
encode_data = MultipartEncoder(fields, boundary)
ContentType = en

本文记录了使用Python的request库上传图片到接口的过程,包括上传图片到图片引擎并获取picId,然后将picId同步到业务系统。主要难点在于文件的二进制读取、MultipartEncoder的boundary参数设置以及Content-Type的正确获取。

1737

被折叠的 条评论
为什么被折叠?



