Python的Bottle框架中返回静态文件和JSON对象的方法
作者:JohnnyHu90 发布时间:2023-11-07 20:14:41
标签: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
结果如下:
其中的 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!'
其他错误处理如法泡制!
0
投稿
猜你喜欢
- http://serverName/appName/module/action/id/1/这个就是pathinfo模式在不考虑路由的情况下,
- 在数据库中有时我们可能需要对一些数据进行处理,例如四舍五入、直接舍去后面的几位等,其实很简单,都是有现成的函数,我们只需要套用就行了:sel
- 前言:最近在探索用Go来读取文件,读取文本时发现,对于单行超长的文本,我的Go代码无法处理。经过查阅才发现,Go提供的Scanner无法读取
- Menu(菜单)组件用于实现顶级菜单、下拉菜单和弹出菜单。何时使用 Menu 组件?Menu 组件通常被用于实现应用程序上的各种菜单,由于该
- 昨天晚上跑起来一个classification实验,今天发现训练loss在降,然而accuracy永远是0 。。。直觉告诉我evaluati
- pip用pipdeptree查看包依赖1、安装pipdeptreepip install pipdeptree2、使用pipdeptree查
- 前言MySQL提供了众多功能强大、方便易用的函数,使用这些函数,可以极大地提高用户对于数据库的管理效率,从而更加灵活地满足不同用户的需求。本
- 首先感谢朋友们对第一篇文章的鼎力支持,感动中....... 今天说的是选择排序,包括“直接选择排序”和“堆排序”。话说
- 1.画最简单的直线图代码如下:import numpy as np import matplotlib.pyplot as plt x=[0
- 一、Python 操作 Excel 的常用库小伙伴你好,在开始操作 Excel 之前,你需要安装 Python 和一些相关库。可以使用 pi
- vue组件在prop里根据type决定传值还是传引用。简要如下:传值:String、Number、Boolean传引用:Array、Obje
- 一、获取Tensor神经网络在运算过程中实际上是以Tensor为格式进行计算的,我们只需稍稍改动一下forward函数即可从运算过程中抓到T
- SQL语句举例:SELECT * FROM `test` WHERE `id`=1;当我们输入一条SQL语句,返回一个结果时,那这条语句在
- 引言vcf文件的全称是variant call file,即突变识别文件,它是基因组工作流程中产生的一种文件,保存的是基因组上的突变信息。通
- 本博文源于绘图基础,主要讲解如何用python的plot绘制气温的折线图。先讲解plot参数如何使用后给出一个气温折线图样例绘制使用plot
- 基本使用import unittestclass Testcase(unittest.TestCase): @classmeth
- ALTER TABLE将表更改为当前字符集。如果在执行ALTER TABLE操作期间遇到重复键错误,原因在于新的字符集将2个键映射到了相同值
- 项目地址:https://github.com/PythonerKK/django-generate-pdf/tree/master这个de
- 本文实例讲述了PHP实现的随机IP函数。分享给大家供大家参考,具体如下:function get_rand_ip(){ $arr
- 这篇文章主要介绍了简单了解Python3 bytes和str类型的区别和联系,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的