Writing Plugins

Author: PyBlosxom Development Team
Version: dev_writing_plugins.txt 1052 2007-06-20 19:42:58Z willhelm
Copyright: This document is distributed under the MIT license.

Contents

Summary

This chapter covers a bunch of useful things to know when writing PyBlosxom plugins. This chapter, moreso than the rest of this manual, is very much a work in progress.

FIXME - absorb from wiki, Will's tips, and tutorials

Things that all plugins should have

All plugins should have a docstring at the top of the file that describes in detail:

  1. what the plugin does
  2. how to install it
  3. how to configure it
  4. the license the plugin is distributed under
  5. and any copyright information you have

For example, this is at the top of Will's wbgpager plugin:

"""
Quickly written plugin for paging long index pages.

PyBlosxom uses the num_entries configuration variable to prevent
more than num_entries being rendered by cutting the list down
to num_entries entries.  So if your num_entries is set to 20, you
will only see the first 20 entries rendered.

The wbgpager overrides this functionality and allows for paging.
It does some dirty stuff so that PyBlosxom doesn't cut the list down
and then wbgpager cuts it down in the prepare callback later down
the line.

To install wbgpager, do the following:

  1. add "wbgpager" to your load_plugins list variable in your
     config.py file--make sure it's the first thing listed so
     that it has a chance to operate on the entry list before
     other plugins.
  2. add the $page_navigation variable to your head or foot
     (or both) templates.  this is where the page navigation
     HTML will appear.


Here are some additional configuration variables to adjust the
behavior:

  wbgpager_count_from
    datatype:       int
    default value:  0
    description:    Some folks like their paging to start at 1--this
                    enables you to do that.

  wbgpager_previous_text
    datatype:       string
    default value:  <<
    description:    Allows you to change the text for the prev link.

  wbgpager_next_text
    datatype:       string
    default value:  >>
    description:    Allows you to change the text for the next link.

  wbgpager_linkstyle
    datatype:       integer
    default value:  0
    description:    This allows you to change the link style of the paging.
                    style 0:  [1] 2 3 4 5 6 7 8 9 ... >>
                    style 1:  Page 1 of 4 >>


That should be it!


Note: This plugin doesn't work particularly well with static rendering.
The problem is that it relies on the querystring to figure out which
page to show and when you're static rendering, only the first page
is rendered.  This will require a lot of thought to fix.  If you are
someone who is passionate about fixing this issue, let me know.


Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Copyright 2004, 2005, 2006 Will Guaraldi
"""

All plugins should have the following module-level variables defined in them just after the docstring:

For example:

__author__      = "Will Guaraldi - willg at bluesock dot org"
__version__     = "version 1.5 2006-01-15"
__url__         = "http://www.bluesock.org/~willg/pyblosxom/"
__description__ = "Splits long indexes into multiple pages."

After that, you should have a verify_installation section that verifies that the plugin is configured correctly. As of PyBlosxom 0.9, the pyblosxom.cgi is able to test your PyBlosxom installation. It verifies certain items in your config.py file and also loads all the plugins and lets them verify their configuration as well. First it tells you your Python version, OS name, and then proceeds to verify your config properties (did you specify a valid datadir? does it exist?...) and then initializes all your plugins and executes verify_installation(request) on every plugin you have installed that has the function.

As a plugin developer, you should add a verify_installation function to your plugin module. Something like this (taken from pycategories):

def verify_installation(request):
    config = request.getConfiguration()

    if not config.has_key("category_flavour"):
        print "missing optional config property 'category_flavour' "
        print "which allows you to specify the flavour for the category "
        print "link.  refer to pycategory plugin documentation for more "
        print "details."
    return 1

This gives you (the plugin developer) the opportunity to walk the user through configuring your highly complex, quantum-charged, turbo plugin in small baby steps without having to hunt for where their logs might be.

So check the things you need to check, print out error messages (informative ones), and then return a 1 if the plugin is configured correctly or a 0 if it's not configured correctly.

This is not a substitute for the user to read the installation instructions. It should be a really easy way to catch a lot of potential problems without involving the web server's error logs and debugging information being sent to a web-browser and things of that nature.

Here's another example of verify_installation from Will's wbgpager plugin:

def verify_installation(request):
    config = request.getConfiguration()
    if config.get("num_entries", 0) == 0:
        print "missing config property 'num_entries'.  wbgpager won't do "
        print "anything without num_entries set.  either set num_entries "
        print "to a positive integer, or disable the wbgpager plugin."
        print "see the documentation at the top of the wbgpager plugin "
        print "code file for more details."
        return 0

    return 1

How to log messages to a log file

First you need to get the logger instance. After that, you can call debug, info, warning, error and critical on the logger instance. For example:

from pyblosxom import tools

def cb_prepare(args):
   ...
   logger = tools.getLogger()
   logger.info("blah blah blah...")

   try:
      ...
   except Exception, e:
      logger.error(e)

How to store plugin state between callbacks

The easiest way to store state between callbacks is to store the data in the data dict of the Request object. For example:

STATE_KEY = "myplugin_state"

def cb_date_head(args):
   request = args["request"]
   data = request.getData()

   if data.has_key(STATE_KEY) and data[STATE_KEY]["blah"] == "blahblah":
      ...


def cb_filelist(args):
   request = args["request"]
   data = request.getData()

   data[STATE_KEY] = {}
   data[STATE_KEY]["blah"] = "blahblah"

How to implement a callback

If you want to implement a callback, you add a function corresponding to the callback name to your plugin module. For example, if you wanted to modify the Request object just before rendering, you'd implement cb_prepare like this:

def cb_prepare(args):
    pass

Obviously, since we have pass we're not actually doing anything here, but when the user sends a request and PyBlosxom handles it, this function in your plugin will get called when PyBlosxom runs the prepare callback.

Each callback passes in arguments through a single dictionary. Each callback passes in different arguments and expects different return values. Check the architecture chapter for a list of all the callbacks that are available, their arguments, and return values.

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
    title
    """
    entrydata = {}

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

    # 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

Writing a preformatter plugin

FIXME - need more about preformatters here

A typical preformatter plugin looks like this:

def cb_preformat(args):
    if args['parser'] == 'linebreaks':
        return parse(''.join(args['story']))

def parse(text):
    # A preformatter to convert linebreak to its HTML counterpart
    text = re.sub('\\n\\n+','</p><p>',text)
    text = re.sub('\\n','<br />',text)
    return '<p>%s</p>' % text