【发布时间】:2014-09-12 03:44:07
【问题描述】:
我正在使用CGIHTTPServer.py 创建简单的 CGI 服务器。如果某些操作出错,我希望我的 CGI 脚本处理响应代码。我该怎么做?
我的 CGI 脚本中的代码 sn-p。
if authmxn.authenticate():
stats = Stats()
print "Content-Type: application/json"
print 'Status: 200 OK'
print
print json.dumps(stats.getStats())
else:
print 'Content-Type: application/json'
print 'Status: 403 Forbidden'
print
print json.dumps({'msg': 'request is not authenticated'})
一些来自请求处理程序的sn-p,
def run_cgi(self):
'''
rest of code
'''
if not os.path.exists(scriptfile):
self.send_error(404, "No such CGI script (%s)" % `scriptname`)
return
if not os.path.isfile(scriptfile):
self.send_error(403, "CGI script is not a plain file (%s)" %
`scriptname`)
return
ispy = self.is_python(scriptname)
if not ispy:
if not (self.have_fork or self.have_popen2):
self.send_error(403, "CGI script is not a Python script (%s)" %
`scriptname`)
return
if not self.is_executable(scriptfile):
self.send_error(403, "CGI script is not executable (%s)" %
`scriptname`)
return
if not self.have_fork:
# Since we're setting the env in the parent, provide empty
# values to override previously set values
for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
'HTTP_USER_AGENT', 'HTTP_COOKIE'):
env.setdefault(k, "")
self.send_response(200, "Script output follows") # overrides the headers
decoded_query = query.replace('+', ' ')
【问题讨论】:
-
究竟是什么问题?你所拥有的似乎应该可以工作。你在谈论异常处理吗? (在这种情况下,您可以捕获异常并返回 http 响应代码 500 内部服务器错误。
-
@mhawke 你可以在上面的评论中检查上面的代码,你会看到它的覆盖标题。你明白这个问题了吗?