Methods for returning static files and JSON objects in the bottle framework of Python

Source: Internet
Author: User
The code is as follows:

#-*-Coding:utf-8-*-#!/usr/bin/python# filename:todo.py# codedtime:2014-8-28 20:50:44import sqlite3import 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 {' Ta ' SK ': ' 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)
  

The first route @bottle.route ('/HELP3 ') returns a static question, entered in the browser: HTTP://127.0.0.1:8080/HELP3

The results are as follows:

One of the root= '. ') or root= './') indicates that in the current directory of the program, 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, entered in the browser: http://127.0.0.1:8080/json4

The results are as follows:

Web programs will inevitably encounter errors in access failures, so how to catch these errors, bottle can use the routing mechanism to catch errors, the following captures 403, 404:

@error (403) def mistake403 (code):  return ' The parameter you passed have the wrong format! ' @error (404) def mistake404 (code):  return ' Sorry, this page does not exist! '

Other error handling such as the FA Bubble System!

  • 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.