Python Web

The 3 basic method of doing web in Python are :

  1. CGI
  2. WSGI
  3. mod_python

CGI

see http://jroller.com/rezaghp/entry/python_web_hello_world

<!-- form.html in www folder-->
<form action='/cgi-bin/receive.py'>
Change name <input type='text' name='name' />
<input type='submit' />
</form>
 
# receive.py in www/cgi-bin/
#!/usr/bin/env python
# this receives an input from a form
import cgi
form = cgi.FieldStorage()
name = form.getvalue('name', 'world')
print 'Content-type: text/plain'
print
print 'Hello, %s!' % name

Form

#!/usr/bin/env python
# this receives an input from a form
import cgi
form = cgi.FieldStorage()
name = form.getvalue('name', 'world')
print 'Content-type: text/plain'
print
print 'Hello, %s!' % name

mod_python

Among other things there are handlers to make development easier:

CGI handler

The following code can be replaced by the normal cgi handler: "AddHandler cgi-script .cgi .py" and does the same:

SetHandler mod_python
PythonHandler mod_python.cgihandler

PSP handler

Lets you mix HTML and Python code to create executable Web pages

Add the following to the apache:
AddHandler mod_python .psp
PythonHandler mod_python.psp

#test.psp
<%
from random import choice
adjectives = ['beautiful', 'cruel']
%>
<html>
<head>
<title>Hello</title>
</head>
<body>
<p>Hello, <%=choice(adjectives)%> world. My name is Mr. Gumby.</p>
</body>
</html>

Publisher handler

It exposes functions and returns their result, basically lets you call Python functions using URLs.

#add to apache
AddHandler mod_python .py
PythonHandler mod_python.publisher
 
#a simple function in published.py
def test(req):
 return "Hello, world!"
 
call using http://localhost/cgi-bin/published.py/test

WSGI

See: http://webpython.codepoint.net/wsgi_tutorial , http://www.wsgi.org/en/latest/learn.html

from wsgiref.simple_server import make_server
from cgi import parse_qs, escape
def application(environ, start_response):
 
    d = parse_qs(environ['QUERY_STRING'])
 
    response_body = "hi"
    status = '200 OK'
 
    response_headers = [('Content-Type', 'text/html'),
                   ('Content-Length', str(len(response_body)))]
    start_response(status, response_headers)
 
    return [response_body]
 
httpd = make_server('localhost', 8051, application)
httpd.serve_forever()

Reference

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License