Python wordpress自动发布

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: Python wordpress自动发布

因为wordpress自带XMLRPC功能,所以,我们可以通过Python的XMLRPC接口进行wordpress的操作。

详情参考:http://python-wordpress-xmlrpc.readthedocs.io/en/latest/

最后贴下我的代码:

# -*- coding=utf-8 -*-
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc import WordPressPage
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts
import sys
import chardet
import MySQLdb

#build wordpress connection
wp = Client('http://localhost/cms-develop/wordpress/wordpress/xmlrpc.php', 'admin', 'admin');
post = WordPressPost()

try:
	#python mysql operation
	dbconn = MySQLdb.connect(host = "127.0.0.1", user = "root", passwd = "root", db = "mmpic", charset = 'utf8')
	cursor = dbconn.cursor()
	cursor.execute("SELECT DISTINCT title FROM mmonly limit 0, 10")
	rows = cursor.fetchall()
	for row in rows:
		print "title = %s" % (unicode(row[0], 'utf-8'))
		#fencoding = chardet.detect(row[0])
		post.title = row[0]
		post.post_status = 'publish'
		post.terms_names = {}
		data = {}
		up_filename = ""
		post.content = ""
		attachment_id = 0
		#post.thumbnail = attachment_id
		cursor.execute("SELECT filename, description, category, foldername FROM mmonly WHERE title = %s ORDER BY description desc", row[0])
		child_rows = cursor.fetchall()
		current = 0
		count = cursor.rowcount
		for prow in child_rows:
			print "filename = %s, description = %s, category = %s, foldername = %s" % (prow[0], unicode(prow[1], 'utf-8'), unicode(prow[2], 'utf-8'), prow[3])
			current += 1;
			print "current is %d" % current
			nextpagestr = ""
			if (current == 1) :
				post.terms_names = {
					'post_tag': [prow[2]],
					'category': [prow[2]],
				}
				data = {
					'name' : prow[0],
					'type': 'image/jpeg',  # mimetype
				}
				up_filename = r'F:/aikanmeizi/' + prow[3] + "/" + prow[0]
				print "up_filename:" + up_filename
				with open(up_filename, 'rb') as img:
					data['bits'] = xmlrpc_client.Binary(img.read())
				response = wp.call(media.UploadFile(data))
				attachment_id = response['id']
				post.thumbnail = attachment_id
			if (current == count):
				nextpagestr = ""
			else:
				nextpagestr = "<!--nextpage-->"
			post.content += prow[1] + "<img src=http://192.168.1.2/cms-develop/wordpress/wordpress/" + prow[3] + "/" + prow[0] + " /><br />" + nextpagestr
			
		post.id = wp.call(posts.NewPost(post))
	print "Number of rows returned: %d" % cursor.rowcount

	cursor.close()
	dbconn.close()
except MySQLdb.Error,e:
	print "Mysql Error %d: %s" % (e.args[0], e.args[1])
原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: Python wordpress自动发布

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: