繁体   English   中英

Bottle.py错误路由

[英]Bottle.py error routing

Bottle.py附带一个导入来处理抛出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模块中会产生的肮脏,因为第一个参数必须是一个瓶子实例。

所以我的问题:

  1. 还有其他人经历过这个吗?

  2. 为什么没有错误似乎只解决我的情况(我从pip安装瓶安装 )?

  3. 是否有一种无缝方式将我的错误路由从单独的python模块导入主应用程序?

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

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)

这对我有用:

from bottle import error, run, route, abort

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

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

run()

在某些情况下,我发现继承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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM