MetaWeblog & Django
Greg Abbas

As I mentioned previously, I wanted to integrate Ecto with my new Django-based blog using the "MetaWeblog" remote procedure call API. With an XMLRPC implementation ready to go, the remaining task is to write MetaWeblog methods and hook them up to my blog model. The model is pretty straightforward; for instance, here are the fields for "Post" object:

class Post(models.Model):
    title = models.CharField(maxlength=200)
    slug = models.SlugField(prepopulate_from=('title',))
    pub_date = models.DateTimeField('date published', blank=True, null=True)
    create_date = models.DateTimeField('date created', auto_now_add=True,
        blank=True, null=True)
    update_date = models.DateTimeField('date updated', auto_now=True,
        blank=True, null=True)
    body = models.TextField()
    tags = models.ManyToManyField(Tag)
    author = models.ForeignKey(User)
    status = models.CharField(maxlength=32, choices=STATUS_CHOICES,
        radio_admin=True, default='Draft')

The MetaWeblog API is pretty well documented, but has some features that I'm not quite ready to tackle. For instance, I only have a single user with a single blog, you have to be a "super user" to edit it (no sophisticated authorization scheme yet), and I haven't done media objects (e.g., images) yet either.

Most every method takes "username" and "password" parameters, so I wrote an "authenticated" wrapper function to convert them to a user object (and throw an exception if there are any authentication or authorization issues). Then the various methods are short, because the Django database/model API makes things easy. For instance, the method to get information about a blog post (given a post id) is called "getPost". My implementation looks up the post object by id, and then calls a function to turn it into the struct that MetaWeblog requires:

@public
@authenticated()
def metaWeblog_getPost(user, postid):
    post = Post.objects.get(id=postid)
    return post_struct(post)

def post_struct(post):
    link = full_url(post.get_absolute_url())
    categories = post.tags.all()
    struct = {
        'postid': post.id,
        'title': post.title,
        'link': link,
        'permaLink': link,
        'description': post.body,
        'categories': [c.name for c in categories],
        'userid': post.author.id,
        }
    if post.pub_date:
        struct['dateCreated'] = format_date(post.pub_date)
    return struct

where full_url urljoin's the web site host name ("www.allyourpixel.com") to a URL, and format_date calls xmlrpclib to (you guessed it) turn a date into a string. Here's the whole file: metaweblog.py. It's not a complete application, but hopefully it'll be easy enough to customize for what your doing.