杰瑞科技汇

Python wordpresslib如何实现WordPress文章发布?

Of course! Let's dive deep into python-wordpresslib.

Python wordpresslib如何实现WordPress文章发布?-图1
(图片来源网络,侵删)

What is python-wordpresslib?

python-wordpresslib is a Python library designed to interact with the WordPress REST API. It provides a high-level, object-oriented interface to perform common administrative tasks on a WordPress site programmatically.

Think of it as a "remote control" for your WordPress website. Instead of logging into the admin dashboard, you can write a Python script to:

  • Create, read, update, and delete (CRUD) posts and pages.
  • Manage media (upload images, etc.).
  • Work with custom post types and taxonomies (categories, tags).
  • Manage comments.
  • Interact with users and terms.

It's built on top of the popular requests library, making it robust and easy to use.


Key Features

  • Easy Authentication: Supports Basic Auth, Application Passwords (recommended), and OAuth 1.0a.
  • Comprehensive Coverage: Covers most core WordPress entities (Posts, Pages, Media, Comments, Users, etc.).
  • Object-Oriented: Interacting with posts, for example, feels like working with a Python object, not raw JSON data.
  • Error Handling: Provides clear exceptions for common API errors (like authentication failures or 404s).
  • Asynchronous Support: Has an optional asyncio-based client for high-performance applications.

Installation

It's as simple as using pip:

Python wordpresslib如何实现WordPress文章发布?-图2
(图片来源网络,侵删)
pip install wordpresslib

Getting Started: A Practical Guide

Before you start, you need to ensure your WordPress site has the REST API enabled. It is by default on modern WordPress versions (since 4.7).

Authentication (The Most Important Step)

There are a few ways to authenticate. Application Passwords is the modern, secure standard.

Method A: Application Passwords (Recommended)

  1. In your WordPress admin dashboard, go to Users -> Profile.
  2. Scroll down to the Application Passwords section.
  3. Give your new password a name (e.g., "Python Script") and click "Add New Application Password".
  4. WordPress will generate a unique password for you. Copy this password immediately! You won't be able to see it again.

Now you have:

Python wordpresslib如何实现WordPress文章发布?-图3
(图片来源网络,侵删)
  • Username: Your WordPress username.
  • Password: The generated application password.

Method B: Basic Auth (Less Secure)

This uses your standard WordPress username and password. It's simpler but less secure, especially over HTTP. Only use this for local development or trusted environments.

Connecting to Your WordPress Site

Let's write a simple script to connect. We'll use the recommended Application Passwords method.

import wordpresslib
# --- Configuration ---
WP_URL = "https://your-wordpress-site.com"
WP_USERNAME = "your_wp_username"
WP_PASSWORD = "your_generated_application_password" # PASTE IT HERE!
# --- Create the Client ---
# The client handles the connection and authentication for you.
wp = wordpresslib.WordPressClient(WP_URL, WP_USERNAME, WP_PASSWORD)
# Optional: Verify the connection
try:
    user = wp.get_user()
    print(f"Successfully connected as: {user.name}")
except Exception as e:
    print(f"Connection failed: {e}")

Common Use Cases (with Code Examples)

Now that we're connected, let's do something useful.

Example 1: Creating a New Blog Post

This is a classic use case. We'll create a new post and publish it.

# Make sure the 'wp' client from the previous example is initialized
# Create a new post object
post = wordpresslib.Post()= "My First Post from Python!"
post.content = "This is the amazing content for my post, written entirely with a Python script. Isn't it awesome?"
post.status = "publish"  # Options: 'draft', 'pending', 'publish'
# Create the post on the WordPress site
try:
    created_post = wp.create_post(post)
    print(f"Post created successfully! Post ID: {created_post.id}")
    print(f"View it here: {WP_URL}/?p={created_post.id}")
except Exception as e:
    print(f"Error creating post: {e}")

Example 2: Uploading an Image (Media)

You can easily upload images and then use them in your posts.

# Make sure the 'wp' client is initialized
image_path = "path/to/your/image.jpg" # <-- CHANGE THIS to your image file
try:
    # The upload_media function returns the media object
    media = wp.upload_media(image_path)
    print(f"Image uploaded successfully! Media ID: {media.id}")
    print(f"Image URL: {media.source_url}")
    # Now, let's create a post and use this image
    post = wordpresslib.Post()
    post.title = "A Post with an Image"
    post.content = f"Check out this cool image I uploaded! <img src='{media.source_url}' alt='Uploaded Image' />"
    post.status = "publish"
    # You can also attach the media to the post
    post.featured_media = media.id
    created_post = wp.create_post(post)
    print(f"Post with image created! Post ID: {created_post.id}")
except Exception as e:
    print(f"Error uploading image or creating post: {e}")

Example 3: Reading and Updating a Post

Let's find a post and change its title.

# Make sure the 'wp' client is initialized
try:
    # Get a specific post by its ID
    post_id = 123 # <-- CHANGE THIS to an existing post ID on your site
    post_to_update = wp.get_post(post_id)
    if post_to_update:
        print(f"Found post: '{post_to_update.title}' (ID: {post_to_update.id})")
        # Modify the post object
        post_to_update.title = "This Title Was Updated by Python!"
        # Update the post on the site
        updated_post = wp.update_post(post_to_update)
        print(f"Post updated successfully! New title: {updated_post.title}")
    else:
        print(f"Post with ID {post_id} not found.")
except Exception as e:
    print(f"Error updating post: {e}")

Example 4: Deleting a Post

Simple and straightforward.

# Make sure the 'wp' client is initialized
post_id_to_delete = 456 # <-- CHANGE THIS to the ID of the post you want to delete
try:
    # The delete_post function returns True on success
    if wp.delete_post(post_id_to_delete):
        print(f"Post with ID {post_id_to_delete} has been deleted.")
    else:
        print(f"Could not delete post with ID {post_id_to_delete}. It might not exist.")
except Exception as e:
    print(f"Error deleting post: {e}")

Advanced Usage: Async Client

For applications that need to make many API calls quickly (e.g., a web scraping tool or a high-frequency sync), the async client is a much better choice as it doesn't block the execution while waiting for a response.

import asyncio
import wordpresslib
async def main():
    WP_URL = "https://your-wordpress-site.com"
    WP_USERNAME = "your_wp_username"
    WP_PASSWORD = "your_generated_application_password"
    # Create an async client
    wp = wordpresslib.AsyncWordPressClient(WP_URL, WP_USERNAME, WP_PASSWORD)
    # Create multiple posts concurrently
    tasks = []
    for i in range(5):
        post = wordpresslib.Post()
        post.title = f"Async Post Number {i+1}"
        post.content = f"This is content for async post {i+1}."
        post.status = "publish"
        tasks.append(wp.create_post(post))
    # Execute all tasks at once
    created_posts = await asyncio.gather(*tasks)
    for post in created_posts:
        print(f"Async post created: ID {post.id}, Title: {post.title}")
    # Close the client session when done
    await wp.close()
# Run the async main function
asyncio.run(main())

Official Resources

分享:
扫描分享到社交APP
上一篇
下一篇