如何使用 python/django POST 请求将图片上传到 woocommerce

Tha*_*nos 1 python django wordpress woocommerce

我创建了一个 woocommerce 网页,并且尝试使用与我的页面同步的 Django/Python。从文档woocomerce post request

data = {
    "product": {
        "title": "Sample of Title through POST",
        "type": "simple",
        "regular_price": "21.99",
        "description": "Long description from Post Request",
        "short_description": "Short description from Post Request",
        "categories": [
            9,
            14
        ],
        "images": [
            {
                "src": "http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg",
                "position": 0
            },
            {
                "src": "http://example.com/wp-content/uploads/2015/01/premium-quality-back.jpg",
                "position": 1
            }
        ]
    }
}

print (wcapi.post("products", data).json())
Run Code Online (Sandbox Code Playgroud)

我正在使用WooCommerce REST API 的 Python 包装器,它似乎可以处理 get 请求,但我找不到让它处理 post 请求的方法。

我不断收到此错误:

TypeError: <open file 'test.jpg', mode 'rb' at 0x104b4ced0> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我一直在网络上一遍又一遍地搜索可能的解决方案,但我找不到。有谁知道将图像从本地目录上传到网页的正确方法是什么?我尝试将路径从绝对路径重新格式化为 url 路径,但没有成功。

完整代码:

import pprint
import urllib
import os.path
import urlparse
from woocommerce import API


def path2url(path):
    return urlparse.urljoin(
        'file:', urllib.pathname2url(path))

wcapi = API(
    url= '' # Your store URL
    consumer_key= '' # Your consumer key
    consumer_secret= '' # Your consumer secret
    version='v3'  # WooCommerce API version
)
# Get request    
pprint.pprint(wcapi.get("products").json())

# Post request
data = {
    "product": {
        "title": "Sample of Title through POST",
        "type": "simple",
        "regular_price": "21.99",
        "description": "Long description from Post Request",
        "short_description": "Short description from Post Request",
        "categories": [
            9,
            14
        ],
        "images": [
            {
                "src": open('test.jpg', 'rb'),
                "position": 0
            },
            {
                "src": open('test.jpg', 'rb'),
                "position": 1
            }
        ]
    }
}

print (wcapi.post("products", data).json())
Run Code Online (Sandbox Code Playgroud)

更新:我尝试使用来自本地主机的图像的确切路径,例如“ http://localhost:8888/wordpress/wp-content/uploads/2016/04/test.jpg”,在浏览器上它工作正常,我可以看到图片。当我在发布请求上使用此路径时,它会产生相同的错误。我还尝试使用相对路径,例如“ file:///Users/tinyOS/Sites/wordpress/wp-content/uploads/2016/04/test.jpg”仍然相同的错误代码。

Tha*_*nos 7

所以我设法找到解决我的问题的方法。以防万一将来其他人可能需要它。

为了能够将图片上传到 woocommerce,您需要有一个有效的 url 路径(例如http://localhost:8888/wordpress/wp-content/uploads/2016/04/test.jpg

为了获取该网址,您需要首先使用相对路径将文件上传到 woocommerce,然后作为第二步检索路径并将其添加到辅助发布请求中,其中包含您要发布的产品的所有数据。

python 的工具是python-wordpress-xmlrpc。我还发现该手册包含更多分析示例,我发现这些示例比文档更有用:python-wordpress-xmlrpc, Documentation, Release 2.3

下面的例子演示了上传图像的过程。代码取自手册:

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts

client = Client('http://mysite.wordpress.com/xmlrpc.php', 'username', 'password')

# set to the path to your file
filename = '/path/to/my/picture.jpg'

# prepare metadata
data = {
'name': 'picture.jpg',
'type': 'image/jpeg', # mimetype
}

# read the binary file and let the XMLRPC library encode it into base64
with open(filename, 'rb') as img:
    data['bits'] = xmlrpc_client.Binary(img.read())

response = client.call(media.UploadFile(data))

# response == {
# 'id': 6,
# 'file': 'picture.jpg'
# 'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg',
# 'type': 'image/jpeg',
# }
attachment_id = response['id']
Run Code Online (Sandbox Code Playgroud)

第二步,您可以创建一个函数,将所有信息发布到您的 woocommerce 商店。代码示例取自创建产品、WooCommerce 2.1、REST API。您只需创建一个包含所有数据的字典:

data = {
    "product": {
        "title": "Premium Quality",
        "type": "simple",
        "regular_price": "21.99",
        "description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
        "short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
        "categories": [
            9,
            14
        ],
        "images": [
            {
                "src": "http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg",
                "position": 0
            },
            {
                "src": "http://example.com/wp-content/uploads/2015/01/premium-quality-back.jpg",
                "position": 1
            }
        ]
    }
}

print(wcapi.post("products", data).json())
Run Code Online (Sandbox Code Playgroud)

需要src:替换为从上传请求中检索到的 url,瞧。如果您知道要使用哪些工具,则非常简单;如果您不知道,则非常复杂。

我希望这有帮助。