I'm running Python 3.2 on Windows. I want to run a simple CGI server on my machine for testing purposes. Here's what I've done so far:
I created a python program with the following code:
import http.server
import socketserver
PORT = 8000
Handler = http.server.CGIHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
In the same folder, I created "index.html", a simple HTML file. I then ran the program and went to http://localhost:8000/ in my web browser, and the page displayed successfully. Next I made a file called "hello.py" in the same directory, with the following code:
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print()
print("""<html><body><p>Hello World!</p></body></html>""")
Now if I go to http://localhost:8000/hello.py, my web browser displays the full code above instead of just "Hello World!". How do I make python execute the CGI code before serving it?
simplest way to start a cgi server for development is following:
cgi-bin
with all your cgi filespython -m http.server --cgi -b 127.0.0.1 8000
Now you can connect to http://localhost:8000 and tst your html code with cgi scripts
Though not officialy deprecated, the
cgi
module is a bit clunky to use; most folks these days are using something else (anything else!)You can, for instance, use the wsgi interface to write your scripts in a way that can be easily and efficiently served in many http servers. To get you started, you can even use the builtin
wsgiref
handler.And to serve it (possibly in the same file):
Take a look at the docs for CGIHTTPRequestHandler, which describe how it works out which files are CGI scripts.