杰瑞科技汇

WooCommerce如何用Python实现数据交互?

Of course! Working with WooCommerce using Python is a common task for automating e-commerce processes, integrating with other systems, or analyzing data. The primary way to do this is by using the WooCommerce REST API.

WooCommerce如何用Python实现数据交互?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything you need to know.

The Core Concept: The WooCommerce REST API

You don't interact with WooCommerce directly with Python libraries like you might with a database. Instead, you use the REST API, which is a set of URLs (endpoints) that allow you to perform actions like:

  • Read: Get products, orders, customers, etc.
  • Create: Add a new product, create a new order.
  • Update: Modify a product's price, change an order's status.
  • Delete: Remove a product or an order.

Your Python script will act like a web browser, sending HTTP requests (GET, POST, PUT, DELETE) to these API endpoints.


Prerequisites

Before you start coding, you need two things from your WordPress/WooCommerce site:

WooCommerce如何用Python实现数据交互?-图2
(图片来源网络,侵删)

a) API Keys (Consumer Key & Consumer Secret)

  1. Log in to your WordPress admin dashboard.
  2. Go to WooCommerce > Settings > Advanced > REST API.
  3. Click on "Add Key".
  4. Description: Give your key a descriptive name (e.g., "Python Product Updater").
  5. Permissions: Choose the level of access your script needs.
    • Read: Only view data.
    • Write: Create and modify data.
    • Read/Write: Full access.
  6. Click "Generate API Key".
  7. IMPORTANT: Copy the Consumer Key and Consumer Secret immediately. You will not be able to see the secret again after you leave this page. Store them securely (e.g., in environment variables, not in your code).

b) Your Site URL

This is the base URL for your API calls. It will be your WordPress site's address, usually ending in /wp-json.

  • Example: https://your-store.com/wp-json

Choosing a Python HTTP Library

You have a few great options for making HTTP requests in Python.

Option 1: requests (Recommended for Beginners)

The requests library is the de facto standard for HTTP in Python. It's simple, powerful, and has a fantastic API.

Installation:

pip install requests

Option 2: woocommerce (A Specialized Wrapper)

There's a library specifically designed to wrap the WooCommerce API, which can save you some boilerplate code.

Installation:

pip install woocommerce

Example 1: Using the requests Library

This is the most common and flexible approach. We'll create a reusable function to handle authentication.

Step 1: Set Up Your Credentials and Base URL

Never hardcode your credentials directly into your script. Use environment variables for security.

# In your terminal (Linux/macOS) or PowerShell (Windows)
# export WOO_URL="https://your-store.com"
# export WOO_KEY="ck_your_consumer_key"
# export WOO_SECRET="cs_your_consumer_secret"

In your Python script, load them:

import os
import requests
import json
# Load credentials from environment variables
WOO_URL = os.getenv("WOO_URL")
WOO_KEY = os.getenv("WOO_KEY")
WOO_SECRET = os.getenv("WOO_SECRET")
# The API endpoint for products
API_ENDPOINT = f"{WOO_URL}/wp-json/wc/v3/products"

Step 2: Create an Authenticated Session

The WooCommerce API uses Basic Authentication. We can create a session object to handle this for all our requests.

def create_woocommerce_session():
    """Creates an authenticated requests session for WooCommerce."""
    session = requests.Session()
    session.auth = (WOO_KEY, WOO_SECRET)
    # It's good practice to set a user agent
    session.headers.update({'User-Agent': 'My-Python-App/1.0'})
    return session
wc_session = create_woocommerce_session()

Step 3: Perform CRUD Operations

Now you can use the wc_session object to interact with the API.

a) READ: Get All Products

try:
    # The 'params' dictionary is used for query parameters
    # e.g., per_page=10, page=2
    response = wc_session.get(API_ENDPOINT, params={'per_page': 10})
    # Raise an exception for bad status codes (4xx or 5xx)
    response.raise_for_status()
    products = response.json()
    print(f"Successfully retrieved {len(products)} products.")
    for product in products:
        print(f"- ID: {product['id']}, Name: {product['name']}, Price: {product['price']}")
except requests.exceptions.RequestException as e:
    print(f"Error fetching products: {e}")
    if e.response is not None:
        print(f"Response Body: {e.response.text}")

b) CREATE: Add a New Product

