embedding python in HTML

Magnus Lycka lycka at carmen.se
Wed Feb 22 07:37:00 EST 2006


John Salerno wrote:
> Thanks, that makes much more sense to me now. But does this mean I can 
> still write HTML normally? What would an example be of having HTML 
> within a Python script? I have a hard time picturing this, because I 
> imagine that most of my pages will be almost all HTML, with just a bit 
> of Python here and there, perhaps to insert headers and footers. Is all 
> the HTML just wrapped in a big print statement, or something like that?

Imagine for instance, that you have an HTML file where you
want to print a current timestamp when the page is displayed.

A simple way to do this would be to just give your HTML file
another extension (e.g. .tmpl, short for template). Keep the
file as it is, just put the text

    %(timestamp)s

in the place(s) where you want your timestamp to appear
in the HTML file.

In your CGI script you can then do something like this:

#!/usr/bin/python -u
import time
print "Content-type: text/html\n"
text = open('myfile.tmpl).read()
print text % ('timestamp':time.asctime())

The inital Content-type line is important, and it must be
followed by a blank line before the actual content.

Look at the cgitb module too.

Instead of the common Python % interpolation, you could use
string.Template (with a current Python) or one of the many
templating systems around. Since your needs are likely to
grow, you might also want to have a look at one of the many
tool kits for Python and the web. Right now, it seems that
django and turbogears are the most popular. Cherrypy and
web.py are somewhat smaller and simpler systems. Unless you
use one of these tool kits, your homegrown code might turn
into yet another web tool kit eventually, and we have enough
of them already... (Too many I'd say...)

You should also note that traditional CGI scripts are rather
slow with Python, since Python's startup time is significant.
A system where the Python interpreter is already running, as
mod_python embedded in Apache is faster. But by all means, try
it as CGI. It might well be enough for your needs. It's been
ok for me.



More information about the Python-list mailing list