Bottle.py附带一个导入来处理抛出HTTPErrors和路由到一个函数。
首先,文档声称我可以(以及几个例子):
from bottle import error
@error(500)
def custom500(error):
return 'my custom message'但是,当导入此语句时,错误没有得到解决,但在运行时,应用程序会忽略这一点,而只是将我引导到泛型错误页面。
我找到了一种绕过这一切的方法:
from bottle import Bottle
main = Bottle()
@Bottle.error(main, 500)
def custom500(error):
return 'my custom message'但是,这段代码阻止我将错误全部嵌入到单独的模块中,以控制如果我将错误保存在main.py模块中就会产生的不良后果,因为第一个参数必须是一个瓶子实例。
所以我的问题是:
发布于 2011-08-24 12:08:31
如果要将错误嵌入到另一个模块中,可以执行以下操作:
error.py
def custom500(error):
return 'my custom message'
handler = {
500: custom500,
}app.py
from bottle import *
import error
app = Bottle()
app.error_handler = error.handler
@app.route('/')
def divzero():
return 1/0
run(app)发布于 2011-08-24 12:05:56
这对我来说很管用:
from bottle import error, run, route, abort
@error(500)
def custom500(error):
return 'my custom message'
@route("/")
def index():
abort("Boo!")
run()发布于 2016-01-30 17:18:51
在某些情况下,我发现更好的细分瓶。下面是一个这样做并添加自定义错误处理程序的示例。
#!/usr/bin/env python3
from bottle import Bottle, response, Route
class MyBottle(Bottle):
def __init__(self, *args, **kwargs):
Bottle.__init__(self, *args, **kwargs)
self.error_handler[404] = self.four04
self.add_route(Route(self, "/helloworld", "GET", self.helloworld))
def helloworld(self):
response.content_type = "text/plain"
yield "Hello, world."
def four04(self, httperror):
response.content_type = "text/plain"
yield "You're 404."
if __name__ == '__main__':
mybottle = MyBottle()
mybottle.run(host='localhost', port=8080, quiet=True, debug=True)https://stackoverflow.com/questions/7174886
复制相似问题