亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python的Bottle框架中返回靜態(tài)文件和JSON對(duì)象的方法

 更新時(shí)間:2015年04月30日 17:45:33   作者:JohnnyHu90  
這篇文章主要介紹了Python的Bottle框架中返回靜態(tài)文件和JSON對(duì)象的方法,Bottle框架在Python開(kāi)發(fā)者中具有很高的人氣,需要的朋友可以參考下

代碼如下:

# -*- 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對(duì)象

bottle.debug(True)
bottle.run(host='127.0.0.1', port=8080, reloader = True)

 第一個(gè)路由@bottle.route('/help3') 返回一個(gè)靜態(tài)問(wèn),在瀏覽器中輸入:http://127.0.0.1:8080/help3

結(jié)果如下:

2015430174409809.png (313×137)

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

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

結(jié)果如下:

2015430174429421.png (376×141)

Web程序難免會(huì)遇到訪問(wèn)失敗的錯(cuò)誤,那么怎樣去捕獲這些錯(cuò)誤,Bottle可以用路由機(jī)制來(lái)捕捉錯(cuò)誤,如下捕獲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!'

其他錯(cuò)誤處理如法泡制!

相關(guān)文章

最新評(píng)論