11.5. Writing an entryparser

Entry parsing functions take in a filename and the Request object. They then open the file and parse it out. The can call cb_preformat and cb_postformat as they see fit. They should return a dict containing at least "title" and "story" keys. The "title" should be a single string. The "story" should be a list of strings (with \n at the end).

Here's an example code that reads *.plain files which have the title as the first line, metadata lines that start with # and then after all the metadata the body of the entry:

import os
def cb_entryparser(entryparsingdict):
    Register self as plain file handler
    entryparsingdict['plain'] = parse
    return entryparsingdict

def parse(filename, request):
    We just read everything off the file here, using the filename as
    entrydata = {}

    f = open(filename, "r")
    lines = f.readlines()

    # strip off the first line and use that as the title.
    title = lines.pop(0).strip()
    entrydata['title'] = title

    # absorb meta data lines which begin with a # and consist
    # of a name and a value
    while lines and lines[0].startswith("#"):
        meta = lines.pop(0)
        meta = meta[1:].strip()     # remove the hash
        meta = meta.split(" ", 1)
        entrydata[meta[0].strip()] = meta[1].strip()

    # join the rest of the lines as the story
    story = ''.join(lines)
    entrydata["story"] = "".join(lines)

    return entrydata