基本映射
映射使用在根據不同URLs請求來產生相對應的返回內容.Bottle使用route() 修飾器來實現映射.
from bottle import route, run@route('/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, request@route('/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,7@route('/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.
返回文件流和JSON
WSGI規范不能處理文件對象或字符串.Bottle自動轉換字符串類型為iter對象.下面的例子可以在Bottle下運行, 但是不能運行在純WSGI環境下.
@route('/get_string')def get_string(): return "This is not a list of strings, but a single string"@route('/file')def get_file(): return open('some/file.txt','r')
字典類型也是允許的.會轉換成json格式,自動返回Content-Type: application/json.
@route('/api/status')def api_status(): return {'status':'online', 'servertime':time.time()}
你可以關閉這個特性:bottle.default_app().autojson = False
Cookies
Bottle是把cookie存儲在request.COOKIES變量中.新建cookie的方法是response.set_cookie(name, value[, **params]). 它可以接受額外的參數,屬于SimpleCookie的有有效參數.
from bottle import responseresponse.set_cookie('key','value', path='/', domain='example.com', secure=True, expires=+500, ...)
新聞熱點
疑難解答