You are viewing a plain text version of this content. The canonical link for it is here.
Posted to mod_python-commits@quetz.apache.org by Apache Wiki <wi...@apache.org> on 2006/12/02 20:13:57 UTC

[Mod_python Wiki] Update of "HelloBruceHTML" by JoreyBump

Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Mod_python Wiki" for change notification.

The following page has been changed by JoreyBump:
http://wiki.apache.org/mod_python/HelloBruceHTML

The comment on the change is:
A minimal "Hello, World!" PythonHandler that outputs HTML

New page:
This basic handler explains how to return HTML content.

{{{#!python
"""
A "Hello, World!" example for a minimal PythonHandler. This one outputs HTML.
"""

from mod_python import apache

page = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
           "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Hello, Bruce!</title>
    <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body>
    <h1>Hello, Bruce!</h1>
</body>
</html>
"""

def handler(req):
    req.content_type = "text/html"
    req.write(page)
    return apache.OK
}}}

Just like HelloBruceText, this handler outputs a string, but this time we used the text/html MIME type in the Content-Type header:

{{{#!python
    req.content_type = "text/html"
}}}

The visitor's browser will display a simple HTML page:

{{{
Hello, Bruce!
}}}

NOTE: The example could have used a simpler snippet of HTML code that would render fine in most browsers:

{{{#!python
    req.write('<html><body><h1>Hello, Bruce!</h1></body></html>')
}}}

But this is as good a time as any to emphasize the importance of constructing valid output, whether it's an HTML page or any other type of content. We're operating at a very low level, using technology that encompasses multiple protocols. Adhere to the guidelines faithfully, and you will have an application that behaves as expected. Browser bugs or quirks are easily triggered by invalid output, which can make troubleshooting difficult.