• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-07) 23次浏览 已收录 0个评论

这篇文章主要介绍了Python的Bottle框架中返回静态文件和JSON对象的方法,Bottle框架在Python开发者中具有很高的人气,需要的朋友可以参考下

代码如下:

 # -*- 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='.') #静态文件 @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': <div style="color:transparent">来源gaodai.ma#com搞##代!^码网</div>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!' 

其他错误处理如法泡制!

以上就是Python的Bottle框架中返回静态文件和JSON对象的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python的Bottle框架中返回静态文件和JSON对象的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址