Skip to content

Instantly share code, notes, and snippets.

@Danielericking
Forked from alexpos/Example 1
Created September 26, 2020 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danielericking/ec95a5bed4f7d36a40d50f98f3d747a2 to your computer and use it in GitHub Desktop.
Save Danielericking/ec95a5bed4f7d36a40d50f98f3d747a2 to your computer and use it in GitHub Desktop.
Several examples how to use python-wordpress-xmlrpc to post to wordpress
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
#authenticate
wp_url = "http://192.168.50.100:8051/xmlrpc.php"
wp_username = "admin"
wp_password = "12"
wp = Client(wp_url, wp_username, wp_password)
#post and activate new post
post = WordPressPost()
post.title = 'My post'
post.content = 'This is a wonderful blog post about XML-RPC.'
post.post_status = 'publish'
post.terms_names = {
'post_tag': ['test', 'firstpost'],
'category': ['Introductions', 'Tests']
}
wp.call(NewPost(post))
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost
#authenticate
wp_url = "http://192.168.50.100:8051/xmlrpc.php"
wp_username = "admin"
wp_password = "12"
wp = Client(wp_url, wp_username, wp_password)
def find_id(title):
offset = 0
increment = 10
while True:
filter = { 'offset' : offset }
p = wp.call(GetPosts(filter))
if len(p) == 0:
break # no more posts returned
for post in p:
if post.title == title:
return(post.id)
offset = offset + increment
return(False)
#newish post
post = WordPressPost()
post.id = 590
post.title = 'My post'
post.content = 'This is an even more wonderful blog post about XML-RPC.'
post.post_status = 'publish'
post.terms_names = {
'post_tag': ['test', 'firstpost'],
'category': ['Introductions', 'Tests']
}
if post.id:
wp.call(EditPost(post.id, post))
else:
post_id=find_id(post.title)
if post_id:
print "Sorry, we already have such a post(-title):", post_id
else:
wp.call(NewPost(post))
#!/usr/bin/python
#
# author: alexander.poslavsky@gmail.com
# version: 1.0.3 (14-12-2012)
# license: BSD
#
# post to wordpress from the command-line
#
# Changelog:
# - 1.0.0 dependencies: Install from PyPI using easy_install python-wordpress-xmlrpc or pip install python-wordpress-xmlrpc.
# - 1.0.1 load config from file
# - 1.0.2 added [TOC] and headerid http://packages.python.org/Markdown/extensions/index.html
# - 1.0.3 fix odd charcters (decode('utf-8'))
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost
import datetime, xmlrpclib
import markdown
import argparse
import sys
import ConfigParser, os
config = ConfigParser.ConfigParser()
config.read(['.md2wp.cfg', os.path.expanduser('~/.md2wp.cfg')])
def ConfigSectionMap(section):
dict1 = {}
options = config.options(section)
for option in options:
try:
dict1[option] = config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
print("exception on %s!" % option)
dict1[option] = None
return dict1
def mdimport():
md = markdown.Markdown(extensions = ['extra', 'meta','headerid','toc'])
post.content = md.convert(rawText)
# https://github.com/maxcutler/python-wordpress-xmlrpc/blob/master/wordpress_xmlrpc/wordpress.py
if 'id' in md.Meta:
post.id = md.Meta['id']
else:
post.id = False
if 'title' in md.Meta:
post.title = md.Meta['title'][0]
post.terms_names = {}
if 'category' in md.Meta:
post.terms_names['category'] = md.Meta['category']
if 'tags' in md.Meta:
post.terms_names['post_tag'] = md.Meta['tags']
post.dateCreated = xmlrpclib.DateTime(datetime.datetime.strptime("2009-10-20 21:08", "%Y-%m-%d %H:%M"))
return md
def find_id(title):
offset = 0
increment = 10
while True:
filter = { 'offset' : offset }
allposts = wp.call(GetPosts(filter))
if len(allposts) == 0:
break
for p_item in allposts:
if p_item.title == title:
return(p_item.id)
offset = offset + increment
return(False)
def post2wp():
if post.id:
wp.call(EditPost(post.id, post))
if args.verbose:
print "Updated post"
else:
post_id=find_id(post.title)
if post_id:
if args.updateid:
update_id(post_id)
else:
print "Sorry, we already have such a post (or at least a post with such a title):", post_id,", use -u to update the id"
else:
if args.publish:
post.post_status = 'publish'
else:
post.post_status = 'draft'
post_id = wp.call(NewPost(post))
if args.verbose:
print "Placed new post ( %s )" % post_id
update_id(post_id)
def update_id(post_id):
try:
f = open(args.filePath, "w")
f.write("id: "+post_id+"\n")
f.write(rawText)
f.close()
if args.verbose:
print "Updated the post-id"
except Exception, e:
print("Sorry, could not update post with the id")
exit(1)
def main():
global args, rawText, post, wp
parser = argparse.ArgumentParser(description='Work on your blog, posts default to draft')
parser.add_argument('filePath', nargs='?')
parser.add_argument('--updateid','-u', dest='updateid', action='store_true',
help='update the id of the post by title')
parser.add_argument('--publish','-p', dest='publish', action='store_true',
help='publish straight away (don\'t save as draft)')
parser.add_argument('--config','-c', dest='config', action='store',
help='use this configuration')
parser.add_argument('--list-config','-l', dest='list_config', action='store_true',
help='list configurations')
parser.add_argument('--verbose','-v', dest='verbose', action='store_true',
help='print return messages')
parser.add_argument('--debug','-d', dest='debug', action='store_true',
help='print all messages')
args = parser.parse_args()
if args.debug:
args.verbose=True
print(parser.parse_args())
try:
settings = ConfigSectionMap(args.config)
wp_url = settings['wp_url']
wp_username = settings['wp_username']
wp_password = settings['wp_password']
if args.debug:
print "Posting to %s with user: %s" % (wp_url, wp_username)
wp = Client(wp_url, wp_username, wp_password)
except:
print("Cannot find configuration!")
exit(1)
if args.list_config:
print config.sections()
exit()
if args.filePath is None:
parser.print_help()
exit(1)
try:
myFile = open(args.filePath, "r")
rawText = myFile.read()
rawText = rawText.decode('utf-8')
myFile.close()
except Exception, e:
print("Sorry, could not open your markdown file")
exit(1)
post = WordPressPost()
md=mdimport()
if args.debug:
print md.Meta
post2wp()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment