The method for returning static files and JSON objects in the Python Bottle framework,

Source: Internet
Author: User

The method for returning static files and JSON objects in the Python Bottle framework,

The Code is as follows:

#-*-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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.