bottle框架學習(一)之安裝以及路由的使用

安裝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, ...)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章