new_product = {
    "name": "A Custom Python T-Shirt",
    "type": "simple",
    "regular_price": "25.00",
    "description": "A high-quality t-shirt for Python developers.",
    "short_description": "Show your love for Python!",
    "categories": [
        {"id": 9}  # Replace with an existing category ID
    ],
    "images": [
        {
            "src": "https://your-store.com/wp-content/uploads/2025/10/python-shirt.jpg"
        }
    ]
}
try:
    response = wc_session.post(API_ENDPOINT, data=json.dumps(new_product))
    response.raise_for_status()
    created_product = response.json()
    print(f"Successfully created product with ID: {created_product['id']}")
    print(json.dumps(created_product, indent=2))
except requests.exceptions.RequestException as e:
    print(f"Error creating product: {e}")
    if e.response is not None:
        print(f"Response Body: {e.response.text}")

c) UPDATE: Modify a Product

Let's change the price of the product we just created.

product_id_to_update = created_product['id'] # Get the ID from the previous step
updated_product_data = {
    "regular_price": "30.00" # New price
}
UPDATE_ENDPOINT = f"{API_ENDPOINT}/{product_id_to_update}"
try:
    response = wc_session.put(UPDATE_ENDPOINT, data=json.dumps(updated_product_data))
    response.raise_for_status()
    updated_product = response.json()
    print(f"Successfully updated product ID {updated_product['id']}. New price: {updated_product['regular_price']}")
except requests.exceptions.RequestException as e:
    print(f"Error updating product: {e}")
    if e.response is not None:
        print(f"Response Body: {e.response.text}")

d) DELETE: Remove a Product

DELETE_ENDPOINT = f"{API_ENDPOINT}/{product_id_to_update}"
try:
    # The WooCommerce API requires `force=true` to permanently delete a product
    response = wc_session.delete(DELETE_ENDPOINT, params={'force': 'true'})
    response.raise_for_status()
    print(f"Successfully deleted product ID {product_id_to_update}.")
except requests.exceptions.RequestException as e:
    print(f"Error deleting product: {e}")
    if e.response is not None:
        print(f"Response Body: {e.response.text}")

Example 2: Using the woocommerce Library

This library abstracts away some of the details like authentication and request formatting.

import os
import woocommerce
# Load credentials from environment variables
WOO_URL = os.getenv("WOO_URL")
WOO_KEY = os.getenv("WOO_KEY")
WOO_SECRET = os.getenv("WOO_SECRET")
# Initialize the API client
wcapi = woocommerce.WooCommerce(
    WOO_URL,
    WOO_KEY,
    WOO_SECRET,
    version="wc/v3" # Specify the API version
)
try:
    # READ: Get all products
    products = wcapi.get("products", params={'per_page': 5})
    print(f"--- Retrieved {len(products['data'])} products ---")
    for product in products['data']:
        print(f"- ID: {product['id']}, Name: {product['name']}")
    # CREATE: Add a new product
    new_product_data = {
        "name": "API-Generated Mug",
        "regular_price": "15.00",
        "description": "A mug for your morning coffee."
    }
    created_product = wcapi.post("products", new_product_data)
    print("\n--- Created Product ---")
    print(f"ID: {created_product['data']['id']}, Name: {created_product['data']['name']}")
    # UPDATE: Change the price
    product_id_to_update = created_product['data']['id']
    updated_data = {"regular_price": "18.00"}
    updated_product = wcapi.put(f"products/{product_id_to_update}", updated_data)
    print("\n--- Updated Product ---")
    print(f"ID: {updated_product['data']['id']}, New Price: {updated_product['data']['regular_price']}")
    # DELETE: Remove the product
    wcapi.delete(f"products/{product_id_to_update}", params={'force': 'true'})
    print(f"\n--- Deleted Product ID {product_id_to_update} ---")
except Exception as e:
    print(f"An error occurred: {e}")

Advanced Topics & Best Practices

  • Pagination: The API returns results in pages (default is 10 per page). Always check the total_pages and current_page in the response headers (X-WP-TotalPages, X-WP-Total) and loop through pages if you need all data.
  • Rate Limiting: The API has rate limits. If you make too many requests in a short period, you'll get a 429 Too Many Requests error. Implement a small delay (time.sleep(1)) between requests if you're doing bulk operations.
  • Error Handling: Always check the HTTP status code and the response body for error messages from WooCommerce (e.g., validation errors).
  • Asynchronous Requests: For high-performance tasks (e.g., syncing thousands of products), consider using an asynchronous library like httpx or aiohttp to run many API calls concurrently.
  • Webhooks: For real-time updates (e.g., a new order is placed), set up WooCommerce Webhooks. Your Python script can have a simple web server (using Flask or FastAPI) that receives a POST request from WooCommerce whenever an event occurs. This is far more efficient than polling the API constantly.
分享:
扫描分享到社交APP
上一篇
下一篇