在上一篇日志中已經(jīng)討論和實(shí)現(xiàn)了根據(jù)url執(zhí)行相應(yīng)應(yīng)用,在我閱讀了bottle.py官方文檔后,按照bottle的設(shè)計(jì)重寫(xiě)一遍,主要借鑒大牛們的設(shè)計(jì)思想。
來(lái)看看bottle是如何使用的,代碼來(lái)自http://www.bottlepy.org/docs/0.12/index.html:
from bottle import route, run, template@route('/hello/<name>')def index(name): return template('<b>Hello {{name}}</b>!', name=name)run(host='localhost', port=8080)
很顯然,bottle是使用裝飾器來(lái)路由的。根據(jù)bottle的設(shè)計(jì),我來(lái)寫(xiě)一個(gè)簡(jiǎn)單的框架。
裝飾器,顧名思義就是包裝一個(gè)函數(shù)。在不改變函數(shù)的同時(shí),動(dòng)態(tài)的給函數(shù)增加功能。這里不在探討更多的細(xì)節(jié)。
根據(jù)WSGI的定義,一個(gè)WSGI應(yīng)用必須要是可調(diào)用的。所以下面是一個(gè)WSGI應(yīng)用的大致框架:
class WSGIapp(object): def __init__(self): pass def route(self,path=None): pass def __call__(self,environ,start_response): return self.wsgi(environ,start_response) def wsgi(self,environ,start_response): pass
其中,route方法就是來(lái)保存url->target的。這里為了方便,將url->target保存在字典中:
def route(self,path=None): def decorator(func): self.routes[path] = func return func return decorator
這里return func注釋掉也可以,求大神解釋一下啊!!
然后就是實(shí)現(xiàn)WSGIapp的每個(gè)方法:
class WSGIapp(object): def __init__(self): self.routes = {} def route(self,path=None): def decorator(func): self.routes[path] = func return func return decorator def __call__(self,environ,start_response): PRint 'call' return self.wsgi(environ,start_response) def wsgi(self,environ,start_response): path = environ['PATH_INFO'] print path if path in self.routes: status = '200 OK' response_headers = [('Content-Type','text/plain')] start_response(status,response_headers) print self.routes[path]() return self.routes[path]() else: status = '404 Not Found' response_headers = [('Content-Type','text/plain')] start_response(status,response_headers) return '404 Not Found!'app = WSGIapp()@app.route('/')def index(): return ['This is index']@app.route('/hello')def hello(): return ['hello']from wsgiref.simple_server import make_serverhttpd = make_server('',8000,app)print 'start....'httpd.serve_forever()
這樣,一個(gè)簡(jiǎn)易的web框架的雛形就實(shí)現(xiàn)了,如果對(duì)裝飾器中的路徑加入正則表達(dá)式,那么就可以很輕松的應(yīng)對(duì)URL了。下一篇日志就是加入模板引擎jinja2了。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注