473,726 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recommended way of generating HTML from Python

What is the recommended way of generating HTML from Python? I know of
HTMLGen and of
few recipes in the Cookbook, but is there something which is more or
less standard?
Also, are there plans to include a module for HTML generation in the
standard library?
I really would like to see some standardization in this area.

Michele Simionato

Jul 18 '05 #1
13 2391
Michele Simionato napisa³(a):
What is the recommended way of generating HTML from Python? I know of
HTMLGen and of
few recipes in the Cookbook, but is there something which is more or
less standard?
Also, are there plans to include a module for HTML generation in the
standard library?
I really would like to see some standardization in this area.


I don't thing there is anything "recommende d" except personal
recommendations . Personally, I like Hamish Sanderson's HTMLTemplate
(http://freespace.virgin.net/hamish.s...template.html), but I
may be biased. ;)

Hamish planned to start process that would lead to inclusion of
HTMLTemplate to standard library, but I don't think it's gonna happen in
any foreseeable future.

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
Jul 18 '05 #2
Just to clarify, before people start pointing out their preferred
templating language: I am NOT asking for
a template system. I am asking for something on the
lines of HTMLGen, where you just use pure Python.

Jul 18 '05 #3
Michele Simionato wrote:
What is the recommended way of generating HTML from Python? I know of
HTMLGen and of
few recipes in the Cookbook, but is there something which is more or
less standard?
I'm also an htmlgen user, but it's getting a bit long in the tooth, and the
installation is not very clean (pre-distutils). I keep an eye out for
alternatives, here's one (which I haven't looked at yet):

######
htmldata 1.0.6 is available.

http://oregonstate.edu/~barnesc/htmldata/

The htmldata module allows one to translate HTML
documents back and forth to list data structures.
This allows for programmatic reading and writing
of HTML documents, with much flexibility.

######

I could swear that I also saw another recent email announcing an htmlgen
alternative, but no amount of googling or digging through my email could turn
it up. I think it was in the last month or so, and probably on the
python-announce list, but looking through the archives I can't find it. Maybe
my memory is playing tricks on me.
Also, are there plans to include a module for HTML generation in the
standard library?
I really would like to see some standardization in this area.


I would too. The HTMLgen model is quite nice and clean (at least for my simple
uses), but I'd use anything, as long as it's included by default and supported.

Cheers,

f

Jul 18 '05 #4
Here are a couple of pointers. I agree with Michele that it would be
nice to have some kind of standardization . Maybe this would be worth a
post to the Web-SIG ?

- I posted a 70-line recipe on the Python Cookbook, a sort of poor man's
HTMLGen called HTMLTags
http://aspn.activestate.com/ASPN/Coo.../Recipe/366000
with a syntax like this :

# print HTML( HEAD(TITLE('Tes t document')) +
# BODY(H1('This is a test document')+
# TEXT('First line')+BR()+
# TEXT('Second line')))

The use of addition allows for shortcuts like
print Sum([ TR(TD(i)+TD(i*i )) for i in range(100) ])

where Sum works like the built-in sum, but sum only works for numbers
apparently

- in the Cookbook someone mentioned the HyperText package, published in
2000 by Andy Dustman : http://dustman.net/andy/python/HyperText/

It uses this syntax :

# print TABLE(
# TR((TH('SPAM'), TH('EGGS')),
# TR(TD('foo','ba r', colspan=2))
# )

The package also handles XML, SGML etc.

- I wrote to Andy and he said there was also Living Logic's XIST :
http://www.livinglogic.de/Python/xist/index.html

An example taken from the site :

#node = xsc.Frag(
# xml.XML10(),
# html.DocTypeXHT ML10transitiona l(),
# html.html(
# html.head(
# meta.contenttyp e(),
# html.title("Exa mple page")
# ),
# html.body(
# html.h1("Welcom e to the example page"),
# html.p(
# "This example page has a link to the ",
# html.a("Python home page", href="http://www.python.org/"),
# "."
# )
# )
# )
# )
#
# print node.conv().asB ytes(encoding=" us-ascii")
Jul 18 '05 #5
Stan (part of nevow, which is part of twisted) is a nice python syntax
for building HTML - I like the use of () and [] to separate attributes
from sub-elements.

For example:

class Greeter(rend.Pa ge):
def greet(self, context, data):
return random.choice(["Hello", "Greetings" , "Hi"]), " ", data

