代碼如下:
# -*- coding: utf-8 -*-#!/usr/bin/python# filename: todo.py# codedtime: 2014-8-28 20:50:44import sqlite3import bottle @bottle.route('/help3')def help(): return bottle.static_file('help.html', root='.') #靜態文件@bottle.route('/json:json#[0-9]+#')def show_json(json): conn = sqlite3.connect('todo.db') c = conn.cursor() c.execute("SELECT task FROM todo WHERE id LIKE ?", (json)) result = c.fetchall() c.close() if not result: return {'task':'This item number does not exist!'} else: return {'Task': result[0]} #返回Json對象bottle.debug(True)bottle.run(host='127.0.0.1', port=8080, reloader = True)第一個路由@bottle.route('/help3') 返回一個靜態問,在瀏覽器中輸入:http://127.0.0.1:8080/help3
結果如下:

其中的 root='.')或 root='./')表示在程序當前目錄下,當然你也可以知道其他的路徑如: root='/path/to/file'
第二個路由@bottle.route('/json:json#[0-9]+#')返回一個Json對象,在瀏覽器中輸入:http://127.0.0.1:8080/json4
結果如下:

Web程序難免會遇到訪問失敗的錯誤,那么怎樣去捕獲這些錯誤,Bottle可以用路由機制來捕捉錯誤,如下捕獲403、404:
@error(403)def mistake403(code): return 'The parameter you passed has the wrong format!'@error(404)def mistake404(code): return 'Sorry, this page does not exist!'
其他錯誤處理如法泡制!
新聞熱點
疑難解答
圖片精選