安装bottle:

[root@ju bottle]#  yum install python-devel python-setuptools -y
[root@ju bottle]#  easy_install pip
[root@ju bottle]#  pip install bottle

官方文档:http://www.bottlepy.org/docs/dev/index.html

 

静态路由

[root@ju bottle]#  vim first.py
#/usr/bin/env python
#coding=utf-8
from bottle import route, run
@route('/start)  #定义路由,即浏览器访问的url
def start():
   return " <h1>hello, this is my first bottleprocess</h1> "   #浏览器返回的内容
run(host='0.0.0.0', port=8000)     #开启服务,端口是8000,授受任何IP地址访问

保存文件并执行:python  first.py

在浏览器中输入:http://192.168.116.199:8000/start

wKiom1WENv3Tv3RXAADpXk6M6nc426.jpg

代码注释:

Route()是一个修饰器的函数名,它可以将一段代码绑定到一个URL,这里就是将start()函数绑定给了/start。在浏览器请求URL 的时候,bottle框架会根据URL调用与之相应的函数,然后将函数的返回值发送到浏览器。Run()函数是bottle内置的http服务器,但它仅能用于测试环境。

 

动态路由

动态路由就是可以用url传递不同的内容或参数到网页上,如下:

#!/usr/bin/env python
#coding=utf-8
from bottle import route,run
 
@route('/start/<sth>')
def start(sth):
   return "<h1>hello, this is my %s bottleprocess</h1>" % sth
run(host='0.0.0.0',port=8000)

保存文件并执行:python  first.py

url中,输入不同的值,就会出现不同的内容,如下:

wKioL1WEOLDif5VWAAD5sjYgrgQ615.jpgwKiom1WENv3xVEZnAAEFujLoGMk345.jpg


<sth>是一个通配符,通配符之间用”/分隔。如果将 URL 定义为/start/<sth>,它能匹配/start/first /start/second等,但不能匹配/start, /start/,/start/first//start/first/somethURL 中的通配符会当作参数传给回调函数,直接在回调函数中使用。


扩展用法

一个回调函数还可以绑定多个route,如:

@route('/<sth>')
@route('/start/<sth:>')
def start(sth):
    return "<h1>hello, this is my %sbottle process</h1>" % sth

 

0.10 版本开始,过滤器(Filter)还可以被用来定义特殊类型的通配符,在传通配符给回调函数之前,先自动转换通配符类型。包含过滤器的通配符定义一般像<name:filter><name:filter:config>这样。config部分是可选的,其语法由你使用的过滤器决定。

已实现下面几种形式的过滤器,后续可能会继续添加:

int        匹配一个×××,自动将其转换为int类型。

float      int类似,用于浮点数。

path       匹配一个路径(包含”/)

re:config  匹配config部分的一个正则表达式

例子:

@route('/object/<id:int>')
def callback(id):
    assert isinstance(id, int)
@route('/show/<name:re:[a-z]+>')
def callback(name):
    assert name.isalpha()
@route('/static/<path:path>')
def callback(path):
    return static_file(path, ...)