Python-Ref > Dynamic web pages in Python > Simple example
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Simple example

The following example shows a simple dynamic web-page created using the publisher handler of mod_python.
The function index is run by default if no relative path is provided after the script name. The function can be declared as having no arguments or it can have a req argument that will contain a Request object. We will not use this object in the following examples, but it contains all the information from the request HTTP headers - the URL, form attributes, etc. and might be useful in more complicated scripts.
Expand/Shrink
Zdroj: (dpages2-1.py)
  1   page_template = """
  2   <html>
  3   <head>
  4   <title>%s</title>
  5   </head>
  6   <body>
  7   %s
  8   </body>
  9   </html>"""
 10   
 11   
 12   def index( req):
 13     title = "Current time"
 14     import datetime
 15     body = "Current time is: "+datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")
 16     return page_template % (title, body)
<html>
<head>
<title>Current time</title>
</head>
<body>
Current time is: 2008-03-12 10:56:37
</body>
</html>
Doba běhu: 57.8 ms
If a relative path is given, it selects a function inside the script.
Expand/Shrink
URL:
dpages2-2.py/test
Zdroj: (dpages2-2.py)
  1   page_template = """
  2   <html>
  3   <head>
  4   <title>%s</title>
  5   </head>
  6   <body>
  7   %s
  8   </body>
  9   </html>"""
 10   
 11   
 12   def index():
 13     title = "Current time"
 14     import datetime
 15     body = "Current time is: "+datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")
 16     return page_template % (title, body)
 17   
 18   def test():
 19     return page_template % ("Test", "This is a test page")
<html>
<head>
<title>Test</title>
</head>
<body>
This is a test page
</body>
</html>
Doba běhu: 5.7 ms
Adding index as the relative path is the same as not giving it.
Expand/Shrink
URL:
dpages2-2.py/index
Zdroj: (dpages2-2.py)
  1   page_template = """
  2   <html>
  3   <head>
  4   <title>%s</title>
  5   </head>
  6   <body>
  7   %s
  8   </body>
  9   </html>"""
 10   
 11   
 12   def index():
 13     title = "Current time"
 14     import datetime
 15     body = "Current time is: "+datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")
 16     return page_template % (title, body)
 17   
 18   def test():
 19     return page_template % ("Test", "This is a test page")
<html>
<head>
<title>Current time</title>
</head>
<body>
Current time is: 2008-03-12 10:56:37
</body>
</html>
Doba běhu: 5.6 ms