Bottle?中的基本映射和動態映射

來源:互聯網
上載者:User

標籤:

這篇Bottle 教程是比較基礎的,主要講解Bottle?的基本映射和動態映射。

 

基本映射

映射使用在根據不同 URLs 請求來產生相對應的返回內容。
Bottle 使用 route() 修飾器來實現映射。

from bottle import route, [email protected](’/hello’)def hello():

    return "Hello World!"

run() # This starts the HTTP server

運行這個程式,訪問 http://localhost:8080/hello 將會在瀏覽器裡看到 "Hello World!"。

GET, POST, HEAD, ...

這個映射裝飾器有可選的關鍵字 method 預設是 method=’GET’。
還有可能是 POST,PUT,DELETE,HEAD 或者監聽其他的 HTTP 要求方法。

from bottle import route, [email protected](’/form/submit’, method=’POST’)def form_submit():

    form_data = request.POST

    do_something(form_data)

return "Done"

 

動態映射

你可以提取 URL 的部分來建立動態變數名的映射。

@route(’/hello/:name’)def hello(name):

    return "Hello %s!" % name

預設情況下,一個 :placeholder 會一直匹配到下一個斜線。
需要修改的話,可以把正則字元加入到 #s 之間:

@route(’/get_object/:id#[0-9]+#’)def get(id):

    return "Object ID: %d" % int(id)

或者使用完整的正則匹配組來實現:

@route(’/get_object/(?P<id>[0-9]+)’)def get(id):

    return "Object ID: %d" % int(id)

正如你看到的,URL 參數仍然是字串,即使你正則裡面是數字。
你必須顯式的進行類型強制轉換。

@validate() 裝飾器

Bottle 提供一個方便的裝飾器 validate() 來校正多個參數。
它可以通過關鍵字和過濾器來對每一個 URL 參數進行處理然後返回請求。

from bottle import route, validate# /test/validate/1/2.3/4,5,6,[email protected](’/test/validate/:i/:f/:csv’)@validate(i=int, f=float, csv=lambda x: map(int, x.split(’,’)))def validate_test(i, f, csv):

    return "Int: %d, Float:%f, List:%s" % (i, f, repr(csv))

你可能需要在校正參數失敗時拋出 ValueError。

 

 

文章來自:segmentfault

Bottle?中的基本映射和動態映射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.