Bottle.py error routing

前端 未结 3 955
再見小時候
再見小時候 2021-02-13 03:46

Bottle.py ships with an import to handle throwing HTTPErrors and route to a function.

Firstly, the documentation claims I can (and so do several examples):



        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 04:21

    In some cases I find it's better to subclass Bottle. Here's an example of doing that and adding a custom error handler.

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

提交回复
热议问题