簡單介紹Python的輕便web框架Bottle
基本映射
映射使用在根據(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<id>[0-9]+)')def get(id):
return "Object ID: %d" % int(id)
正如你看到的,URL參數(shù)仍然是字符串, 即使你正則里面是數(shù)字.你必須顯式的進(jìn)行類型強制轉(zhuǎn)換.
@validate() 裝飾器
Bottle 提供一個方便的裝飾器validate() 來校驗多個參數(shù).它可以通過關(guān)鍵字和過濾器來對每一個URL參數(shù)進(jìn)行處理然后返回請求.
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 responseresponse.set_cookie('key','value', path='/', domain='example.com', secure=True, expires=+500, ...)
設(shè)置max-age屬性(它不是個有效的Python參數(shù)名) 你可以在實例中修改 cookie.SimpleCookie inresponse.COOKIES.
from bottle import responseresponse.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大致這樣:
<h1>Hello {{username}}</h1><p>How are you?</p>
模板搜索路徑
模板是根據(jù)bottle.TEMPLATE_PATH列表變量去搜索.默認(rèn)路徑包含['./%s.tpl', './views/%s.tpl'].
模板緩存
模板在編譯后在內(nèi)存中緩存.修改模板不會更新緩存,直到你清除緩存.調(diào)用bottle.TEMPLATES.clear().
模板語法
模板語法是圍繞Python很薄的一層.主要目的就是確保正確的縮進(jìn)塊.下面是一些模板語法的列子:
- %...Python代碼開始.不必處理縮進(jìn)問題.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']<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模塊變量提供一個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 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)的.
from bottle import default_app, runapp = default_app()newapp = YourMiddleware(app)run(app=newapp)
默認(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, runmybottle = 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, CherryPyServerbottle.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ù)器進(jìn)程
一個Python程序只能使用一次一個CPU,即使有更多的CPU.關(guān)鍵是要利用CPU資源來負(fù)載平衡多個獨立的Python程序.
單實例Bottle應(yīng)用,你可以通過不同的端口來啟動(localhost:8080, 8081, 8082, ...).高性能負(fù)載作為反向代理和遠(yuǎn)期每一個隨機瓶進(jìn)程的新要求,平衡器的行為,傳播所有可用的支持與服務(wù)器實例的負(fù)載.這樣,您就可以使用所有的CPU核心,甚至分散在不同的物理服
相關(guān)文章
Django開發(fā)web后端對比SpringBoot示例分析
這篇文章主要介紹了Django開發(fā)web后端對比SpringBoot示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
TensorFlow人工智能學(xué)習(xí)數(shù)據(jù)類型信息及轉(zhuǎn)換
這篇文章主要為大家介紹了TensorFlow人工智能學(xué)習(xí)數(shù)據(jù)類型信息及轉(zhuǎn)換,2021-11-11
opencv-python 讀取圖像并轉(zhuǎn)換顏色空間實例
今天小編就為大家分享一篇opencv-python 讀取圖像并轉(zhuǎn)換顏色空間實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python DataFrame 設(shè)置輸出不顯示index(索引)值的方法
今天小編就為大家分享一篇Python DataFrame 設(shè)置輸出不顯示index(索引)值的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

