Python,启动CGIHTTPServer并在同一脚本中启动浏览器

时间:2013-08-05 18:09:31

标签: python webserver cgi

我在下面有这个python代码,适用于从与脚本相同的目录提供的简单html页面。什么行不通,我想从cgi-bin目录运行一个cgi脚本。我的想法是拥有可移植的python,运行一个脚本,启动Web服务器并使用ajax,SQLite等提供cgi页面。

# helper to load url
# runs webserver and loads url with webbrowswer module
import sys

def load_url(path):
    PORT = 80
    httpd = StoppableHTTPServer(("127.0.0.1",PORT), handler)
    thread.start_new_thread(httpd.serve, ())
    webbrowser.open_new('http://localhost:%s/%s'%(PORT,path))
    input("Press <RETURN> to stop server\n")
    httpd.stop()
    print("To restart server run: \n%s"%server)


if sys.version_info[0] == 2:
    import BaseHTTPServer, CGIHTTPServer
    import cgitb; cgitb.enable()  ## This line enables CGI error reporting
    import socket
    import thread
    import webbrowser
    #handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    handler = CGIHTTPServer.CGIHTTPRequestHandler
    input = raw_input
    server = "python -m SimpleHTTPServer 80"

    class StoppableHTTPServer(BaseHTTPServer.HTTPServer):

        def server_bind(self):
            BaseHTTPServer.HTTPServer.server_bind(self)
            self.socket.settimeout(1)
            self.run = True

        def get_request(self):
            while self.run:
                try:
                    sock, addr = self.socket.accept()
                    sock.settimeout(None)
                    return (sock, addr)
                except socket.timeout:
                    pass

        def stop(self):
            self.run = False

        def serve(self):
            while self.run:
                self.handle_request()


else:
    import http.server, http.server
    import socket
    import _thread as thread
    import webbrowser
    #handler = http.server.SimpleHTTPRequestHandler
    handler = http.server.CGIHTTPRequestHandler
    server = "python -m http.server 80"

    class StoppableHTTPServer(http.server.HTTPServer):

        def server_bind(self):
            http.server.HTTPServer.server_bind(self)
            self.socket.settimeout(1)
            self.run = True

        def get_request(self):
            while self.run:
                try:
                    sock, addr = self.socket.accept()
                    sock.settimeout(None)
                    return (sock, addr)
                except socket.timeout:
                    pass

        def stop(self):
            self.run = False

        def serve(self):
            while self.run:
                self.handle_request()

load_url("cgi-bin/page01.py")

0 个答案:

没有答案