Chinaunix首页 | 论坛 | 博客
  • 博客访问: 450571
  • 博文数量: 64
  • 博客积分: 3271
  • 博客等级: 中校
  • 技术积分: 727
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-30 18:42
文章分类

全部博文(64)

文章存档

2013年(1)

2011年(19)

2010年(42)

2009年(2)

分类: Python/Ruby

2010-12-26 21:10:19


一.bottle基础


一个bottle程序分为四部分
1.import bottle
2.@route('/index')定义一个访问路径,这样从浏览器访问时就能
3.定义一个与第2步route相应的处理函数,系统在看到@route标记后会自动调用其后边的这个函数。
4.调用run()函数。


from bottle import route, run

@route('/hello')
def hello():
    return "Hello World!" #返回给浏览器

run(host='localhost', port=8080)


其中,@route标签中的名字不一定要与其后的函数同名。系统自动调用跟随其后的函数。


二.动态的route

即是可以动态的匹配请求的路径。
语法如下:

@route('/:name')

这样就可以匹配/index,/hello,等等路径。
在程序中获取name的值:

@route('/:name')
def index(name='World'):
    return 'Hello %s!' % name


@route支持正则表达式:

@route('/object/:id#[0-9]+#')

语法规则:以‘#’开始,以‘#’结束。
表达式匹配/object目录下的数字的路径,如如果请求的路径不是数字,则返回404.


注意:@route后面的处理函数必须接受相应个数的参数,举例说明:
@route('/:year/:month/:day')
def handle(year, month, day):
     return 'h'
其中route有三个动态参数,则在数字handle中也必须接受3个参数。否则会出现
  1. Error 500: Internal Server Error

  2. Sorry, the requested URL http://localhost:8080/login/2003/22 caused an error:

  3. Unhandled exception
当然,如果在代码中加入
  1. import bottle
  2. bottle.debug(True)
效果会更加明显。

阅读(5848) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~