【问题标题】:Bottle.py error routingBottle.py 错误路由
【发布时间】:2011-11-02 17:52:06
【问题描述】:

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 模块中会出现的问题,因为第一个参数必须是一个瓶子实例。

所以我的问题:

  1. 有其他人经历过这种情况吗?

  2. 为什么 error 似乎只在我的情况下无法解决(我从 pip install bottle 安装)?

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

【问题讨论】:

    标签: python bottle


    【解决方案1】:

    在某些情况下,我发现子类化 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)
    

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

        【解决方案3】:

        这对我有用:

        from bottle import error, run, route, abort
        
        @error(500)
        def custom500(error):
            return 'my custom message'
        
        @route("/")
        def index():
            abort("Boo!")
        
        run()
        

        【讨论】:

          猜你喜欢
          • 2014-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-02
          • 1970-01-01
          • 1970-01-01
          • 2020-06-28
          • 1970-01-01
          相关资源
          最近更新 更多