这个问题(Python CGIHTTPServer默认目录)详细介绍了如何为Python CGIHTTPServer设置cgi-bin文件位置的路径。通过测试,您似乎不能将.py和.html文件混合在同一个文件夹中:在cgi-bin中,它可以很好地处理.py文件,但是需要提供一个静态的html文件。
127.0.0.1 - - [08/Jan/2017 10:51:22] "GET /dev.html HTTP/1.1" 200 -
Traceback (most recent call last):
File "/usr/lib/python2.7/CGIHTTPServer.py", line 248, in run_cgi
os.execve(scriptfile, args, env)
OSError: [Errno 8] Exec format error
127.0.0.1 - - [08/Jan/2017 10:51:22] CGI script exit status 0x7f00这是真正的故意行为,还是我遗漏了什么?稀疏而不透明的文档说:“但是,如果类猜测CGI脚本是CGI脚本,那么类将运行CGI脚本,而不是作为文件提供它。只有使用基于目录的CGI,另一种常见的服务器配置是将特殊的扩展视为表示CGI脚本。”
如何“将特殊扩展视为CGI脚本的表示”。我应该使用什么方法或设置,或者我应该说什么魔法词?或者这只是一个粗俗的暗示,我就是做不到?
我只将它用于快速测试,虽然我可以重组为分离.py和.html文件,但我还有其他限制,这将使这成为一个痛苦的练习。
发布于 2017-01-08 13:10:02
我从is_cgi()中提取了oryginal is_cgi(),并添加了两个元素
CGIHTTPServer. in CGIHTTPServer._url_collapse_path(self.path)以在文件CGIHTTPServer.py之外使用它我没有用
if tail.endswith('.py'):因为如果需要的话,服务器可以用其他语言执行脚本。Perl、PHP、Bash等。
代码:
import BaseHTTPServer
import CGIHTTPServer
class MyHandler(CGIHTTPServer.CGIHTTPRequestHandler):
# code from oryginal CGIHTTPServer.py
def is_cgi(self):
# v added `CGIHTTPServer.`
collapsed_path = CGIHTTPServer._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:
if not tail.endswith('.html'): # <-- new line
#if tail.endswith('.py'): # <-- new line
self.cgi_info = head, tail
return True
return False
# --- test ---
MyHandler.cgi_directories = ['/']
server = BaseHTTPServer.HTTPServer(('', 8000), MyHandler)
server.serve_forever()发布于 2017-01-08 12:29:22
您需要检测请求的文件类型(py/cgi还是静态文件)。Mimetype可能会有帮助。当请求一个静态文件时,您可以调用另一个交付静态文件的cgi脚本。顺便说一句。您应该使用wsgi,而不是过时的cgi。
我修改了一些我得到的旧代码(py2.7) --这很难看,我从未使用过它--但是当您将静态文件'dev.html‘放在'handler.cgi_directory’中时,应该由static.py提供服务。
server.py:
#!/usr/bin/python2
import BaseHTTPServer
import CGIHTTPServer
from mimetypes import MimeTypes
import urllib
class handler(CGIHTTPServer.CGIHTTPRequestHandler):
def is_cgi(self):
mime = MimeTypes()
request = self.path.split('?')
if len(request) == 2:
path, args = request
else:
path, args = request, None
if isinstance(path, list):
path = path[0]
url = urllib.pathname2url(path)
mime_type = mime.guess_type(url)
if 'python' in mime_type[0]:
self.cgi_info = '', self.path[1:]
return True
else:
self.cgi_info = '', '/static.py?path=%s' % path[1:]
print self.cgi_info
return True
server = BaseHTTPServer.HTTPServer
server_address = ("", 8000)
handler.cgi_directories = ["/somedir/..."]
httpd = server(server_address, handler)
httpd.serve_forever()static.py:
#!/usr/bin/python2
import cgi
import urllib
from mimetypes import MimeTypes
form = cgi.FieldStorage()
mime = MimeTypes()
path = form.getvalue('path')
url = urllib.pathname2url(path)
mime_type = mime.guess_type(url)
print """Content-type: %s""" % mime
print
print open(path, 'r').read()https://stackoverflow.com/questions/41532074
复制相似问题