xmlrpc
我喜欢用命令行做一些事情,写一篇文章,发布到这个博客,也是一样。最好的方法应该能够使用文本编辑器写好,然后从命令行直接发布,比如
[plain light=”true”]
blog hello.txt
blog -m hello.txt
blog -d post_id
[/plain]
-m 是修改,-d是删除,这样就方便多了
wordpress的设置中有个Remote Publishing项,支持atom publishing protocol和xml-rpc,我对atom不太熟悉,不过xml-rpc以前用过,便想试一试,python很适合这种实验性质的程序。wordpresss是用xmlrpc.php文件支持远程调用的,看了看这个文件,在客户端写了几个脚本尝试一下,感觉挺简单的,就写了下面段代码,丑是丑了点儿,不过能满足我的需求就够了。
[python]
import sys;
import xmlrpclib;
class Blog:
"""just a simple interface for xmlrpc call"""
def __init__(self,url,name,pwd):
self.name = name;
self.pwd = pwd;
self.sv = xmlrpclib.ServerProxy(url);
def newPost(self, cont):
self.sv.metaWeblog.newPost(1, self.name, self.pwd, cont, True);
def editPost(self, pid, newpost):
self.sv.metaWeblog.editPost(pid, self.name, self.pwd, newpost, True);
def delPost(self, pid):
self.sv.metaWeblog.deletePost(0, pid, self.name, self.pwd, True);
def parse_content(ct):
bcont = {};
ct = ct.decode("gbk");
head,cont = ct.split("nn",1);
for line in head.split("n"):
k,v = line.split(":");
if k.startswith("categories"):
bcont[k] = v.split(",");
else:
bcont[k] = v;
bcont["description"] = cont;
return bcont;
def new_from_commandline(b):
ct = sys.stdin.read();
return b.newPost(parse_content(ct));
def new_from_file(b,fname):
ct = open(fname).read();
return b.newPost(parse_content(ct));
def modify_from_commandline(b,pid):
ct = sys.stdin.read();
return b.editPost(pid, parse_content(ct));
def modify_from_file(b, pid, fname):
ct = open(fname).read();
return b.editPost(pid, parse_content(ct));
def delete_post(b,pid):
b.delPost(pid);
def main():
b = Blog("http://localhost/wordpress/xmlrpc.php","username","password");
if len(sys.argv)==1:
new_from_commandline(b);
elif len(sys.argv)==2 and not sys.argv[1].startswith("-"):
new_from_file(b,sys.argv[1]);
elif len(sys.argv)==3:
if sys.argv[1].startswith("-m"):
modify_from_commandline(b,int(sys.argv[2]));
elif sys.argv[1].startswith("-d"):
delete_post(b,int(sys.argv[2]));
elif len(sys.argv)==4:
modify_from_file(b,int(sys.argv[2]),sys.argv[3]);
if __name__ == ‘__main__’:
main();
[/python]
现在很喜欢python,给人一种优雅简约的感觉,心里想什么,顺手就能写出来。