Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python CGIHTTPServer默认目录_Python_Cgi_Httpserver_Cgihttpserver_Cgihttprequesthandler - Fatal编程技术网

Python CGIHTTPServer默认目录

Python CGIHTTPServer默认目录,python,cgi,httpserver,cgihttpserver,cgihttprequesthandler,Python,Cgi,Httpserver,Cgihttpserver,Cgihttprequesthandler,我为CGI处理HTTP服务器提供了以下最低限度的代码,这些代码来自内部管道上的几个示例: #!/usr/bin/env python import BaseHTTPServer import CGIHTTPServer import cgitb; cgitb.enable() # Error reporting server = BaseHTTPServer.HTTPServer handler = CGIHTTPServer.CGIHTTPRequestHandler server_a

我为CGI处理HTTP服务器提供了以下最低限度的代码,这些代码来自内部管道上的几个示例:

#!/usr/bin/env python

import BaseHTTPServer
import CGIHTTPServer
import cgitb;

cgitb.enable()  # Error reporting

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = [""]

httpd = server(server_address, handler)
httpd.serve_forever()
然而,当我执行脚本并尝试通过CGI使用
http://localhost:8000/test.py
,我看到的是脚本的文本,而不是执行的结果

权限都设置正确,测试脚本本身也不是问题(因为当脚本驻留在cgi-bin中时,我可以使用
python-mcgihttpserver
很好地运行它)。我怀疑这个问题与默认的CGI目录有关


如何让脚本执行?我的怀疑是正确的。从中派生此代码的示例显示了将默认目录设置为服务器脚本所在的同一目录的错误方法。要以这种方式设置默认目录,请使用:

handler.cgi_directories = ["/"]

警告:如果您不在任何类型的防火墙后面,这将打开潜在的巨大安全漏洞。这只是一个有启发性的例子。请务必小心使用。

如果.cgi_目录需要多层子目录(
['/db/cgi-bin']
),则解决方案似乎不起作用(至少对我而言)。对服务器进行子类化并更改
is\u cgi
def似乎是可行的。以下是我在您的脚本中添加/替换的内容:

from CGIHTTPServer import _url_collapse_path
class MyCGIHTTPServer(CGIHTTPServer.CGIHTTPRequestHandler):  
  def is_cgi(self):
    collapsed_path = _url_collapse_path(self.path)
    for path in self.cgi_directories:
        if path in collapsed_path:
            dir_sep_index = collapsed_path.rfind(path) + len(path)
            head, tail = collapsed_path[:dir_sep_index], collapsed_path[dir_sep_index + 1:]
            self.cgi_info = head, tail
            return True
    return False

server = BaseHTTPServer.HTTPServer
handler = MyCGIHTTPServer

下面是如何将服务器上的每个.py文件都设置为cgi文件(您可能不希望将其用于生产/公共服务器;):


谢谢你的回答!这帮助我整理出一个只使用Python的服务器,这是我多年来一直在尝试的。值得指出的是,规范的“正确的”shebang是“#!/usr/bin/env python”-我以前就被它抓住了@scubbo-很高兴我的挣扎能为你提供一些清晰的信息。我已经按照你的建议更新了shebang。谢谢
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()

server = BaseHTTPServer.HTTPServer

# Treat everything as a cgi file, i.e.
# `handler.cgi_directories = ["*"]` but that is not defined, so we need
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):  
  def is_cgi(self):
    self.cgi_info = '', self.path[1:]
    return True

httpd = server(("", 9006), Handler)
httpd.serve_forever()