使用Square Python API上传目录图片时file参数报错求助
Square Python API 上传目录图片时file参数报错问题
安装方式
- 初始安装:通过
requirements.txt安装,等效命令:
pip install squareup
- 版本排查时改用官方Git仓库安装,
requirements.txt配置:
# 从官方Git仓库安装SDK git+https://github.com/square/square-python-sdk.git
完整代码示例
import os from dotenv import load_dotenv from square.client import Client # 加载环境变量 cwd = os.getcwd() env_path = os.path.join(cwd, '.env') load_dotenv(dotenv_path=env_path) # 初始化Square客户端 sq_client = Client( access_token=os.environ['SQUARE_ACCESS_TOKEN'], environment='production' ) # 验证权限:创建商品接口可正常调用 result = sq_client.catalog.upsert_catalog_object( body = { "idempotency_key": "{UNIQUE_KEY}", "object": { "type": "ITEM", "id": "#coffee", "item_data": { "name": "Coffee", "description": "Coffee Drink", "abbreviation": "Co", "variations": [ { "type": "ITEM_VARIATION", "id": "#small_coffee", "item_variation_data": { "item_id": "#coffee", "name": "Small", "pricing_type": "FIXED_PRICING", "price_money": { "amount": 300, "currency": "USD" } } }, { "type": "ITEM_VARIATION", "id": "#large_coffee", "item_variation_data": { "item_id": "#coffee", "name": "Large", "pricing_type": "FIXED_PRICING", "price_money": { "amount": 350, "currency": "USD" } } } ] } } } ) if result.is_success(): print(result.body) elif result.is_error(): print(result.errors) # 验证权限:列出目录接口可正常调用 result = sq_client.catalog.list_catalog() if result.is_success(): print(result.body) elif result.is_error(): print(result.errors) # 报错的图片上传代码 file_to_upload_path = "./sample_imgs/drdoom.jpeg" f_stream = open(file_to_upload_path, "rb") result = sq_client.catalog.create_catalog_image( request = { "idempotency_key": "{UNIQUE_KEY}", "image": { "type": "IMAGE", "id": "#image_id", "image_data": { "name": "Image name", "caption": "Image caption" } } }, file = f_stream ) if result.is_success(): print(result.body) elif result.is_error(): print(result.errors)
问题详情
- 前序接口(商品创建、目录列表)均正常,确认API密钥和生产环境权限有效。
- 调用
create_catalog_image时失败,报错指向file参数,但文件流可正常读取。 - 在Square API Explorer中执行相同逻辑(仅自动生成idempotency_key)可成功上传图片。
已尝试的解决步骤
- 更换SDK安装源,从PyPI包改为官方Git仓库代码,问题未解决。
可行的解决方向
- 重置文件流指针
打开文件后若有过读取操作,指针可能不在文件开头,需重置:f_stream = open(file_to_upload_path, "rb") f_stream.seek(0) # 将指针移至文件起始位置 - 使用绝对文件路径
避免相对路径带来的工作目录问题:file_to_upload_path = os.path.abspath(os.path.join("sample_imgs", "drdoom.jpeg")) - 显式指定文件元数据
部分SDK需明确文件名和Content-Type,尝试按元组格式传入:import uuid filename = os.path.basename(file_to_upload_path) result = sq_client.catalog.create_catalog_image( request = { "idempotency_key": str(uuid.uuid4()), "image": { "type": "IMAGE", "id": "#image_id", "image_data": { "name": filename, "caption": "Image caption" } } }, file = (filename, f_stream, "image/jpeg") ) - 生成真实唯一的idempotency_key
不要使用占位符{UNIQUE_KEY},用UUID生成唯一值:import uuid idempotency_key = str(uuid.uuid4())
内容的提问来源于stack exchange,提问作者netskink
相关产品推荐
相关产品推荐

