PUT请求Payload用本地文件报错:BufferedReader无法JSON序列化求助
问题:本地PNG文件作为PUT请求Payload时的JSON序列化错误
你尝试向Printful API发送PUT请求,希望在Payload中包含本地PNG文件信息,使用open('images/path-to-image/image-1.png', 'rb')读取文件,但收到错误:
TypeError: Object of type BufferedReader is not JSON serializable
改用网络图片URL时代码可正常运行,需明确错误原因及本地文件的正确使用方式。
你的完整代码:
order_number = 99 item_number = 12345678 url = f"https://api.printful.com/orders/@{order_number}" payload={ 'items': [ {'external_id': str(item_number), 'files': [ {'url': open('images/path-to-image/image-1.png', 'rb'), 'position': { 'area_width': 3000, 'area_height': 4000, 'width': 3000, 'height': 4000, 'top': 0, 'left': 0} } ] } ] } headers = { 'Authorization': 'Bearer PRIVATE-KEY' } response = requests.request("PUT", url, headers=headers, json=payload) res = response.json() print(f"Order {order_number}, Code result: {res['code']}")
错误原因
你直接将open()返回的BufferedReader文件流对象放入了JSON Payload中,但JSON仅支持序列化字符串、数字、列表、字典等基础数据类型,无法直接处理文件流对象,因此触发序列化错误。
解决方法
Printful API支持两种方式处理本地文件上传:
方式1:先上传文件到Printful存储,再使用返回的URL
先调用Printful的文件上传API将本地图片上传至其服务器,获取返回的文件URL后,再将该URL放入PUT请求的Payload中:
import requests # 1. 上传本地文件到Printful upload_url = "https://api.printful.com/files" headers = {'Authorization': 'Bearer PRIVATE-KEY'} with open('images/path-to-image/image-1.png', 'rb') as img_file: files = {'file': img_file} upload_response = requests.post(upload_url, headers=headers, files=files) upload_data = upload_response.json() file_url = upload_data['result']['url'] # 2. 发送PUT请求更新订单 order_number = 99 item_number = 12345678 url = f"https://api.printful.com/orders/@{order_number}" payload={ 'items': [ {'external_id': str(item_number), 'files': [ {'url': file_url, 'position': { 'area_width': 3000, 'area_height': 4000, 'width': 3000, 'height': 4000, 'top': 0, 'left': 0} } ] } ] } response = requests.put(url, headers=headers, json=payload) res = response.json() print(f"Order {order_number}, Code result: {res['code']}")
方式2:使用multipart/form-data格式直接发送文件
无需单独调用上传API,将请求改为multipart/form-data格式,同时传递JSON数据和本地文件:
import requests import json order_number = 99 item_number = 12345678 url = f"https://api.printful.com/orders/@{order_number}" # 定义订单Payload数据 payload_data = { 'items': [ {'external_id': str(item_number), 'files': [ {'url': 'file://image-1.png', # 用该标识关联上传的文件 'position': { 'area_width': 3000, 'area_height': 4000, 'width': 3000, 'height': 4000, 'top': 0, 'left': 0} } ] } ] } headers = {'Authorization': 'Bearer PRIVATE-KEY'} # 组合multipart数据:JSON转字符串+本地文件 with open('images/path-to-image/image-1.png', 'rb') as img_file: multipart_data = { 'json': (None, json.dumps(payload_data), 'application/json'), 'image-1.png': img_file } response = requests.put(url, headers=headers, files=multipart_data) res = response.json() print(f"Order {order_number}, Code result: {res['code']}")
注意事项
- 使用
with open(...) as f:的写法,可自动关闭文件流,避免资源泄漏 - 确保本地文件路径正确,避免触发文件找不到的异常
- 保持Authorization头部的密钥有效,否则会触发权限错误
内容的提问来源于stack exchange,提问作者Alex Capellan
相关产品推荐
相关产品推荐

