当前位置:Gxlcms > Python > Python的Bottle框架中返回静态文件和JSON对象的方法

Python的Bottle框架中返回静态文件和JSON对象的方法

时间:2021-07-01 10:21:17 帮助过:74人阅读

代码如下:

  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/python
  3. # filename: todo.py
  4. # codedtime: 2014-8-28 20:50:44
  5. import sqlite3
  6. import bottle
  7. @bottle.route('/help3')
  8. def help():
  9. return bottle.static_file('help.html', root='.') #静态文件
  10. @bottle.route('/json:json#[0-9]+#')
  11. def show_json(json):
  12. conn = sqlite3.connect('todo.db')
  13. c = conn.cursor()
  14. c.execute("SELECT task FROM todo WHERE id LIKE ?", (json))
  15. result = c.fetchall()
  16. c.close()
  17. if not result:
  18. return {'task':'This item number does not exist!'}
  19. else:
  20. return {'Task': result[0]} #返回Json对象
  21. bottle.debug(True)
  22. 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:

  1. @error(403)
  2. def mistake403(code):
  3. return 'The parameter you passed has the wrong format!'
  4. @error(404)
  5. def mistake404(code):
  6. return 'Sorry, this page does not exist!'

其他错误处理如法泡制!

人气教程排行