Python的Bottle框架中返回靜態(tài)文件和JSON對象的方法
代碼如下:
# -*- coding: utf-8 -*- #!/usr/bin/python # filename: todo.py # codedtime: 2014-8-28 20:50:44 import sqlite3 import bottle @bottle.route('/help3') def help(): return bottle.static_file('help.html', root='.') #靜態(tài)文件 @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') 返回一個靜態(tài)問,在瀏覽器中輸入:http://127.0.0.1:8080/help3
結(jié)果如下:
其中的 root='.')或 root='./')表示在程序當前目錄下,當然你也可以知道其他的路徑如: root='/path/to/file'
第二個路由@bottle.route('/json:json#[0-9]+#')返回一個Json對象,在瀏覽器中輸入:http://127.0.0.1:8080/json4
結(jié)果如下:
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!'
其他錯誤處理如法泡制!
相關(guān)文章
pytorch機器學(xué)習(xí)softmax回歸的簡潔實現(xiàn)
這篇文章主要介紹了為大家介紹了pytorch機器學(xué)習(xí)中softmax回歸的簡潔實現(xiàn)方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10Python的代理類實現(xiàn),控制訪問和修改屬性的權(quán)限你都了解嗎
這篇文章主要為大家詳細介紹了Python的代理類實現(xiàn),控制訪問和修改屬性的權(quán)限,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03深入淺析Python中l(wèi)ist的復(fù)制及深拷貝與淺拷貝
這篇文章主要介紹了Python中l(wèi)ist的復(fù)制及深拷貝與淺拷貝及區(qū)別解析 ,需要的朋友可以參考下2018-09-09總結(jié)Python函數(shù)參數(shù)的六種類型
這篇文章主要總結(jié)了Python函數(shù)參數(shù)的六種類型,傳遞參數(shù)實現(xiàn)不同場景的靈活使用,下面總結(jié)的六種函數(shù)參數(shù)類型,需要的小伙伴可以參考一下2022-03-03