Bottle是一个轻量级的Web框架,此框架只由一个 bottle.py 文件构成,不依赖任何第三方模块。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
app = Bottle()
@app.route('/say')
def index():
return "Hello World"
# return template('Hello {{name}}!', name="bottle")
if __name__ == '__main__':
app.run(server="tornado",host='0.0.0.0', port=8888)
1、路由系统
路由系统是的url对应指定函数,当用户请求某个url时,就由指定函数处理当前请求,对于Bottle的路由系统可以分为一下几类:
静态路由
动态路由
请求方法路由
二级路由
1.1静态路由
@app.route("/login") # 默认为get请求
def hello():
return """
Username:
Password:
"""
@app.route("/login",method="POST")
def do_login():
username = request.forms.get("username")
password = request.forms.get("password")
print(username,password)
if username and password:
return "
login success
"else:
return "
login failure
"1.2动态路由
@app.route('/say/')
def callback(name):
return template('Hello {{name}}!')
@app.route('/say/')
def callback(id):
return template('Hello {{id}}!')
@app.route('/say/')
def callback(name):
return template('Hello {{name}}!')
@app.route('/static/')
def callback(path):
return static_file(path, root='static')
1.3请求方法路由
@app.route('/hello/', method='POST') # 等同于@app.post('/hello/')
def index():
...
@app.get('/hello/') # 等同于@app.route('/hello/',method='GET')
def index():
...
@app.post('/hello/') # 等同于@app.route('/hello/',method='POST')
def index():
...
@app.put('/hello/') # 等同于@app.route('/hello/',method='PUT')
def index():
...
@app.delete('/hello/')
def index():
...
1.4二级路由
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
app01 = Bottle()
@app01.route('/hello/', method='GET')
def index():
return template('App01!')
app01.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
app02 = Bottle()
@app02.route('/hello/', method='GET')
def index():
return template('App02!')
app02.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
from bottle import static_file
app = Bottle()
@app.route('/hello/')
def index():
return template('Root {{name}}!', name="bottle")
from root_dir import app01
from root_dir import app02
app.mount('app01', app01.app01)
app.mount('app02', app02.app02)
app.run(host='localhost', port=8888)
1.5静态文件映射,static_file()函数用于响应静态文件的请求
# 静态文件映射,static_file()函数用于响应静态文件 的请求
@app.route("/static/