Posts Tagged ‘Python


PyML(Python Markup Language) template engine

I know it’s been a while since my last post. I’ve been busy with setting up and pulling down I decided to go for another blog system), I’ve spend a good deal of time working on PyMouse and worked on some projects for myself and for clients.

I want to share one of those projects with you. I decided to make a CMS like Jekyll and Hyde(not the book!), since I liked neither of the previous systems. So like a lot of people who like reinventing wheels I started to look for a nice markup language for the user and a nice template language for the designer.

I choose for Markdown right away, end of story here…

Because of the little experience I have with Pylons I looked ad Genshi and Mako initially(can’t help the Chinese feeling these names give me). Personally the ugly tags in most template languages make me run away, so I threw Make out of the window, together with all the other ugly-tag-based languages.

I like the idea of working with valid XML attributes for templating, so I started of with Genshi initially, especially since speed isn’t a major point for a static blog!

Days later I came across this wiki page on the Python website:

Looking at Dirty I remembered my own attempts to write a template language implemented as Python objects(extending dict, for free functionality).

The problem with writing such a thing is described in the code below, I mailed the developer of Dirty about how he solved the problem — he didn’t.

>>> def div(*content, **attributes):
...     pass
>>> div("hello world!", id="test") # Doesn't html have the attributes first!? Ugly!
>>> def div(**attributes, *content): # Not allowed!
  File "", line 1
    def div(**attributes, *content):
SyntaxError: invalid syntax
>>> def div(atributes, *content):
...     pass
>>> div({'id':'test'}, "hello world!") # Even uglier!

But then I came up with this slightly brilliant solution:

When you define __call__ on a class it allows you to call the class, no big deal, eh? Wrong! It allows you to write this:

    head( # No atributes
        title("Hello world")
            "Hi", br(),
            "How are you?"
        img(src="test.img", alt="just a test") # No content
            *[li(c) for c in xrange(10)] # Now that is cool!

In short PyML is a pure Python combination of a string and a dict looking like html when written and printed!

You can do all sorts of things with this that you normally do with dictionaries, strings and lists, like sorting and filtering them, change a p into a div or getting/setting attributes later with square brackets. You could define functions to return a snippet or you could include templates into others. If you’re finished with them, just print the object!

Oh, about the speed? Quite good for my hobby project! (Unreliable micro benchmark ahead!)

Render time Engine
0.03160 PyML
0.50618 Genshi
0.01813 Mako

You can get it here if you want! Or wait for my complete CMS of course…


First library for my CMS started!

I finaly started coding for my CMS. I’m not sure if I’m already up to the job, but I’ll find out soon enough. The first library is part of the template engine. I don’t want people to write crap HTML, so I wrote a library that can generate strict XHTML with python code that is as similar to html as possible, see below for an example.

The big question remains, what to do with user content, even valid XHTML theme break if someone pastes his Word HTML in the editor. I plan on using BeautifulSoup to parse the user code, strip off the ‘invalid’ tags like <i>, <u>, <iframe>, etc… and feed it to my XHTMLLib. The even cooler part is that you could use your old HTML theme, feed it to my lib and fill/replace the content. With the latest version this became even easyer because I added some sort of xpath support(absolute paths only, but with attribute selection).

I present to you, my first lib!

Link: Also available in the sidebar widget. You need as well!


page = XHTMLLib().template() # generate a basic XHTML template
    page.xpath('/html/head/title')['child'] = "Hello world" # set the title

    page.function_factory(['div', 'img', 'fieldset', 'input', 'ul', 'li'], '', '') # register functions

    lists = [li(class_='xtra', child="Home"), li(class_="test", child="Links"), li(child="Contact"), li(class_="test", child="About"), li(child="Sitemap")] # create a list
    lists.sort() # sort elements

    page.xpath('/html/body')['child'] = [ # add to the body
        div(id_='header', child='test & more'), # Entities get converted
        fieldset(class_='test', child=[
            input(type_='text', name='name'),
        ul(child=lists) # Comppose pages of different object sets.

    page.xpath('/html/body/img').__setitem__('onclick', 'alert("!@#$^, stop clicking!")', True) # Voodoo magic to get evil js in, alsays use external js!
    page.xpath('/html/body/ul/li[class=test][4]')['style'] = 'color:red' # Some more 'advanced xpath' to get a specific list item

    print page.render();


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
		<meta content="application/xhtml+xml;charset=utf-8" http-equiv="Content-Type"></meta>
		<title>Hello world</title>
		<div id="header">test &amp; more</div>
		<img src="image.jpg" onclick="<![CDATA[alert("!@#$^, stop clicking!")]]>"></img>
		<fieldset class="test">
			<input type="text" name="name"></input>
			<input type="submit"></input>
			<li class="test">About</li>
			<li class="xtra">Home</li>
			<li style="color:red" class="test">Links</li>

Python thumbnail generator

This is the second version of my first Python program. You know the problem, you got a blog, a website, want to send an email or chat with a lot of photo’s, but nowadays camera’s shoot photos of at least 3 Mega Pixel, if not 10 or more. That is going to take forever to send/receive, if at all posible.(most web server have an upload limit of 5MB)

That is why I made this script, it takes all the jpg files in on(or even more) directories and copies a thumbnail over to another directory. The default is to take all the jpg files in ‘.'(current directory) and copy them with a maximum size of 500×500 to ‘./thumbnails’. Want something else? you can specify the maximum with and height, as much source directories as you want and one destination.

The usage is:

python -w 300 -h 200 /some/photo/dir /another/vacation/photo/dir /the/destination/directory/for/thumbnails

The first version had a very bad coding style, but here is the new version:
note: It does not yet work without source and target dir, but I’m working on that fixed it!
another note: You’ll need PIL

I’m now on, so here’s the link:


PepSite CMS so far

What I did not yet do: Everything.

What I did do: the rest, being:

  • Started to learn python
  • Register at
  • Write a batch Thumbnail generator with PIL
  • Think about what I want and don’t want for my own website/CMS

My blog has moved!

My blog has permanently moved to a self hosted Wordpress at

This blog will stay around for accidental search engine visitors.


This is me

Blog Stats

  • 22,233 hits