You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify API(Python)文件上传出现Processing Error原因排查

问题

尝试通过Python调用Shopify API将图片上传至店铺Files板块,代码参考公开实现编写。代码运行无报错,fileCreate接口返回成功数据:

{'data': {'fileCreate': {'files': [{'alt': 'alt-tag'}], 'userErrors': []}}, 'extensions': {'cost': {'requestedQueryCost': 20, 'actualQueryCost': 20, 'throttleStatus': {'maximumAvailable': 1000.0, 'currentlyAvailable': 980, 'restoreRate': 50.0}}}}

但店铺Files页面显示“1 upload failed -- processing error”,请求排查代码问题。代码如下:

import requests
import os

# Set up Shopify API credentials
shopify_store = 'url-goes-here.myshopify.com' # 实际URL已替换
access_token = 'token-goes-here' # 实际token已替换

# Read the image file
image_path = r'C:\the-actual-filepath-is-here\API-TEST-1.jpg'  # Replace with the actual path to your image file
with open(image_path, 'rb') as file:
    image_data = file.read()

# Create staged upload
staged_upload_url = f"https://{shopify_store}/admin/api/2023-04/graphql.json"
staged_upload_query = '''
mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {
  stagedUploadsCreate(input: $input) {
    stagedTargets {
      resourceUrl
      url
      parameters {
        name
        value
      }
    }
    userErrors {
      field
      message
    }
  }
}
'''
staged_upload_variables = {
    "input": [
        {
            "filename": "API-TEST-1.jpg",
            "httpMethod": "POST",
            "mimeType": "image/jpeg",
            "resource": "FILE"
        }
    ]
}

response = requests.post(
    staged_upload_url,
    json={"query": staged_upload_query, "variables": staged_upload_variables},
    headers={"X-Shopify-Access-Token": access_token}
)

data = response.json()
staged_targets = data['data']['stagedUploadsCreate']['stagedTargets']
target = staged_targets[0]
params = target['parameters']
url = target['url']
resource_url = target['resourceUrl']

# Post image data to the staged target
form_data = {
    "file": image_data
}
headers = {
    param['name']: param['value'] for param in params  # Fix the headers assignment
}
headers["Content-Length"] = str(len(image_data))

response = requests.post(url, files=form_data, headers=headers)  # Use 'files' parameter instead of 'data'

# Create the file in Shopify using the resource URL
create_file_url = f"https://{shopify_store}/admin/api/2023-04/graphql.json"
create_file_query = '''
mutation fileCreate($files: [FileCreateInput!]!) {
  fileCreate(files: $files) {
    files {
      alt
    }
    userErrors {
      field
      message
    }
  }
}
'''
create_file_variables = {
    "files": [
        {
            "alt": "alt-tag",
            "contentType": "IMAGE",
            "originalSource": resource_url
        }
    ]
}

response = requests.post(
    create_file_url,
    json={"query": create_file_query, "variables": create_file_variables},
    headers={"X-Shopify-Access-Token": access_token}
)

data = response.json()
files = data['data']['fileCreate']['files']
alt = files[0]['alt']
问题排查与修复方案

出现这个问题的核心原因是上传到临时存储(staged target)时的请求格式错误,具体问题和修复如下:

1. 错误处理StagedUpload返回的Parameters

Shopify返回的parameters里,一部分是请求头参数,另一部分是表单字段参数,不能全部塞进请求头:

  • 以Content-开头的参数属于请求头
  • 其他参数(比如key、policy、signature等)属于表单字段

2. 手动设置Content-Length导致冲突

使用requests.post的files参数时,requests会自动计算并设置Content-Length,手动设置会导致实际上传内容长度与声明的不匹配,引发处理错误。

3. 文件上传未指定文件名和MIME类型

直接传二进制数据时,需要明确指定文件名和MIME类型,让Shopify正确识别文件格式。

修复后的代码(替换上传到staged target的部分)

# Post image data to the staged target
# 分离header参数和表单参数
headers = {}
form_fields = {}
for param in params:
    if param['name'].startswith('Content-'):
        headers[param['name']] = param['value']
    else:
        form_fields[param['name']] = param['value']

# 构造files参数,指定文件名和MIME类型
files = {
    'file': ('API-TEST-1.jpg', image_data, 'image/jpeg')
}

# 发送请求,不需要手动设置Content-Length
response = requests.post(url, files=files, data=form_fields, headers=headers)

# 检查临时上传是否成功
if response.status_code not in [200, 201]:
    print(f"临时上传失败: {response.text}")
    exit()

额外建议

  • 调用stagedUploadsCreate后,检查userErrors是否为空,提前排查错误
  • 临时上传后,检查响应状态码和内容,确认文件已成功上传到临时存储

内容的提问来源于stack exchange,提问作者king_anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:07:54