Creating an HTTP Server to Process CGI Scripts


import os import BaseHTTPServer, CGIHTTPServer serverAddr = ("", 80) os.chdir("/myTest") serv = BaseHTTPServer.HTTPServer( \     serverAddr, CGIHTTPServer.CGIHTTPRequestHandler) serv.serve_forever()

Python includes the CGIHTTPServer module that provides a quick and easy way to create your own CGI script server, eliminating the need to set up and configure a web server. This can be extremely time-saving.

To set up a simple CGI script server, first set the root directory for the server to act in, and then create an instance of the CGI script server using BaseHTTPServer.HTTPServer(address, handler). The address argument is a list including the server address and port, respectively. A simple server handler should specify the default handler of CGIHTTPServer.CGIHTTPRequestHandler. The CGIHTTPRequestHandler is similar to a normal HTTPRequestHandler; however, the do_GET and do_HEAD functions have been modified to handle CGI scripts, and the do_POST method will only allow posting to CGI scripts.

Note

You can override the do_GET, do_HEAD, and do_POST methods to create a customized CGI script parser.


After you have created an instance of the CGI script server, start the server by calling its serve_forever() function.

Note

The default location for CGI scripts is /cgi-bin or /htbin, relative to the root directory of the script server. The CGI scripts will need to reside in one of these two locations, and the Linux permissions must be set so that the scripts are executable (typically 0755).


import os import BaseHTTPServer, CGIHTTPServer serverAddr = ("", 80) #Set root directory os.chdir("/myTest") #Create server object serv = BaseHTTPServer.HTTPServer( \    serverAddr, CGIHTTPServer.CGIHTTPRequestHandler) #Start server serv.serve_forever()


cgi_serv.py

Figure 10.10 shows the web page generated by cgi_form.cgi as it is executed by the cgi_serv.py script.

Figure 10.10. Output HTML page created by cgi_form.cgi code executed by cgi_serv.py.




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net