HTML.py - a Python module to easily generate HTML tables and lists

HTML.py has been developed to easily generate HTML code for tables and lists in Python scripts. This is mostly convenient to generate reports in HTML or simple web applications in lightweight frameworks such as CherryPy.

There are already quite a few similar solutions for Python, either HTML generators or templating engines (see links at the end of this article). Most of them are very powerful but quite complex for simple cases. HTML.py is useful when you need to generate simple HTML code without requiring to learn a templating language. Furthermore, while some HTML generators provide a comprehensive object-oriented model of HTML, HTML.py is meant to translate Python objects to HTML as easily as possible.

Download

Click on the attached file below at the bottom of this page.

License

Cecill: open-source, GPL compatible.


How to use HTML.py

Basic principles

The HTML module provides two different interfaces: classes (Table, List, ...) and functions with similar names in lowercase (table, list, ...). Functions simply translate Python data to HTML source code in a string, while classes are a representation of data which may be modified in place and rendered as HTML code when needed. For simple tasks functions are easier to use, while classes provide more flexibility.


HTML Tables

Basically, an HTML table is stored as a list of rows. Each row is itself a list of cells. Each cell is a Python string or any object which may be rendered as a string using str().

So the easiest way to create a HTML table is to use a list of lists:

import HTML
table_data = [
        ['Last name',   'First name',   'Age'],
        ['Smith',       'John',         30],
        ['Carpenter',   'Jack',         47],
        ['Johnson',     'Paul',         62],
    ]
htmlcode = HTML.table(table_data)
print htmlcode

A header row may be specified: it will appear in bold in browsers

table_data = [
        ['Smith',       'John',         30],
        ['Carpenter',   'Jack',         47],
        ['Johnson',     'Paul',         62],
    ]
htmlcode = HTML.table(table_data,
    header_row=['Last name',   'First name',   'Age'])
print htmlcode

You may also create a Table object and add rows one by one. Its "rows" attribute is a list which can be modified in place. When the table is complete, convert the Table object to a string using str() to get the HTML code:

t = HTML.Table(header_row=['x', 'square(x)', 'cube(x)'])
for x in range(1,10):
    t.rows.append([x, x*x, x*x*x])
htmlcode = str(t)
print htmlcode

Rows may be any iterable (list, tuple, ...) including a generator. This is useful to save memory when generating a large table.

def gen_rows(i):
    'rows generator'
    for x in range(1,i):
        yield [x, x*x, x*x*x]
htmlcode = HTML.table(gen_rows(10), header_row=['x', 'square(x)', 'cube(x)'])
print htmlcode

To choose a specific background color for a cell, use a TableCell object:

HTML_COLORS = ['Black', 'Green', 'Silver', 'Lime', 'Gray', 'Olive', 'White',
    'Maroon', 'Navy', 'Red', 'Blue', 'Purple', 'Teal', 'Fuchsia', 'Aqua']
t = HTML.Table(header_row=['Name', 'Color'])
for colorname in HTML_COLORS:
    colored_cell = HTML.TableCell(' ', bgcolor=colorname)
    t.rows.append([colorname, colored_cell])
htmlcode = str(t)
print htmlcode

Here is an example of how HTML.py can be used to generate a test report with colors for successes, failures and errors:

# dictionary of test results, indexed by test id:
test_results = {
        'test 1': 'success',
        'test 2': 'failure',
        'test 3': 'success',
        'test 4': 'error',
    }
# dict of colors for each result:
result_colors = {
        'success':      'lime',
        'failure':      'red',
        'error':        'yellow',
    }
t = HTML.Table(header_row=['Test', 'Result'])
for test_id in sorted(test_results):
    # create the colored cell:
    color = result_colors[test_results[test_id]]
    colored_result = HTML.TableCell(test_results[test_id], bgcolor=color)
    # append the row with two cells:
    t.rows.append([test_id, colored_result])
htmlcode = str(t)
print htmlcode

HTML Lists

a HTML list (with bullets) may simply be built from a Python list of strings:

a_list = ['john', 'paul', 'jack']
htmlcode = HTML.list(a_list)
print htmlcode

It is easy to change it into a numbered (ordered) list:

htmlcode = HTML.list(a_list, ordered=True)
print htmlcode

Lines of a list may also be added one by one, when using the List class. Its "lines" attribute can be modified in place:

html_list = HTML.List()
for i in range(1,10):
    html_list.lines.append('square(%d) = %d' % (i, i*i))
htmlcode = str(html_list)
print htmlcode

To save memory, a large list may also be built from a generator:

def gen_lines(i):
    'lines generator'
    for x in range(1,i):
        yield 'square(%d) = %d' % (x, x*x)
htmlcode = HTML.list(gen_lines(10))
print htmlcode

HTML Links

How to create a link:

htmlcode = HTML.link('Decalage website', 'http://www.decalage.info')
print htmlcode

HTML.py tutorial

All the examples above may be tested using the script HTML_tutorial.py provided with HTML.py.


Alternatives

If HTML.py does not suit your needs, there are quite a few other solutions to generate HTML from Python:

HTML generators:

  • HTMLTags: http://karrigell.sourceforge.net/en/htmltags.htm or http://code.activestate.com/recipes/366000/
  • markup.py: http://markup.sourceforge.net/
  • makeHTML: http://www.hoboes.com/Mimsy/?ART=128
  • HTMLgen: http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/ (used to be http://starship.python.net/crew/friedrich/HTMLgen)
  • html: http://home.arcor.de/jurner/python/
  • pyhtmloo: http://pyhtmloo.sourceforge.net/
  • pyWeb: http://www.freenet.org.nz/python/pyweb/
  • XIST: http://www.livinglogic.de/Python/xist/
  • htmlbuilder.py: http://gflanagan.net/site/python/
  • StupidXML: http://code.google.com/p/stupidxml/

Templating engines:

  • Genshi: http://genshi.edgewall.org/
  • Kid: http://www.kid-templating.org/
Attachment Size
HTML.py-0.04.zip 30.41 KB