开发者

What python html generator module should I use in a non-web application?

I'm hacking a quick and dirty python script to generate some reports as static html files.

What would be a good module to easily build static html files outside the context of a web application?

My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to output some html tags).

I found two alternatives on my first goolge search:

  • markup.py - http://markup.sourceforge.net/
  • HTML.py - http://www.decalage.info/en/python/html

Also, I feel that using a templating engi开发者_开发技巧ne would be over-kill, but if you differ please say it and why.

Any other recommendation?


Maybe you could try Markdown instead, and convert it to HTML on the fly?


You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:

http://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py

(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.)


Why would a templating engine necessarily be overkill? You don't need the whole web framework just to use the templating engine (at least, for most templating engines). Mako for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and such)


ElementTree can produce html with some limitations. I'd write it like this:

from xml.etree.ElementTree import ElementTree, Element, SubElement
import sys 

html = Element('html')

head = SubElement(html, 'head')
style = SubElement(head, 'link')
style.attrib = {'rel': 'stylesheet', 'href': 'style.css', 'type': 'text/css'}
body = SubElement(html, 'body')

para = SubElement(body, 'p')
para.text = 'Lorem ipsum sit amet'

doc = ElementTree(html)
doc.write(sys.stdout)

In case of moderately complex html I'd stick with some templating engine: Jinja2, Mako, Cheetah, just to name a few.


If you have just some simple static HTML files. Then why not use string templates like so.

import string

TEMPLATE_FORMAT = """
<html>
<head><title>Trial</title></head>
<body>
    <div class="myclass">$my_div_data</div>
</body>
"""
my_div_data = "some_data_to_display_in_HTML"
TEMPLATE    = string.Template(TEMPLATE_FORMAT)
html_data   = TEMPLATE.safe_substitute(my_div_data)
open("out.html", "w").write(html_data)

Give this a shot if you don't have too big HTML files to generate. Saves you on the learning you need to do if you decide to use libraries.


i recommend having a look at shpaml

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