How do I set up a Python CGI server?

心已入冬 提交于 2019-12-03 13:49:15

问题


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()


来源:https://stackoverflow.com/questions/8156898/how-do-i-set-up-a-python-cgi-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!