Continúo aprendiendo algo de Python (para variar un poco de lenguajes) y de paso investigando un poco con API's y herramientas para WordPress. WordPress permite manejar tus entradas en el blog sin necesidad de conectarte al propio WordPress desde la interfaz web que ellos ofrecen (ya sabéis: wp-admin). Existen infinidad de herramientas para postear (herramientas de escritorio). Estas herramientas aprovechan que WordPress implementa xmlrpc, interfaz XML mediante la que podemos "hablar" con nuestro WordPress.
Python tiene una librería muy chula para poder manejar xmlrpc, llamada xmlrpclib. Así que con estos ingredientes el trabajito estaba servido. He implementado un pequeño programita en python que nos permitirá postear en nuestro wordpress desde la línea de comandos. Parece poco útil pero, y de verdad que lo he probado, es bastante interesante para hacer post rápidos, sobre todo si no te apetece estar haciendo login en WordPress, llendo a "Write" y demás zarandajas. La herramienta está en una fase muy beta, y de momento sólo permite postear, indicando el título del post y el contenido. Pero poco a poco la iré completando, y de esta forma seguiré aprendiendo un poco más de python, lenguaje que me está sorprendiendo sobremanera por su rapidez de desarrollo y la cantidad de librerías de clases ya implementadas.
Para ejecutar el programita:
./wp.py --server=direccion_a_wordpress --user=usuario --pass=password --title=titulo_del_post --post=cuerpo_del_post
Por ejemplo:
./wp.py --server="http://midireccion.com/wordpress" --user="onofre" --pass="foo" --title="Este es mi primer post" --post="bla bla..."
Respecto al código comentaré que la parte más interesante es cuando creamos la instancia del objeto xmlrpclib.Server:
server = xmlrpclib.Server(server + "/xmlrpc.php")
y cuando hacemos realmente la operació de "Post":
res = server.metaWeblog.newPost("1", user, passwd, post.toStructure(), "1")
Probad en vuestros WordPress esto:
http://direccion_a_mi_wordpress.com/xmlrpc.php
Ahí tenéis ubicado el servicio xmlrpc de vuestro wordpress...
Podéis descargar el programita aquí. También dejo directamente el código por si os apetece echarle una ojeada sin necesidad de descargarlo:
#!/usr/bin/python
#
# Simple command line tool for managing WordPress Post
# Author: Juanjo Escribano
# Version: 0.1 (beta)
# License: GPL v3
# Notes : by the moment it only supports "New Post" operation
#
import xmlrpclib
from datetime import datetime
import getopt
import sys
class Post:
"""
This class will save the post info
Private Attributes :
_post_title : the title of the post
_post_description : the body of the post
_post_date : date timestamp of the post (now())
"""
_post_title = ""
_post_description = ""
_post_date = ""
def __init__(self, post_title, post_description):
"""
constructor of the class
"""
self._post_title = post_title
self._post_description = post_description
actual_date = datetime.now()
self._post_date = actual_date.year.__str__() + " " + actual_date.month.__str__() + " " + actual_date.day.__str__()
def toStructure(self):
"""
Creates an structure with the information. The elements of the struct
are defined as elements of
I don't support all of them
"""
post_structure = {
"title" : self._post_title,
"description" : self._post_description,
"pubDate" : self._post_date
}
return post_structure
def main():
"""
Main funcion. Parse the parameters and do the job
"""
user = ""
passwd = ""
server = ""
title = ""
post = ""
options, args = getopt.getopt(sys.argv[1:], "", ["server=", "user=", "pass=", "title=", "post="])
for opt,val in options:
if opt == "--user":
user = val
elif opt == "--pass":
passwd = val
elif opt == "--title":
title = val
elif opt == "--post":
post = val
elif opt == "--server":
server = val
# user and server are not optative
if user == "" or server == "":
print "Syntax: " + sys.argv[0] + "
sys.exit(0)
# init a xmlrpclib.Server object
server = xmlrpclib.Server(server + "/xmlrpc.php")
# Create a Post Object with title and post. Then try to post it
post = Post(title, post)
try:
res = server.metaWeblog.newPost("1", user, passwd, post.toStructure(), "1")
except xmlrpclib.ProtocolError, err:
print "Error conecting with server"
sys.exit(-1)
except xmlrpclib.Fault, err:
print "Error :" + err.__str__()
sys.exit(-1)
except err:
print "Error :" + err.__str__()
sys.exit(-1)
print "Post id: " + res
# Start here
if __name__ == "__main__":
main()