[Tutor] Really basic web templating

Martin Walsh mwalsh at groktech.org
Mon Oct 1 10:32:07 CEST 2007


wormwood_3 wrote:
> Well yes and no:-) This sort of application would fall under the
> sprawling category of CGI, yes, and I can use Python scripts on my web
> server, so it is supported. But nearly every tutorial I have seen
> regarding Python and CGI only have to do with form submissions, doing
> calculations and other things with data sent from webpages to Python
> scripts. But that is not really what I want to do. I am wondering what a
> script would need to do to take requests for pages on my site, and
> generate them from templates. I am not sure if I can do this without
> having access to Apache rewrite rules, etc.

I am going to assume from your description that you are looking for a
way to use a *single* cgi script to handle all page requests to your
site, and respond with the appropriate template based on the requested
url. If I have assumed incorrectly then you can safely ignore the rest
of this message. :)

Some mod_rewrite directives are available to .htaccess, IIRC -- so that
may be a valid option, only if your webhost has enabled mod_rewrite of
course, and they allow overrides with htaccess.

Otherwise, this is a fairly simple task if you are content with "ugly"
urls. For example, given a url something like
http://mysite.com/mycgi.py?page=index.html, a very basic cgi
implementation might look like this:

#!/usr/bin/env python
import cgi

form = cgi.FieldStorage()

print "Content-type: text/html\n"
try:
    page = form["page"]
except KeyError:
    print file('custom404error.html').read()
else:
    content = file(page.value).read()
    # ... do something with content ...
    print content

---

If your webhost has enabled mod_actions (I suppose this is unlikely),
you can also do the following in .htaccess (again, only if they allow
override):

AddHandler my-python-handler .html
Action my-python-handler /cgi-bin/handler.py

which should force apache to set an environment variable named
'PATH_TRANSLATED' with the value of the requested url, and call
'handler.py' for any requested file with an .html extension (that
exists) in that directory -- honestly, I've never attempted this myself
-- and there is probably a better way, but it's all I can think of ATM.
If the file doesn't exist apache returns a 404, which is only desirable
if you plan to store your templates on the filesystem. And you can use
the os module to access the cgi environment variables:

#!/usr/bin/env python
import os

print "Content-type: text/plain\n"

try:
    path = os.environ["PATH_TRANSLATED"]
except:
    path = 'PATH_TRANSLATED is not defined.'

print "The requested url is:", path

---

Perhaps you could convince your webhost to install mod_python, if they
haven't already. It's fairly trivial to write a simple mod_python
handler to accomplish exactly what you are trying to do.

HTH,
Marty


More information about the Tutor mailing list