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

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
