$ ls ~yifei/notes/

Python bottle 库的使用

Posted on:

Last modified:

In this section, we run bottle in default app mode, which means we do not make a Bottle instance explicitly

from bottle import *

@method("/path/<param:filter:config>/<more>")
def func(param, more):
    return template("<h1>{{ name }}</h1>", name=name)

if __name__ == "__main__":
    run(host="localhost", port=8080)

param can be restricted to specific filter, available filters are int float path re

Error pages are described by @error(code) decorator

@error(404)
def not_found(error): # error is an instance of HTTPError
    return ...

Request data can be accessed by by the request object, the request object is thread safe

Retrieve single value

param    one value    multi value
cookies    request.cookies.key    request.cookies.getall('key')
POST    request.forms.key    request.forms.getall('key')
GET    request.query.key    request.query.getall('key')
headers    request.headers.get('Referer')    
files(by form)    request.files    
json    request.json....    Notes: must with application/json header

request.body contains the raw request body. If you are posting a binary directly, please set the right Content-Type header, you may not access it by the files attribute, just read request.body

bottle automatically generate proper headers and response by the value type you return.

dict    json
string    normal html
file    file.read() as html
HTTPError    cause a error, like abort()

Instead of returning errors, use the functions

abort(error_code, body)
redirect(url, error_code)

Headers:

request.set_header(header, value)
request.add_header(header, value)

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.