我使用CherryPy来运行一个非常简单的web服务器。它的目的是处理GET
参数,如果它们是正确的,则对它们执行某些操作。
import cherrypy
class MainServer(object):
def index(self, **params):
# do things with correct parameters
if 'a' in params:
print params['a']
index.exposed = True
cherrypy.quickstart(MainServer())
例如,
http://127.0.0.1:8080/abcde:
404 Not Found
The path '/abcde' was not found.
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 656, in respond
response.body = self.handler()
File "C:\Python27\lib\site-packages\cherrypy\lib\encoding.py", line 188, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 386, in __call__
raise self
NotFound: (404, "The path '/abcde' was not found.")
Powered by CherryPy 3.2.4
我试图捕捉这个异常并显示一个空白页面,因为客户端并不关心它。具体地说,无论是导致异常的url还是查询字符串,结果都将是一个空的正文。
我看过有关错误处理cherrypy._cperror
的文档,但我没有找到实际使用它的方法。
编辑:我放弃了使用CherryPy
,使用BaseHTTPServer
找到了一个简单的解决方案(参见下面我的答案,被否决了,因为它解决了问题,但没有回答问题...sigh...)
发布于 2019-03-01 03:12:09
文档似乎不知何故遗漏了这一部分。这是我在从源代码中寻找自定义错误处理的详细解释时发现的。
自定义错误处理
预期的HTTP响应
'error_page‘配置名称空间可用于为预期的响应(如404not Found)提供自定义的HTML输出。提供将从中读取输出的文件名。内容将使用普通的老Python string formatting使用值%(状态)s、%(消息)s、%(回溯)s和%(版本)s进行插值。
_cp_config = {
'error_page.404': os.path.join(localDir, "static/index.html")
}
从3.1版开始,您还可以提供一个函数或其他可调用的error_page条目。将向其传递插入到模板中的相同状态、消息、回溯和版本参数
def error_page_402(status, message, traceback, version):
return "Error %s - Well, I'm very sorry but you haven't paid!" % status
cherrypy.config.update({'error_page.402': error_page_402})
同样在3.1中,除了编号的错误代码之外,您还可以提供error_page.default
来处理没有自己的error_page条目的所有代码。
意料之外的错误
CherryPy还有一个通用的错误处理机制:每当代码中出现意外错误时,它都会调用Request.error_response
来设置响应状态、头和正文。默认情况下,这与HTTPError(500)
的输出相同。如果你想提供一些其他的行为,你通常需要替换"request.error_response“。
下面是一些示例代码,说明如何显示自定义错误消息并发送包含错误的电子邮件
from cherrypy import _cperror
def handle_error():
cherrypy.response.status = 500
cherrypy.response.body = [
"<html><body>Sorry, an error occurred</body></html>"
]
sendMail('error@domain.com',
'Error in your web app',
_cperror.format_exc())
@cherrypy.config(**{'request.error_response': handle_error})
class Root:
pass
请注意,您必须显式设置response.body
,而不是简单地返回一条错误消息。
发布于 2013-12-06 01:27:59
CherryPy 正在捕获您的异常。这就是它向浏览器返回带有捕获的异常的有效页面的方式。
我建议您通读所有的文档。我知道这不是最好的文档,也不是组织得很好,但如果你至少浏览一下,这个框架会更有意义。它是一个很小的框架,但它几乎完成了您对应用程序服务器的所有期望。
import cherrypy
def show_blank_page_on_error():
"""Instead of showing something useful to developers but
disturbing to clients we will show a blank page.
"""
cherrypy.response.status = 500
cherrypy.response.body = ''
class Root():
"""Root of the application"""
_cp_config = {'request.error_response': show_blank_page_on_error}
@cherrypy.expose
def index(self):
"""Root url handler"""
raise Exception
有关上述页面上的文档中的示例,请参阅this以获得进一步的参考。
发布于 2013-12-06 05:09:15
选择最适合你的:Default Methods,Custom Error Handling。
我不认为你应该使用BaseHTTPServer
。如果你的应用程序这么简单,那就买一个轻量级的框架(比如Flask),尽管它可能有点夸张,或者保持较低的水平,但仍然在WSGI标准之内,并使用一个符合WSGI的服务器。
https://stackoverflow.com/questions/20395565
复制相似问题