如何在CGI服务器中配置索引文件



我刚刚在Python中制作了一个服务器(仅用于localhost),通过CGI执行并尝试我的Python脚本。以下是执行服务器的文件代码:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import BaseHTTPServer
import CGIHTTPServer
import cgitb
cgitb.enable()  ## This line enables CGI error reporting
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = ["/"]
httpd = server(server_address, handler)
httpd.serve_forever()

当我访问一些脚本在服务器(http://127.0.0.1:8000/index.py)没有问题,但当我访问服务器(http://127.0.0.1:8000/)它显示:

Error response
Error code 403.
Message: CGI script is not executable ('//').
Error code explanation: 403 = Request forbidden -- authorization will not help.

这就像如果索引文件没有被设置为默认文件访问时,访问文件夹而不是一个特定的文件…

我希望在访问http://127.0.0.1/时能够访问http://127.0.0.1/index.py

Python的内置HTTP服务器是非常基本的,所以它不包括这样的功能。但是,您可以通过子类化CGIHTTPRequestHandler来实现它,可能替换is_cgi函数。

如果您使用handler.cgi_directories = ["/cgi"],您可以在"/"中放置index.html文件。当然,如果你想要一个默认的cgi脚本index.py,你可以使用index.html来转发…

我确实尝试修改is_cgi函数,它正在工作!

def is_cgi(self):
    collapsed_path = _url_collapse_path(self.path)
    if collapsed_path == '//':
        self.path = '/index.py'
        collapsed_path = _url_collapse_path(self.path)
    dir_sep = collapsed_path.find('/', 1)
    head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep + 1:]
    if head in self.cgi_directories:
        self.cgi_info = head, tail
        return True
    return False

我把这个方法放到下面的类中:

class CGIHandlerOverloadIndex(CGIHTTPServer.CGIHTTPRequestHandler):

最新更新