基本映射
映射使用在根據(jù)不同URLs請(qǐng)求來產(chǎn)生相對(duì)應(yīng)的返回內(nèi)容.Bottle使用route() 修飾器來實(shí)現(xiàn)映射.
1
2
|
from bottle import route, run@route( '/hello' ) def hello(): return "Hello World!" run() # This starts the HTTP server |
運(yùn)行這個(gè)程序,訪問http://localhost:8080/hello將會(huì)在瀏覽器里看到 "Hello World!".
GET, POST, HEAD, ...
這個(gè)映射裝飾器有可選的關(guān)鍵字method默認(rèn)是method='GET'. 還有可能是POST,PUT,DELETE,HEAD或者監(jiān)聽其他的HTTP請(qǐng)求方法.
1
2
3
4
|
from bottle import route, request@route( '/form/submit' , method = 'POST' ) def form_submit(): form_data = request.POST do_something(form_data) return "Done" |
動(dòng)態(tài)映射
你可以提取URL的部分來建立動(dòng)態(tài)變量名的映射.
1
2
|
@route ( '/hello/:name' ) def hello(name): return "Hello %s!" % name |
默認(rèn)情況下, 一個(gè):placeholder會(huì)一直匹配到下一個(gè)斜線.需要修改的話,可以把正則字符加入到#s之間:
1
2
|
@route ( '/get_object/:id#[0-9]+#' ) def get( id ): return "Object ID: %d" % int ( id ) |
或者使用完整的正則匹配組來實(shí)現(xiàn):
1
2
|
@route ( '/get_object/(?P<id>[0-9]+)' ) def get( id ): return "Object ID: %d" % int ( id ) |
正如你看到的,URL參數(shù)仍然是字符串, 即使你正則里面是數(shù)字.你必須顯式的進(jìn)行類型強(qiáng)制轉(zhuǎn)換.
@validate() 裝飾器
Bottle 提供一個(gè)方便的裝飾器validate() 來校驗(yàn)多個(gè)參數(shù).它可以通過關(guān)鍵字和過濾器來對(duì)每一個(gè)URL參數(shù)進(jìn)行處理然后返回請(qǐng)求.
1
2
|
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)) |
你可能需要在校驗(yàn)參數(shù)失敗時(shí)拋出ValueError.
返回文件流和JSON
WSGI規(guī)范不能處理文件對(duì)象或字符串.Bottle自動(dòng)轉(zhuǎn)換字符串類型為iter對(duì)象.下面的例子可以在Bottle下運(yùn)行, 但是不能運(yùn)行在純WSGI環(huán)境下.
1
2
3
|
@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' ) |
字典類型也是允許的.會(huì)轉(zhuǎn)換成json格式,自動(dòng)返回Content-Type: application/json.
1
2
|
@route ( '/api/status' ) def api_status(): return { 'status' : 'online' , 'servertime' :time.time()} |
你可以關(guān)閉這個(gè)特性:bottle.default_app().autojson = False
Cookies
Bottle是把cookie存儲(chǔ)在request.COOKIES變量中.新建cookie的方法是response.set_cookie(name, value[, **params]). 它可以接受額外的參數(shù),屬于SimpleCookie的有有效參數(shù).
1
|
from bottle import responseresponse.set_cookie( 'key' , 'value' , path = '/' , domain = 'example.com' , secure = True , expires = + 500 , ...) |
設(shè)置max-age屬性(它不是個(gè)有效的Python參數(shù)名) 你可以在實(shí)例中修改 cookie.SimpleCookie inresponse.COOKIES.
1
|
from bottle import responseresponse.COOKIES[ 'key' ] = 'value' response.COOKIES[ 'key' ][ 'max-age' ] = 500 |
模板
Bottle使用自帶的小巧的模板.你可以使用調(diào)用template(template_name, **template_arguments)并返回結(jié)果.
1
2
|
@route ( '/hello/:name' ) def hello(name): return template( 'hello_template' , username = name) |
這樣就會(huì)加載hello_template.tpl,并提取URL:name到變量username,返回請(qǐng)求.
hello_template.tpl大致這樣:
1
|
< h1 >Hello {{username}}</ h1 >< p >How are you?</ p > |
模板搜索路徑
模板是根據(jù)bottle.TEMPLATE_PATH列表變量去搜索.默認(rèn)路徑包含['./%s.tpl', './views/%s.tpl'].
模板緩存
模板在編譯后在內(nèi)存中緩存.修改模板不會(huì)更新緩存,直到你清除緩存.調(diào)用bottle.TEMPLATES.clear().
模板語法
模板語法是圍繞Python很薄的一層.主要目的就是確保正確的縮進(jìn)塊.下面是一些模板語法的列子:
- %...Python代碼開始.不必處理縮進(jìn)問題.Bottle會(huì)為你做這些.
- %end關(guān)閉一些語句%if ...,%for ...或者其他.關(guān)閉塊是必須的.
- {{...}}打印出Python語句的結(jié)果.
- %include template_name optional_arguments包括其他模板.
- 每一行返回為文本.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
% header = 'Test Template' % items = [ 1 , 2 , 3 , 'fly' ] % include http_header title = header, use_js = [ 'jquery.js' , 'default.js' ]<h1>{{header.title()}}< / h1><ul> % for item in items: <li> % if isinstance (item, int ): Zahl: {{item}} % else : % try : Other type : ({{ type (item).__name__}}) {{ repr (item)}} % except : Error: Item has no string representation. % end try - block (yes, you may add comments here) % end < / li> % end< / ul> % include http_footer |
Key/Value數(shù)據(jù)庫
Bottle(>0.4.6)通過bottle.db模塊變量提供一個(gè)key/value數(shù)據(jù)庫.你可以使用key或者屬性來來存取一個(gè)數(shù)據(jù)庫對(duì)象.調(diào)用 bottle.db.bucket_name.key_name和bottle.db[bucket_name][key_name].
只要確保使用正確的名字就可以使用,而不管他們是否已經(jīng)存在.
存儲(chǔ)的對(duì)象類似dict字典, keys和values必須是字符串.不支持 items() and values()這些方法.找不到將會(huì)拋出KeyError.
持久化
對(duì)于請(qǐng)求,所有變化都是緩存在本地內(nèi)存池中. 在請(qǐng)求結(jié)束時(shí),自動(dòng)保存已修改部分,以便下一次請(qǐng)求返回更新的值.數(shù)據(jù)存儲(chǔ)在bottle.DB_PATH文件里.要確保文件能訪問此文件.
Race conditions
一般來說不需要考慮鎖問題,但是在多線程或者交叉環(huán)境里仍是個(gè)問題.你可以調(diào)用 bottle.db.save()或者botle.db.bucket_name.save()去刷新緩存,但是沒有辦法檢測(cè)到其他環(huán)境對(duì)數(shù)據(jù)庫的操作,直到調(diào)用bottle.db.save()或者離開當(dāng)前請(qǐng)求.
Example
1
2
3
4
5
|
from bottle import route, db@route( '/db/counter' ) def db_counter(): if 'hits' not in db.counter: db.counter.hits = 0 db[ 'counter' ][ 'hits' ] + = 1 return "Total hits: %d!" % db.counter.hits |
使用WSGI和中間件
bottle.default_app()返回一個(gè)WSGI應(yīng)用.如果喜歡WSGI中間件模塊的話,你只需要聲明bottle.run()去包裝應(yīng)用,而不是使用默認(rèn)的.
1
|
from bottle import default_app, runapp = default_app()newapp = YourMiddleware(app)run(app = newapp) |
默認(rèn)default_app()工作
Bottle創(chuàng)建一個(gè)bottle.Bottle()對(duì)象和裝飾器,調(diào)用bottle.run()運(yùn)行. bottle.default_app()是默認(rèn).當(dāng)然你可以創(chuàng)建自己的bottle.Bottle()實(shí)例.
1
2
|
from bottle import Bottle, runmybottle = Bottle()@mybottle.route( '/' ) def index(): return 'default_app' run(app = mybottle) |
發(fā)布
Bottle默認(rèn)使用wsgiref.SimpleServer發(fā)布.這個(gè)默認(rèn)單線程服務(wù)器是用來早期開發(fā)和測(cè)試,但是后期可能會(huì)成為性能瓶頸.
有三種方法可以去修改:
- 使用多線程的適配器
- 負(fù)載多個(gè)Bottle實(shí)例應(yīng)用
- 或者兩者
多線程服務(wù)器
最簡(jiǎn)單的方法是安裝一個(gè)多線程和WSGI規(guī)范的HTTP服務(wù)器比如Paste, flup, cherrypy or fapws3并使用相應(yīng)的適配器.
from bottle import PasteServer, FlupServer, FapwsServer, CherryPyServerbottle.run(server=PasteServer) # Example
如果缺少你喜歡的服務(wù)器和適配器,你可以手動(dòng)修改HTTP服務(wù)器并設(shè)置bottle.default_app()來訪問你的WSGI應(yīng)用.
1
2
3
4
|
def run_custom_paste_server( self , host, port): myapp = bottle.default_app() from paste import httpserver httpserver.serve(myapp, host = host, port = port) |
多服務(wù)器進(jìn)程
一個(gè)Python程序只能使用一次一個(gè)CPU,即使有更多的CPU.關(guān)鍵是要利用CPU資源來負(fù)載平衡多個(gè)獨(dú)立的Python程序.
單實(shí)例Bottle應(yīng)用,你可以通過不同的端口來啟動(dòng)(localhost:8080, 8081, 8082, ...).高性能負(fù)載作為反向代理和遠(yuǎn)期每一個(gè)隨機(jī)瓶進(jìn)程的新要求,平衡器的行為,傳播所有可用的支持與服務(wù)器實(shí)例的負(fù)載.這樣,您就可以使用所有的CPU核心,甚至分散在不同的物理服