python web框架 多线程_python 简单web框架: Bottle
基本映射
映射使用在根據不同URLs請求來產生相對應的返回內容.Bottle使用route()?修飾器來實現映射.
1
2
3
4
5
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或者監(jiān)聽其他的HTTP請求方法.
1
2
3
4
5
6
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)變量名的映射.
1
2
3
@route('/hello/:name')def?hello(name):
return?"Hello?%s!"?%?name
默認情況下, 一個:placeholder會一直匹配到下一個斜線.需要修改的話,可以把正則字符加入到#s之間:
1
2
3
@route('/get_object/:id#[0-9]+#')def?get(id):
return?"Object?ID:?%d"?%?int(id)
或者使用完整的正則匹配組來實現:
1
2
3
@route('/get_object/(?P[0-9]+)')def?get(id):
return?"Object?ID:?%d"?%?int(id)
正如你看到的,URL參數仍然是字符串, 即使你正則里面是數字.你必須顯式的進行類型強制轉換.
@validate() 裝飾器
Bottle 提供一個方便的裝飾器validate()?來校驗多個參數.它可以通過關鍵字和過濾器來對每一個URL參數進行處理然后返回請求.
1
2
3
4
5
6
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規(guī)范不能處理文件對象或字符串.Bottle自動轉換字符串類型為iter對象.下面的例子可以在Bottle下運行, 但是不能運行在純WSGI環(huán)境下.
1
2
3
4
5
6
@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.
1
2
3
@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的有有效參數.
1
2
from?bottle?import?responseresponse.set_cookie('key','value',?path='/',?domain='example.com',?secure=True,?expires=+500,?...)
設置max-age屬性(它不是個有效的Python參數名) 你可以在實例中修改?cookie.SimpleCookie?inresponse.COOKIES.
1
2
3
from?bottle?import?responseresponse.COOKIES['key']?=?'value'response.COOKIES['key']['max-age']?=?500
模板
Bottle使用自帶的小巧的模板.你可以使用調用template(template_name, **template_arguments)并返回結果.
1
2
3
@route('/hello/:name')def?hello(name):
return?template('hello_template',?username=name)
這樣就會加載hello_template.tpl,并提取URL:name到變量username,返回請求.
hello_template.tpl大致這樣:
1
2
Hello?{{username}}
How?are?you?
模板搜索路徑
模板是根據bottle.TEMPLATE_PATH列表變量去搜索.默認路徑包含['./%s.tpl', './views/%s.tpl'].
模板緩存
模板在編譯后在內存中緩存.修改模板不會更新緩存,直到你清除緩存.調用bottle.TEMPLATES.clear().
模板語法
模板語法是圍繞Python很薄的一層.主要目的就是確保正確的縮進塊.下面是一些模板語法的列子:
%...Python代碼開始.不必處理縮進問題.Bottle會為你做這些.
%end關閉一些語句%if ...,%for ...或者其他.關閉塊是必須的.
{{...}}打印出Python語句的結果.
%include template_name optional_arguments包括其他模板.
每一行返回為文本.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%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
%include?http_footerKey/Value數據庫
Bottle(>0.4.6)通過bottle.db模塊變量提供一個key/value數據庫.你可以使用key或者屬性來來存取一個數據庫對象.調用?bottle.db.bucket_name.key_name和bottle.db[bucket_name][key_name].
只要確保使用正確的名字就可以使用,而不管他們是否已經存在.
存儲的對象類似dict字典, keys和values必須是字符串.不支持?items()?and?values()這些方法.找不到將會拋出KeyError.
持久化
對于請求,所有變化都是緩存在本地內存池中. 在請求結束時,自動保存已修改部分,以便下一次請求返回更新的值.數據存儲在bottle.DB_PATH文件里.要確保文件能訪問此文件.
Race conditions
一般來說不需要考慮鎖問題,但是在多線程或者交叉環(huán)境里仍是個問題.你可以調用?bottle.db.save()或者botle.db.bucket_name.save()去刷新緩存,但是沒有辦法檢測到其他環(huán)境對數據庫的操作,直到調用bottle.db.save()或者離開當前請求.
Example
1
2
3
4
5
6
7
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應用.如果喜歡WSGI中間件模塊的話,你只需要聲明bottle.run()去包裝應用,而不是使用默認的.
1
2
3
4
from?bottle?import?default_app,?runapp?=?default_app()newapp?=?YourMiddleware(app)run(app=newapp)
默認default_app()工作
Bottle創(chuàng)建一個bottle.Bottle()對象和裝飾器,調用bottle.run()運行.?bottle.default_app()是默認.當然你可以創(chuàng)建自己的bottle.Bottle()實例.
1
2
3
4
5
6
from?bottle?import?Bottle,?runmybottle?=?Bottle()@mybottle.route('/')def?index():
return?'default_app'run(app=mybottle)
發(fā)布
Bottle默認使用wsgiref.SimpleServer發(fā)布.這個默認單線程服務器是用來早期開發(fā)和測試,但是后期可能會成為性能瓶頸.
有三種方法可以去修改:
使用多線程的適配器
負載多個Bottle實例應用
或者兩者
多線程服務器
最簡單的方法是安裝一個多線程和WSGI規(guī)范的HTTP服務器比如Paste,?flup,?cherrypy?or?fapws3并使用相應的適配器.
1
2
from?bottle?import?PasteServer,?FlupServer,?FapwsServer,?CherryPyServerbottle.run(server=PasteServer)?#?Example
如果缺少你喜歡的服務器和適配器,你可以手動修改HTTP服務器并設置bottle.default_app()來訪問你的WSGI應用.
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)
多服務器進程
一個Python程序只能使用一次一個CPU,即使有更多的CPU.關鍵是要利用CPU資源來負載平衡多個獨立的Python程序.
單實例Bottle應用,你可以通過不同的端口來啟動(localhost:8080, 8081, 8082, ...).高性能負載作為反向代理和遠期每一個隨機瓶進程的新要求,平衡器的行為,傳播所有可用的支持與服務器實例的負載.這樣,您就可以使用所有的CPU核心,甚至分散在不同的物理服
總結
以上是生活随笔為你收集整理的python web框架 多线程_python 简单web框架: Bottle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python linux编程与windo
- 下一篇: 充值游戏钱怎么申请退款