在正式開始Web開發(fā)前,我們需要編寫一個Web框架。
為什么不選擇一個現(xiàn)成的Web框架而是自己從頭開發(fā)呢?我們來考察一下現(xiàn)有的流行的Web框架:
所以,我們綜合幾種框架的優(yōu)點,設(shè)計一個簡單、靈活、入侵性極小的Web框架。
設(shè)計Web框架
一個簡單的URL框架應(yīng)該允許以@decorator方式直接把URL映射到函數(shù)上:
# 首頁:@get('/')def index(): return '<h1>Index page</h1>'# 帶參數(shù)的URL:@get('/user/:id')def show_user(id): user = User.get(id) return 'hello, %s' % user.name有沒有@decorator不改變函數(shù)行為,也就是說,Web框架的API入侵性很小,你可以直接測試函數(shù)show_user(id)而不需要啟動Web服務(wù)器。
函數(shù)可以返回str、unicode以及iterator,這些數(shù)據(jù)可以直接作為字符串返回給瀏覽器。
其次,Web框架要支持URL攔截器,這樣,我們就可以根據(jù)URL做權(quán)限檢查:
@interceptor('/manage/')def check_manage_url(next): if current_user.isAdmin(): return next() else: raise seeother('/signin')攔截器接受一個next函數(shù),這樣,一個攔截器可以決定調(diào)用next()繼續(xù)處理請求還是直接返回。
為了支持MVC,Web框架需要支持模板,但是我們不限定使用哪一種模板,可以選擇jinja2,也可以選擇mako、Cheetah等等。
要統(tǒng)一模板的接口,函數(shù)可以返回dict并配合@view來渲染模板:
@view('index.html')@get('/')def index(): return dict(blogs=get_recent_blogs(), user=get_current_user())如果需要從form表單或者URL的querystring獲取用戶輸入的數(shù)據(jù),就需要訪問request對象,如果要設(shè)置特定的Content-Type、設(shè)置Cookie等,就需要訪問response對象。request和response對象應(yīng)該從一個唯一的ThreadLocal中獲取:
@get('/test')def test(): input_data = ctx.request.input() ctx.response.content_type = 'text/plain' ctx.response.set_cookie('name', 'value', expires=3600) return 'result'最后,如果需要重定向、或者返回一個HTTP錯誤碼,最好的方法是直接拋出異常,例如,重定向到登陸頁:
raise seeother('/signin')返回404錯誤:
raise notfound()
基于以上接口,我們就可以實現(xiàn)Web框架了。
實現(xiàn)Web框架
最基本的幾個對象如下:
# transwarp/web.py# 全局ThreadLocal對象:ctx = threading.local()# HTTP錯誤類:class HttpError(Exception): pass# request對象:class Request(object): # 根據(jù)key返回value: def get(self, key, default=None): pass # 返回key-value的dict: def input(self): pass # 返回URL的path: @property def path_info(self): pass # 返回HTTP Headers: @property def headers(self): pass # 根據(jù)key返回Cookie value: def cookie(self, name, default=None): pass# response對象:class Response(object): # 設(shè)置header: def set_header(self, key, value): pass # 設(shè)置Cookie: def set_cookie(self, name, value, max_age=None, expires=None, path='/'): pass # 設(shè)置status: @property def status(self): pass @status.setter def status(self, value): pass# 定義GET:def get(path): pass# 定義POST:def post(path): pass# 定義模板:def view(path): pass# 定義攔截器:def interceptor(pattern): pass# 定義模板引擎:class TemplateEngine(object): def __call__(self, path, model): pass# 缺省使用jinja2:class Jinja2TemplateEngine(TemplateEngine): def __init__(self, templ_dir, **kw): from jinja2 import Environment, FileSystemLoader self._env = Environment(loader=FileSystemLoader(templ_dir), **kw) def __call__(self, path, model): return self._env.get_template(path).render(**model).encode('utf-8')把上面的定義填充完畢,我們就只剩下一件事情:定義全局WSGIApplication的類,實現(xiàn)WSGI接口,然后,通過配置啟動,就完成了整個Web框架的工作。
設(shè)計WSGIApplication要充分考慮開發(fā)模式(Development Mode)和產(chǎn)品模式(Production Mode)的區(qū)分。在產(chǎn)品模式下,WSGIApplication需要直接提供WSGI接口給服務(wù)器,讓服務(wù)器調(diào)用該接口,而在開發(fā)模式下,我們更希望能通過app.run()直接啟動服務(wù)器進行開發(fā)調(diào)試:
wsgi = WSGIApplication()if __name__ == '__main__': wsgi.run()else: application = wsgi.get_wsgi_application()因此,WSGIApplication定義如下:class WSGIApplication(object): def __init__(self, document_root=None, **kw): pass # 添加一個URL定義: def add_url(self, func): pass # 添加一個Interceptor定義: def add_interceptor(self, func): pass # 設(shè)置TemplateEngine: @property def template_engine(self): pass @template_engine.setter def template_engine(self, engine): pass # 返回WSGI處理函數(shù): def get_wsgi_application(self): def wsgi(env, start_response): pass return wsgi # 開發(fā)模式下直接啟動服務(wù)器: def run(self, port=9000, host='127.0.0.1'): from wsgiref.simple_server import make_server server = make_server(host, port, self.get_wsgi_application()) server.serve_forever()Try
把WSGIApplication類填充完畢,我們就得到了一個完整的Web框架。
新聞熱點
疑難解答
圖片精選