January 2, 2012

Generating demo content with Plone

Implementing content-types for Plone site is one part of every typical Plone project. Styling & testing is another one. Both testers and designer need content for testing.

As part of a new project I decided to provide example content for each new content-type. The two core components are the loremipsum module for Python and the lorempixel.com web-service. The Python module can be used to generate single sentences of text or multiple paragraphs of text. The web-service provided random images in arbitrary sizes for you.

Here is a picture of a sample glossary

and one of a simple picture database:

Here is some example code for generating content and random image from using the mentioned services:

def gen_paragraphs(num=3):
    return u'/'.join([p[2] for p in loremipsum.Generator().generate_paragraphs(num)])
def gen_sentence():
    return loremipsum.Generator().generate_sentence()[-1]
def gen_sentences(length=80):
    return u'/'.join([s[2] for s in loremipsum.Generator().generate_sentences(length)])
def random_image(width, height):
    url = 'http://lorempixel.com/%d/%d/' % (width, height)
    return urllib2.urlopen(url).read()

The code for generating a gallery as seen above looks like this:

def installAssets(self, site):

    service = site.restrictedTraverse('deutschland/de/service')
    assets = invokeFactory(service, 'Folder', 'Assets')
    for width,height in ((200,200), (400,400), (600, 400), (800, 600), 
                         (800,800), (1024, 768))
        imagefolder_id = '%sx%s' % (width, height) 
        images = invokeFactory(assets, 'Folder', imagefolder_id)
        for i in range(20):
           img = invokeFactory(images, 'Image')
           img.setImage(random_image(width, height))

The invokeFactory() method used here is just a tiny wrapper around the standard invokeFactory() method of a folder object that generates a random title and a normalized id for the new content object plus doing some pre-allocation of the description and text field (if available) on the created content-object.

The complete code can be found on the website of my Plone partner Veit Schiele (German only).