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

时间:2016-04-11 14:29:31

标签: 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())

我正在使用Python wrapper for the WooCommerce REST API,它似乎正在处理get请求,我找不到一种方法让它与post请求一起使用。

我不断收到此错误:

TypeError: <open file 'test.jpg', mode 'rb' at 0x104b4ced0> is not JSON serializable

我一直在网上寻找可能的解决方案,但我找不到一个。有谁知道将图像从本地目录上传到网页的正确方法是什么?我试图重新格式化从绝对路径到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())

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

1 个答案:

答案 0 :(得分:2)

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

为了能够将图片上传到woocommerce,您需要有一个有效的网址路径(例如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']

作为第二步,您可以创建一个功能,将所有信息发布到您的woocommerce商店。代码示例取自Create a Product, WooCommerce 2.1, the 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())

需要使用上传请求中检索到的网址替换src:并瞧。如果你知道使用哪种工具就很简单,如果不知道就很复杂。

我希望这会有所帮助。