当使用squareup python API将图像上传到目录时,它在文件参数上失败。我将发布代码、失败以及关于API文档的一些观察。
pip安装方法#1
我实际上用了
requirements.txt
,但这是我安装模块的有效方式:
$ pip install squareup
代码
# Import the os package
import os
# import the dotenv package
from dotenv import load_dotenv
# Get the current working directory
cwd = os.getcwd()
# Construct the .env file path
env_path = os.path.join(cwd, '.env')
# Load the .env file
load_dotenv(dotenv_path=env_path)
# Import square
from square.client import Client
# init the square API
sq_client = Client(
access_token=os.environ['SQUARE_ACCESS_TOKEN'],
environment='production'
)
# This works to verify api key and access id to upload to production environment. ie
# not sandbox
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)
# afterwards, I could look in the square storefront and see the
# sample item in the storefront catalog.
# As a further test of the API, here is getting info about the
# api in the sample item. This also works as expected.
result = sq_client.catalog.list_catalog()
if result.is_success():
print(result.body)
elif result.is_error():
print(result.errors)
# This fails though.
file_to_upload_path = "./sample_imgs/drdoom.jpeg" # Modify this to point to your desired file.
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调用失败。它在
file = f_stream
参数对f_stream使用读取操作是有效的,所以这并不是说找不到图像,而是文件参数本身。
其他感兴趣的地方,我使用了square api explorer网页,并做了完全相同的代码,它在那里工作。唯一的区别是资源管理器生成一个密钥,而不是使用
{UNIQUE_KEY}
机械装置我还试着把这张照片放在
这样我就不需要使用相对目录路径。即不
./sample_imgs'
前缀
考虑到错误可能与python库的版本和文件参数有关,我回到了square文档中,了解他们指定如何安装sdk。
这
page
有一个关于如何获得SDK包的链接,上面写着访问PyPi。注意PyPi上的链接指定使用git。结果,我在requirements.txt中使用了这个
方法#2的requirements.txt
# square api install for method #1
#squareup
# square api install for method #2 using git clone
#square-python-sdk
git+https://github.com/square/square-python-sdk.git
但是,使用git版本也会出现同样的错误。请告知。