如何运行Python CGI脚本

时间:2011-10-28 12:01:48

标签: python cgi

我之前从未设置过服务器(更不用说python服务器)而且我有点迷失了。我如何使用以下代码?我试图放入cgi bin目录但是没有用。它返回了内部服务器错误。看看这个here

#!/usr/bin/env python
#
# Funf: Open Sensing Framework
# Copyright (C) 2010-2011 Nadav Aharony, Wei Pan, Alex Pentland.
# Acknowledgments: Alan Gardner


from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import sys
import cgi
import urlparse
import os.path
import shutil
import time

server_dir = os.path.dirname(__file__)

config_path = '/config'
config_file_path = os.path.join(server_dir, 'config.json')

upload_path = '/data'
upload_dir = os.path.join(server_dir, 'uploads')

def read_config():
    config = None
    try:
        with open(config_file_path) as config_file:
            config = config_file.read()
    except IOError:
        pass
    return config

def backup_file(filepath):
    shutil.move(filepath, filepath + '.' + str(int(time.time()*1000)) + '.bak')

def write_file(filename, file):
    if not os.path.exists(upload_dir):
        os.mkdir(upload_dir)
    filepath = os.path.join(upload_dir, filename)
    if os.path.exists(filepath):
        backup_file(filepath)
    with open(filepath, 'wb') as output_file:
        while True:
            chunk = file.read(1024)
            if not chunk:
                break
            output_file.write(chunk)

class RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        parsed_url = urlparse.urlparse(self.path)
        if parsed_url.path == config_path:
            config = read_config()
            if config:
                self.send_response(200)
                self.end_headers()
                self.wfile.write(config)
            else:
                self.send_error(500)
        elif parsed_url.path == upload_path:
            self.send_error(405)
        else:
            self.send_error(404)

    def do_POST(self):
        parsed_url = urlparse.urlparse(self.path)
        path = parsed_url.path
        ctype, pdict = cgi.parse_header(self.headers['Content-Type']) 
        if path == upload_path:
            if ctype=='multipart/form-data':
                form = cgi.FieldStorage(self.rfile, self.headers, environ={'REQUEST_METHOD':'POST'})
                try:
                    fileitem = form["uploadedfile"]
                    if fileitem.file:
                        try:
                            write_file(fileitem.filename, fileitem.file)
                        except Exception as e:
                            print e
                            self.send_error(500)
                        else:
                            self.send_response(200)
                            self.end_headers()
                            self.wfile.write("OK")
                        return
                except KeyError:
                    pass
            # Bad request
            self.send_error(400)
        elif parsed_url.path == config_path:
            self.send_error(405)
        else:
            self.send_error(404)


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""                


if __name__ == '__main__':
    if sys.argv[1:]:
        port = int(sys.argv[1])
    else:
        port = 8000
    server_address = ('', port)
    httpd = ThreadedHTTPServer(server_address, RequestHandler)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    print 'use <Ctrl-C> to stop'
    httpd.serve_forever()

4 个答案:

答案 0 :(得分:6)

如果你想在Apache之类的东西上运行CGI(而不是像你上面粘贴的自定义服务器代码那样),你可以在(.py)启用CGI的目录中创建这样的.py文件。

#!/usr/bin/env python
print "Content-Type: text/html"
print
print 'Hello World'

如果你正在使用Apache,那么这里是some info on how to set up CGI executables

编辑(正如Adrien P.所说,Python脚本应该是可执行的。)

答案 1 :(得分:0)

您不必将其放入cgi-bin目录。

如果您正在运行Windows,则可以从python条目下的开始菜单启动Idle。粘贴代码,然后按F5运行代码。

如果您正在运行* nix,请查看Adrien对命令的回答并复制运行./your_script.py时输出的内容。

您是否尝试使用Python编写网站?这是用于创建Web 服务器的代码,而不是站点,因此在Web浏览器中导航到该程序将不会产生任何结果。

答案 2 :(得分:0)

Heroku是托管和python脚本的好地方。

<强>预-REQ

pythonscripts.py
procfile
requirements.txt

并添加,提交并将脚本推送到heroku应用程序。只需在终端上运行以下命令即可运行脚本。

heroku run python your_scripts.py

如果您想按计划时间运行此脚本,请执行更多操作。然后heroku提供了很多附加功能。只需在heroku上搜索

答案 3 :(得分:-1)

$ chmod +x your_script.py
$ ./your_script.py

快速查看您的代码:它启动一个简单的http服务器,他在端口8000上监听