Bottle.py错误路由

2024-03-29 01:18:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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模块中会导致的混乱,因为第一个参数必须是一个瓶子实例。

所以我的问题是:

  1. 还有人经历过吗?

  2. 为什么错误似乎只在我的情况下解决了(我是从pip install bottle安装的)?

  3. 有没有一种无缝的方法可以将错误路由从一个单独的python模块导入到主应用程序中?


Tags: 模块frompyimport路由bottlereturnmain
3条回答

如果要将错误嵌入到另一个模块中,可以执行以下操作:

错误.py

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

handler = {
    500: custom500,
}

应用程序py

from bottle import *
import error

app = Bottle()
app.error_handler = error.handler

@app.route('/')
def divzero():
    return 1/0

run(app)

这对我有效:

from bottle import error, run, route, abort

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

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

run()

在某些情况下,我发现最好将瓶子分类。下面是一个这样做并添加自定义错误处理程序的示例。

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

相关问题 更多 >