docFactory = loaders.stan(
tags.html[
tags.head[ tags.title[ "Greetings! " ]],
tags.body[
tags.h1(style=" font-size: large")[ "Now I will greet you:" ],
greet
]
])

(From http://nevow.com/releases/0.3.0/nevow-intro.html)

I don't know how detachable it is from the rest of nevow. I'd assume it
wouldn't be too difficult to implement in a standalone fashion.

xtian

Jul 18 '05 #6
has
xtian wrote:
Stan (part of nevow, which is part of twisted) is a nice python syntax for building HTML [...] I don't know how detachable it is from the rest of nevow. I'd assume it wouldn't be too difficult to implement in a standalone fashion.


FWIW I whipped up a simple self-contained Stan clone a while back:

http://freespace.virgin.net/hamish.s...on/stanlite.py

It's a bit quick-n-dirty - I think ideally you'd want it to parse all
the HTML element information from a DTD and perform proper validation
of input data - but if anyone want to pick it up and run with it, or
just use it as-is, they're more than welcome to.

HTH

has

Jul 18 '05 #7
The problem is a problem of standardization , indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).

FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

..def makeattr(dict_o r_list_of_pairs ):
.. dic = dict(dict_or_li st_of_pairs)
.. return " ".join("%s= %r" % (k, dic[k]) for k in dic)

..class HTMLTag(object) :
.. def __getattr__(sel f, name):
.. def tag(value, **attr):
.. """value can be a string or a sequence of strings."""
.. if hasattr(value, "__iter__") : # is iterable
.. value = " ".join(valu e)
.. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
.. return tag

# example:
..html = HTMLTag()

..tableheader = ["field1", "field2"]
..tablebody = [["a1", "a2"],
.. ["b1", "b2"]]

..html_header = [html.tr(html.th (el) for el in tableheader)]
..html_table = [html.tr(html.td (el) for el in row) for row in tablebody]
..print html.table(html _header + html_table)

Michele Simionato

Jul 18 '05 #8
Michele Simionato wrote:
The problem is a problem of standardization , indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).
Why not teach your students to use a template system?
FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

.def makeattr(dict_o r_list_of_pairs ):
. dic = dict(dict_or_li st_of_pairs)
. return " ".join("%s= %r" % (k, dic[k]) for k in dic)

.class HTMLTag(object) :
. def __getattr__(sel f, name):
. def tag(value, **attr):
. """value can be a string or a sequence of strings."""
. if hasattr(value, "__iter__") : # is iterable
. value = " ".join(valu e)
. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
. return tag

# example:
.html = HTMLTag()

.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]

.html_header = [html.tr(html.th (el) for el in tableheader)]
.html_table = [html.tr(html.td (el) for el in row) for row in tablebody]
.print html.table(html _header + html_table)
*Shudder*

I've written web pages this way (using a pretty nice Java HTML generation package) and I don't
recommend it. In my experience, this approach has several drawbacks:
- as soon as the web page gets at all complex, the conceptual shift from HTML to code and back is
difficult.
- It is hard to work with a designer. The designer will give you sample web pages which then have to
be hand-translated to code. Changes to the web page have to be located in the code.
- There is no separation of content and presentation

IMO templating systems are a much better solution. They let you express HTML in HTML directly; you
communicate with a designer in a language the designer understands; you can separate content and
presentation.

Kent

Michele Simionato

Jul 18 '05 #9
On Mon, 2005-02-21 at 07:36 -0500, Kent Johnson wrote:
Michele Simionato wrote:
The problem is a problem of standardization , indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).
Why not teach your students to use a template system?
FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

.def makeattr(dict_o r_list_of_pairs ):
. dic = dict(dict_or_li st_of_pairs)
. return " ".join("%s= %r" % (k, dic[k]) for k in dic)

.class HTMLTag(object) :
. def __getattr__(sel f, name):
. def tag(value, **attr):
. """value can be a string or a sequence of strings."""
. if hasattr(value, "__iter__") : # is iterable
. value = " ".join(valu e)
. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
. return tag

# example:
.html = HTMLTag()

.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]

.html_header = [html.tr(html.th (el) for el in tableheader)]
.html_table = [html.tr(html.td (el) for el in row) for row in tablebody]
.print html.table(html _header + html_table)


*Shudder*

