国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python的Bottle框架中返回靜態文件和JSON對象的方法

2019-11-25 17:34:25
字體:
來源:轉載
供稿:網友

代碼如下:

# -*- 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

結果如下:

2015430174409809.png (313×137)

其中的 root='.')或 root='./')表示在程序當前目錄下,當然你也可以知道其他的路徑如: root='/path/to/file'

第二個路由@bottle.route('/json:json#[0-9]+#')返回一個Json對象,在瀏覽器中輸入:http://127.0.0.1:8080/json4

結果如下:

2015430174429421.png (376×141)

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!'

其他錯誤處理如法泡制!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商城县| 陆川县| 老河口市| 南溪县| 明溪县| 双鸭山市| 汝城县| 阜康市| 资溪县| 永平县| 乌拉特后旗| 邹城市| 无极县| 惠州市| 焦作市| 和龙市| 南京市| 右玉县| 新郑市| 法库县| 莒南县| 涟水县| 灵宝市| 高台县| 芜湖市| 特克斯县| 安陆市| 万源市| 周至县| 高尔夫| 敖汉旗| 涿州市| 资阳市| 铜鼓县| 卓尼县| 扶风县| 南投县| 延寿县| 盘锦市| 那坡县| 平阴县|