Open
Description
I have been trying to use a simple code to post a product on WooCommerce from Python.
Im trying this code:
import sys
import googlemaps
from woocommerce import API
import base64
wcapi = API(
url="https://mysite.com",
consumer_key="ck_e6*********************************b9c5", # Your consumer key
consumer_secret="cs_3e*********************************e7de19", # Your consumer secret
wp_api=True, # Enable the WP REST API integration
version="wc/v3", # WooCommerce WP REST API version
query_string_auth=True,
timeout=10
)
data = {
"name": "Premium Quality",
"type": "simple",
"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.",
}
response = wcapi.post("products", data)
print("Status: ", response.status_code)
if response.status_code == 201:
print("Success")
else:
print("Error")
# print(response.text)
sys.exit()
I have gotten the "200" status.
Notthing was post on woocommerce.
After i tryed delete with the code:
print(wcapi.delete("products/108", params={"force": True}).json())
And deleted success.
Where am I going wrong?
Tks
Metadata
Metadata
Assignees
Labels
No labels
Activity
dinhopereira commentedon Apr 5, 2024
response = wcapi.post("products", data)
response is a empty array
My server is a litepeed and the log below:
nickolaschang commentedon Apr 9, 2024
Hope this helps, remeber that your CSV file MUST have all the headers equal to whatever info you want to update, for example if you want to update a products name (or add) you need to have a 'name' header in your csv file and etc..
import pandas as pd
import logging
import threading
import time
import tkinter as tk
from tkinter import filedialog, Button, Frame, ttk
from tkinter.scrolledtext import ScrolledText
from woocommerce import API
Define WooCommerce API credentials
WC_URL = 'insert website here'
WC_CONSUMER_KEY = 'insert key here'
WC_CONSUMER_SECRET = 'insert secret here'
Define a global variable for the root window
root = None
class TextHandler(logging.Handler):
def init(self, widget):
super().init()
self.widget = widget
def configure_wc_api():
return API(
url=WC_URL,
consumer_key=WC_CONSUMER_KEY,
consumer_secret=WC_CONSUMER_SECRET,
version="wc/v3",
timeout=300 # Set a higher timeout (in seconds)
)
def make_api_call(wcapi, method, endpoint, data=None, retries=1, delay=0.5):
for attempt in range(retries):
try:
if method.lower() == 'get':
response = wcapi.get(endpoint)
elif method.lower() == 'post':
response = wcapi.post(endpoint, data)
elif method.lower() == 'put':
response = wcapi.put(endpoint, data)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
def process_csv(wcapi, filename, progress_var, total_rows_label):
start_time = time.time()
df = pd.read_csv(filename, encoding='utf-8')
total_rows = len(df)
def create_product_data(row):
# Here you can edit as many fields as you want to edit, keep in mind to follow wcapi standards
data = {
"sku": row['sku'],
"name": row['name'],
"regular_price": row['regular_price'],
"description": row.get('description', ''),
"stock_quantity": int(row['stock_quantity']) if row['stock_quantity'] else None,
"manage_stock": True,
"images": [],
"attributes": [],
"categories": [],
}
def process_product(data, row_index, total_rows, action):
product_name = data.get('name', 'No Product Name Found in CSV')
if action == "update":
logging.info(f"Processing Row {row_index + 1} of {total_rows}")
logging.info(f"Product '{product_name}' (SKU: {data.get('sku', '')}, ID: {data.get('id', '')}) found")
logging.info(f"Updating Product...\n")
elif action == "create":
logging.info(
f"Product '{product_name}' (SKU: {data.get('sku', '')}, ID: {data.get('id', '')}) not found, creating...")
logging.info(f"Creating Product...\n")
def process_batch(wcapi, batch_data):
batch_action = batch_data[0][1]
logging.info(f"Processing {batch_action} batch...")
products = [data[0] for data in batch_data]
for item in products:
logging.info(
f"Product Sent to be {batch_action.capitalize()}d in WooCommerce, ID:{item.get('id', '')} / SKU: {item.get('sku', '')} / Product: {item.get('name', '')}")
response = make_api_call(wcapi, 'post', "products/batch", {batch_action: products})
if response and response.status_code != 200:
logging.error(
f"ERROR - API call failed with status {response.status_code} for products/batch:\n{response.text}")
else:
logging.info(f"Waiting for the batch to be processed...")
time.sleep(0.5) # Add a sleep time for waiting
logging.info('Processing Done! Moving on to next batch..\n')
def select_and_process_csv(progress_var, total_rows_label):
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
def main():
global root
root = tk.Tk()
root.title("Change your title name")
root.geometry("600x600")
if name == "main":
main()
nickolaschang commentedon Apr 9, 2024
Since GitHub makes a mess with the code you can use this file and paste it on your IDE
SynProducts.txt