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

yipeiwu_com5年前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': 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!'

其他错误处理如法泡制!

相关文章

利用python的socket发送http(s)请求方法示例

利用python的socket发送http(s)请求方法示例

前言 这是个在写计算机网络课设的时候碰到的问题,卡了我一天,所以总结一下。 其实在之前就有用requests写过python爬虫,但是计算机网络要求更底层的实现,刚好我看到了[这篇文章]...

python中 * 的用法详解

1、表示乘号 2、表示倍数,例如: def T(msg,time=1): print((msg+' ')*time) T('hi',3) 打印结果(打印3次): hi h...

python深copy和浅copy区别对比解析

这篇文章主要介绍了python深copy和浅copy区别对比解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 首先先看一段代码...

对变量赋值的理解--Pyton中让两个值互换的实现方法

#Pyton中让两个值互换的实现方法 #方法一:可以理解为相当于是同时赋值 a = 5 b = 4 a,b = b,a print(a,b) #方法二:可以理解为拿箱子过程 c...

Python3调用微信企业号API发送文本消息代码示例

本文主要向大家分享了Python3调用微信企业号API发送文本消息示例的有关代码,具体如下: #!/usr/bin/env python # -*- coding:utf-8 -*-...