Bottle.py 路由错误

15 投票
3 回答
8986 浏览
提问于 2025-04-17 00:15

Bottle.py自带一个功能,可以处理抛出HTTPErrors(HTTP错误)并把请求引导到一个特定的函数。

首先,文档上说我可以这样做(很多例子也这么做):

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模块变得很乱,因为第一个参数必须是一个Bottle的实例。

所以我有几个问题:

  1. 有没有其他人遇到过这个问题?

  2. 为什么在我这里error似乎无法解决(我通过pip install bottle安装的)?

  3. 有没有一种简单的方法可以把我的错误处理从一个单独的Python模块导入到主应用程序中?

3 个回答

0

在某些情况下,我发现继承Bottle类会更好。下面是一个示例,展示了如何这样做,并添加一个自定义的错误处理器。

#!/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)
7

这个对我有效:

from bottle import error, run, route, abort

@error(500)
def custom500(error):
    return 'my custom message'

@route("/")
def index():
    abort("Boo!")

run()
26

如果你想把你的错误信息放到另一个模块里,你可以这样做:

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)

撰写回答