Python-Ref > Dynamic web pages in Python > Introduction
 
 

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

Introduction

The basic idea behind dynamic pages is very simple - instead of preparing all necessary pages as individual files, write a program that will create the pages as they are requested by the user. The program itself can be do whatever you want, the only limitation is that it should produce a HTML page as a result of its execution.
The following schema shows how a dynamic page is processed
  1. The client asks the server for a specific page
  2. The server finds the file and according to some rules in its configuration determines that it is a dynamic page - that is it should not return the document itself but rather run it to obtain the resulting document.
  3. The server executes the source of the page (more on this below) and reads the output.
  4. The server sends the output to the client. For the client it is undistinguishable from a static page.
The most interesting part of the whole schema is part number 3 - the execution of the script. In the simplest case of CGI, there is a program associated with the page that is responsible for generating the resulting document. In more sophisticated cases, an interpreter of the source code is build directly into the web-server (either hard-coded or as a module) and takes care of the execution inside the server.
In case of Python, the most commonly used way to create dynamic pages is to use mod_python module for the Apache web-server. This module creates an extra layer between the server and the script which simplifies creation of dynamic pages.
Mod_python offers a few different ways to write server-side scripts, using the so called handlers. The most commonly used handler is publisher that offers a good mix between flexibility and ease of use.
In scripts interpreted by the publisher handler, each function acts as an individual page. This means that if your script is called "test.py", you can access its function "hello" under the URL "test.py/hello". In case you don't supply the name of the function (the URL is just "test.py"), the result of a function called "index" is returned. This way you can create all the pages in one big file, or you can have each page in a separate file with only the "index" function.
The following example demonstrates a very simple dynamic page using the publisher handler.
Expand/Shrink
Zdroj: (dpages1-1.py)
  1   def index():
  2     return "<html><body><h1>Hello World</h1></body></html>"
<html><body><h1>Hello World</h1></body></html>
Doba běhu: 280.3 ms