I've written web pages this way (using a pretty nice Java HTML generation package) and I don't
recommend it. In my experience, this approach has several drawbacks:
- as soon as the web page gets at all complex, the conceptual shift from HTML to code and back is
difficult.
- It is hard to work with a designer. The designer will give you sample web pages which then have to
be hand-translated to code. Changes to the web page have to be located in the code.
- There is no separation of content and presentation


Slightly off topic but, just to be clear, Nevow supports XHTML templates
*and* stan tag expressions. Both are useful. As a general rule, I stick
to XHTML templates but I use stan for prototyping pages and when marking
up the XHTML templates gets so complicated that they might as well be
written in Python anyway.

Also, just because the HTML code is not in a .html file does not
necessarily mean that content and presentation are mixed up. For
instance, with stan (and probably the alternatives mentioned in this
thread) it's very easy to build a tag library that the "real" Python
code simply calls on to render page content.

IMO templating systems are a much better solution. They let you express HTML in HTML directly; you
communicate with a designer in a language the designer understands; you can separate content and
presentation.


Agreed. Although I would go further and say that it's important to
choose a templating system that allows the Python developer to annotate
XHTML templates using **valid XML**, i.e. no "for x in y" loops, no "if
foo" conditionals, no "i = 0" variable setting, no expression
evaluations, etc.
<advocacy>
The lovely thing about Nevow is that it encourages good separation -
HTML is HTML and logic is Python, as it should be - but does not get in
the way when breaking the rules is necessary or just a lot easier.
</advocacy>
Cheers, Matt

--
__
/ \__ Matt Goodall, Pollenation Internet Ltd
\__/ \ w: http://www.pollenation .net
__/ \__/ e: ma**@pollenatio n.net
/ \__/ \ t: +44 (0)113 2252500
\__/ \__/
/ \ Any views expressed are my own and do not necessarily
\__/ reflect the views of my employer.

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1904
by: Dan Gass | last post by:
The difflib.py module and the diff.py tools script in Python 2.4 alpha 3 now support generating side by side (with intra line differences) in HTML format. I have found this useful for performing build release comparisons (I use a script to generate a main page showing all the files that were changed in a build with hyperlinks to side by side differences for each of those files). I also find it useful for generating HTML test reports to...
8
4257
by: Tim Daneliuk | last post by:
I use a makefile to create distribution tarballs of freestanding Python programs and their documentation. I cannot seem to find the right command line option to just generate a pyc/pyo file from the program and then exit. If I use 'python -OOOO -c"import myprog"' it creates the pyo file, but myprog starts up and keeps running. IOW, I need a batch method for generating compiled python. I know it exists, but I can't find it for some...
0
1789
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return dict() print combo2(5)
4
6014
by: Andreas Jung | last post by:
Hi, does anyone know of a high-level solution to produce RTF from Python (something similar to Reportlab for producing PDF)? Thanks, Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.0 (Darwin)
17
2134
by: flupke | last post by:
Hi, i create my GUIs mainly via wxGlade. However when you start of to program and want to do some rearranging to the gui, wxglade overwrites your file and you've got to put your own code back in. I think i can work around that (at least a bit) by making a second file that imports the gui generated by wxglade and make classes that extend the original ones. For instance i could have a class MainForm that extends the wxFrame
14
2597
by: Philippe C. Martin | last post by:
Hi, I wish to use an easy way to generate reports from wxPython and feel wxHtmlEasyPrinting could be a good solution. I now need to generate the HTML wxHtmlEasyPrinting can print: I need to have a title followed by lines of text that do not look too ugly. If possible I would like to use an existing module. Q1) Is there such a module ?
6
1798
by: John Machin | last post by:
Hi, In general, I'm mainly interested in a template engine for dynamic web pages but would like a general purpose one to avoid learning yet another package for generating e-mail messages, form letters, source code, whatever. In particular, does anyone have much experience with the Python interface to Terence Parr's StringTemplate (http://www.stringtemplate.org/)? Reading the website, I'm attracted by
4
2016
by: John Nagle | last post by:
What's the recommended FastCGI module for Python. There are at least five: The Robin Dunn / Total Control Software version: http://alldunn.com/python/fcgi.py Last revised in 1998. The "JonPy" version: http://jonpy.sourceforge.net/fcgi.html Last revised in 2004.
3
1224
by: Ge Chunyuan | last post by:
hi Group: I am a new comer for Python, I wonder which IDE is recommended in Windows OS. Can anyone give some suggestion. Thanks indeed Ge Chunyuan
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.