如何在python中使用woocommerce api给产品属性赋值

问题描述 投票:0回答:1

我的目标是通过使用woocommerce api为自定义创建的产品属性赋予价值。

但是我不知道该怎么做。官方api文档https://woocommerce.github.io/woocommerce-rest-api-docs/?python#create-a-product-attribute不是提及任何事情。

我曾经做过这样的创建:

product_attributes = {
    "attributes": [
        {
            "name" : "color",
            "slug":"color_slug",
            "visible": True,
            "options": [
              "blue",
              "black",
            ]
        }
    ]
    }
wcapi_yachtcharterapp.post("products/attributes", product_attributes).json()

以及类似的更新:

product_attributes = {
    "attributes": [
        {
            "name" : "color",
            "slug":"color_slug",
            "visible": True,
            "options": [
              "blue",
              "black",
            ]
        }
    ]
    }
wcapi_yachtcharterapp.put("products/attributes/"+str(post_id), product_attributes).json()

但没有用。

我假设我必须先创建属性,然后给出一个值。

有人知道怎么做吗?

python woocommerce woocommerce-rest-api
1个回答
0
投票

您需要先添加属性,然后再添加属性术语。您必须在不同的端点中进行添加。这就是我的方法:

import yaml
from woocommerce import API
from pprint import pprint
from collections import ChainMap


class WOO_API():
 def __init__(self):
    with open("config.yml", "r") as ymlfile:
        cfg = yaml.full_load(ymlfile)

    self.API = API(
    url=cfg['woocommerce']['url'], # Your store URL
    consumer_key=cfg['woocommerce']['consumer_key'], # Your consumer key
    consumer_secret=cfg['woocommerce']['consumer_secret'], # Your consumer secret
    wp_api=True, # Enable the WP REST API integration
    version="wc/v3" # WooCommerce WP REST API version
    )

def retrieve_attributes(self):
    return self.API.get("products/attributes").json()

def add_attribute(self,
                                    name,
                                    slug,
                                    tp="select", 
                                    order_by="menu_order", 
                                    has_archives=True):
    data = {
        "name": name,
        "slug": slug,
        "type": tp,
        "order_by": order_by,
        "has_archives": has_archives
    }
    return self.API.post("products/attributes", data).json()

def retrive_attribute_terms(self, id):
    parameters = {
        'per_page': 100
    }
    return self.API.get("products/attributes/"+id+"/terms", params=parameters).json()

def add_attribute_terms(self, name, id):
    data = {
        'name' : name
    }
    return self.API.post("products/attributes/"+id+"/terms", data).json()

在属性术语端点中使用的ID是属性ID。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.