[英]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模塊中會產生的骯臟,因為第一個參數必須是一個瓶子實例。
所以我的問題:
還有其他人經歷過這個嗎?
為什么沒有錯誤似乎只解決我的情況(我從pip安裝瓶安裝 )?
是否有一種無縫方式將我的錯誤路由從單獨的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.