This article describes how to return static files and JSON objects in the Python Bottle framework. The Bottle framework is very popular among Python developers. For more information, see the following code:
#-*-Coding: UTF-8 -*-#! /Usr/bin/python # filename: todo. py # codedtime: 2014-8-28 20: 50: 44 import sqlite3import bottle @ bottle. route ('/help3') def help (): return bottle.static_file('help.html ', root = '. ') # static file @ bottle. route ('/json: json # [0-9] + #') def show_json (json): conn = sqlite3.connect ('todo. db') c = conn. cursor () c.exe cute ("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]} # return the Json object bottle. debug (True) bottle. run (host = '2017. 0.0.1 ', port = 8080, reloader = True)
The first route @ bottle. route ('/help3') returns a static question. Enter http: // 127.0.0.1: 8080/help3 in the browser.
The result is as follows:
Root = '. ') or root = '. /') indicates that it is in the current directory of the program. Of course, you can also know other paths, such as root ='/path/to/file'
The second route @ bottle. route ('/json: json # [0-9] + #') returns a Json object. In the browser, enter: http: // 127.0.0.1: 8080/json4
The result is as follows:
The Web program will inevitably encounter access failure errors, so how to capture these errors, Bottle can use the crash mechanism to capture errors, as shown in the following capture 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!'
Other error handling methods are as follows!