How do I set up a Python CGI server?

2020-05-29 04:01发布

问题:

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?

回答1:

Take a look at the docs for CGIHTTPRequestHandler, which describe how it works out which files are CGI scripts.



回答2:

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.

def application(environ, start_response):
    start_response([('content-type', 'text/html;charset=utf-8')])
    return ['<html><body><p>Hello World!</p></body></html>'.encode('utf-8')]

And to serve it (possibly in the same file):

import wsgiref.simple_server
server = wsgiref.simple_server.make_server('', 8000, application)
server.serve_forever()


回答3:

simplest way to start a cgi server for development is following:

  • create a base directory with all your html and other files
  • create a subdirectory named cgi-bin with all your cgi files
  • cd to the base directory
  • run python -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