Bottle是一個快速、簡潔、輕量級的基于WSIG的微型Web框架,此框架只由一個 .py 文件,除了Python的標準庫外,其不依賴任何其他模塊。
Bottle框架大致可以分為以下部分:
路由系統(tǒng),將不同請求交由指定函數(shù)處理
模板系統(tǒng),將模板中的特殊語法渲染成字符串,值得一說的是Bottle的模板引擎可以任意指定:Bottle內(nèi)置模板、mako、jinja2、cheetah
公共組件,用于提供處理請求相關(guān)的信息,如:表單數(shù)據(jù)、cookies、請求頭等
服務(wù),Bottle默認支持多種基于WSGI的服務(wù)
框架的基本使用:
1 2 3 4 5 6 7 8 9 10 11 | #!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import template, Bottle root = Bottle() @root .route( '/hello/' ) def index(): return "Hello World" # return template('<b>Hello {{name}}</b>!', name="Alex") root.run(host = 'localhost' , port = 8080 ) |
一、路由系統(tǒng)
路由系統(tǒng)是的url對應(yīng)指定函數(shù),當用戶請求某個url時,就由指定函數(shù)處理當前請求,對于Bottle的路由系統(tǒng)可以分為一下幾類:
靜態(tài)路由
動態(tài)路由
請求方法路由
二級路由
1.靜態(tài)路由
@root.route('/hello/')def index(): return template('<b>Hello {{name}}</b>!', name="Alex")
2.動態(tài)路由
@root.route('/wiki/<pagename>')def callback(pagename): ... @root.route('/object/<id:int>')def callback(id): ... @root.route('/show/<name:re:[a-z]+>')def callback(name): ... @root.route('/static/<path:path>')def callback(path): return static_file(path, root='static')
3.請求方法路由
@root.route('/hello/', method='POST')def index(): ... @root.get('/hello/')def index(): ... @root.post('/hello/')def index(): ... @root.put('/hello/')def index(): ... @root.delete('/hello/')def index(): ...
4.二級路由
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import template, Bottlefrom bottle import static_fileroot = Bottle() @root.route('/hello/')def index(): return template('<b>Root {{name}}</b>!', name="Alex") from framwork_bottle import app01from framwork_bottle import app02 root.mount('app01', app01.app01)root.mount('app02', app02.app02) root.run(host='localhost', port=8080)
二、模板系統(tǒng)
模板系統(tǒng)用于將Html和自定的值兩者進行渲染,從而得到字符串,然后將該字符串返回給客戶端。
我們知道在Bottle中可以使用 內(nèi)置模板系統(tǒng)、mako、jinja2、cheetah等,以內(nèi)置模板系統(tǒng)為例:
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import template, Bottleroot = Bottle() @root.route('/hello/')def index(): # 默認情況下去目錄:['./', './views/']中尋找模板文件 hello_template.html # 配置在 bottle.TEMPLATE_PATH 中 return template('xx.html', name='alex') root.run(host='localhost', port=8080)
1、語法
單值
單行Python代碼
Python代碼快
Python、Html混合
<h1>1、單值</h1>{{name}} <h1>2、單行Python代碼</h1>% s1 = "hello" <h1>3、Python代碼塊</h1><% # A block of python code name = name.title().strip() if name == "Alex": name="seven"%> <h1>4、Python、Html混合</h1> % if True: <span>{{name}}</span>% end<ul> % for item in name: <li>{{item}}</li> % end</ul>
2、函數(shù)
include(sub_template, **variables)
# 導(dǎo)入其他模板文件 % include('header.tpl', title='Page Title')Page Content% include('footer.tpl')
rebase(name, **variables)
# 導(dǎo)入母版 % rebase('base.html', title='Page Title')<p>Page Content ...</p>
defined(name)
# 檢查當前變量是否已經(jīng)被定義,已定義True,未定義False
get(name, default=None)
# 獲取某個變量的值,不存在時可設(shè)置默認值
setdefault(name, default)
# 如果變量不存在時,為變量設(shè)置默認值
擴展:自定義函數(shù)
注:變量或函數(shù)前添加 【 ! 】,則會關(guān)閉轉(zhuǎn)義的功能
三、公共組件
由于Web框架就是用來【接收用戶請求】-> 【處理用戶請求】-> 【響應(yīng)相關(guān)內(nèi)容】,對于具體如何處理用戶請求,開發(fā)人員根據(jù)用戶請求來進行處理,而對于接收用戶請求和相應(yīng)相關(guān)的內(nèi)容均交給框架本身來處理,其處理完成之后將產(chǎn)出交給開發(fā)人員和用戶。
【接收用戶請求】
當框架接收到用戶請求之后,將請求信息封裝在Bottle的request中,以供開發(fā)人員使用
【響應(yīng)相關(guān)內(nèi)容】
當開發(fā)人員的代碼處理完用戶請求之后,會將其執(zhí)行內(nèi)容相應(yīng)給用戶,相應(yīng)的內(nèi)容會封裝在Bottle的response中,然后再由框架將內(nèi)容返回給用戶
所以,公共組件本質(zhì)其實就是為開發(fā)人員提供接口,使其能夠獲取用戶信息并配置響應(yīng)內(nèi)容。
1、request
Bottle中的request其實是一個LocalReqeust對象,其中封裝了用戶請求的相關(guān)信息:
request.headers 請求頭信息 request.query get請求信息 request.forms post請求信息 request.files 上傳文件信息 request.params get和post請求信息 request.GET get請求信息 request.POST post和上傳信息 request.cookies cookie信息 request.environ 環(huán)境相關(guān)相關(guān)
2、response
Bottle中的response其實是一個LocalResponse對象,其中框架即將返回給用戶的相關(guān)信息:
response response.status_line 狀態(tài)行 response.status_code 狀態(tài)碼 response.headers 響應(yīng)頭 response.charset 編碼 response.set_cookie 在瀏覽器上設(shè)置cookie response.delete_cookie 在瀏覽器上刪除cookie
實例:
四、服務(wù)
對于Bottle框架其本身未實現(xiàn)類似于Tornado自己基于socket實現(xiàn)Web服務(wù),所以必須依賴WSGI,默認Bottle已經(jīng)實現(xiàn)并且支持的WSGI有:
使用時,只需在主app執(zhí)行run方法時指定參數(shù)即可:
1 2 3 4 5 6 7 8 9 10 | #!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import Bottle root = Bottle() @root .route( '/hello/' ) def index(): return "Hello World" <br> # 默認server ='wsgiref' root.run(host = 'localhost' , port = 8080 , server = 'wsgiref' ) |
默認server="wsgiref",即:使用Python內(nèi)置模塊wsgiref,如果想要使用其他時,則需要首先安裝相關(guān)類庫,然后才能使用。如:
# 如果使用Tornado的服務(wù),則需要首先安裝tornado才能使用class TornadoServer(ServerAdapter): """ The super hyped asynchronous server by facebook. Untested. """ def run(self, handler): # pragma: no cover # 導(dǎo)入Tornado相關(guān)模塊 import tornado.wsgi, tornado.httpserver, tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port,address=self.host) tornado.ioloop.IOLoop.instance().start()
PS:以上WSGI中提供了19種,如果想要使期支持其他服務(wù),則需要擴展Bottle源碼來自定義一個ServerAdapter
更多參見:http://www.bottlepy.org/docs/dev/index.html