2011-08-24 109 views
14

Bottle.py附帶一個導入來處理拋出HTTPErrors和路由到一個函數。Bottle.py錯誤路由

首先,文件要求,我可以(並且這樣做的幾個例子):

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' 

但這段代碼使我不能嵌入都在一個單獨的模塊,我的錯誤控制,如果我讓他們在我的主會隨之而來的污穢。 py模塊,因爲第一個參數必須是瓶子實例。

所以我的問題:

  1. 有其他人遇到此?

  2. 爲什麼不錯誤似乎只有我的情況(我從安裝PIP安裝瓶)來解決?

  3. 是否有一種無縫的方式將我的錯誤路由從單獨的python模塊導入到主應用程序中?

回答

24

如果你想嵌入另一個模塊中你的錯誤,你可以做這樣的事情:

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) 
+0

哇。那簡單而完美。 – comamitc

7

這個工作對我來說:

from bottle import error, run, route, abort 

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

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

run() 
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)