首页 > 其他 > 详细

bottle框架学习(一)之安装以及路由的使用

时间:2015-06-20 01:35:50      阅读:339      评论:0      收藏:0      [点我收藏+]

安装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

技术分享

代码注释:

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中,输入不同的值,就会出现不同的内容

技术分享技术分享

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

本文出自 “乾楠有” 博客,请务必保留此出处http://changfei.blog.51cto.com/4848258/1663742

bottle框架学习(一)之安装以及路由的使用

原文:http://changfei.blog.51cto.com/4848258/1663742

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!