4 Answers
4

At its most basic level, a Python script works like any CGI program. A Web request is sent to the server. The server sees that the URL is mapped to a Python script, so it runs your program, passing along information about the request (HTTP request headers, etc.). Your script receives those parameters and returns HTTP response headers and, in most cases, a valid HTML page, unless your script is doing a redirect or something rather than an HTML response. All this is done by simply sending the headers and HTML to standard output, e.g. using print or the like, in the appropriate format. Then your script ends.

Because HTTP is a stateless protocol (that is, it does not inherently have any concept of a "user" or a "session"), you have to keep track of users' state data by sending them cookies (or hidden form fields, which is what we used to use before cookies were invented). If you have multiple scripts, you have to arrange to save any information that needs to be passed from one script to another, again using cookies or hidden fields form or special URLs. (You can also save some of that information server-side in a database and simply provide a session cookie.)

Generally you do not embed Python code in HTML as you would with PHP or ASP. Instead your Python script would use a template, possibly reading it from a file, and substitute the necessary values into it.

All this quickly becomes a major pain to do yourself as your application gains complexity (I do recommend it as a learning experience, however -- every Web developer should know how HTTP and CGI work). This is where the frameworks that others are mentioning come in, by doing much of that for you, providing abstractions that make HTTP seem like it has user sessions, templating mini-languages, and so forth.