Python: XML-RPC Requests

Tinkering with Python xmlrpclib, in this case for updating a WordPress blog from the command line. Using Python 2.7.6 here. xmlrpclib is included with Python 2.7, but if you need it, install with Pip.

import xmlrpclib

server = xmlrpclib.Server("http://www.mywordpress.com/xmlrpc.php", verbose=True)
user = "my_username"
password = "my_password"

#List available methods supported by WordPress
methods = server.system.listMethods()
for method in methods:
    print method

def wpGetComments():
    """ Get comments from a given WP post """
    """ https://codex.wordpress.org/XML-RPC_WordPress_API/Comments#wp.getComments """
    listComments = server.wp.getComments(0, user, password, {'post_id': 1302, 'number': 10})
    for comment in listComments:
        print "Status: {0}nAuthor: {1}nDate: {2}nComment: {3}nn".format(comment["status"], 
            comment["author"], 
            comment["date_created_gmt"], 
            comment["content"][:50])
    
wpGetComments()

def wpGetPosts():
    """ Get all the posts from your WP blog """
    """ https://codex.wordpress.org/XML-RPC_WordPress_API/Posts """
    listPosts = server.wp.getPosts(0, user, password, {'post_status': 'publish'})
    for post in listPosts:
        print "Title: {0}nAuthor: {1}nDate: {2}nText: {3}nn".format(post["post_title"], 
        post["post_author"], 
        post["post_date"], 
        post["post_content"][:50])        
        
wpGetPosts()

def wpCreatePost():
    """ Create a new post on your WP blog """
    """ https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost """
    createPost = server.wp.newPost(0, user, password, 
                                  {'post_type': 'post', 'post_status': 'draft', 
                                   'post_author': 1, 'post_title': 'Test XMLRPC', 
                                   'post_content': 'abcdefghijklm'})
    
    # WordPress returns post ID if successful
    if server.methodReponse.value is not None:
        # Needs better logic but you get the point
        print "Post created!"

wpCreatePost()

def wpEditPost():
    """ Edit an existing post on your WP blog """
    """ https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.editPost """
    editPost = server.wp.editPost(0, user, password, 1343,  
                   {'post_title': 'Create WordPress Posts from an RSS Feed'})
               
    # WordPress returns 1 if successful    
    if server.methodResponse.value is not None:
        # Needs better logic but you get the point
        print "Post edited!"                              
                                  
wpEditPost()

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *