在正式開始Web開發前,我們需要編寫一個Web架構。
為什麼不選擇一個現成的Web架構而是自己從頭開發呢?我們來考察一下現有的流行的Web架構:
- Django:一站式開發架構,但不利於定製化;
- web.py:使用類而不是更簡單的函數來處理URL,並且URL映射是單獨配置的;
- Flask:使用@decorator的URL路由不錯,但架構對應用程式的代碼入侵太強;
- bottle:缺少根據URL模式進行攔截的功能,不利於做許可權檢查。
所以,我們綜合幾種架構的優點,設計一個簡單、靈活、入侵性極小的Web架構。
設計Web架構
一個簡單的URL架構應該允許以@decorator方式直接把URL映射到函數上:
# 首頁:@get('/')def index(): return 'Index page
'# 帶參數的URL:@get('/user/:id')def show_user(id): user = User.get(id) return 'hello, %s' % user.name
有沒有@decorator不改變函數行為,也就是說,Web架構的API入侵性很小,你可以直接測試函數show_user(id)而不需要啟動Web伺服器。
函數可以返回str、unicode以及iterator,這些資料可以直接作為字串返回給瀏覽器。
其次,Web架構要支援URL攔截器,這樣,我們就可以根據URL做許可權檢查:
@interceptor('/manage/')def check_manage_url(next): if current_user.isAdmin(): return next() else: raise seeother('/signin')
攔截器接受一個next函數,這樣,一個攔截器可以決定調用next()繼續處理請求還是直接返回。
為了支援MVC,Web架構需要支援模板,但是我們不限定使用哪一種模板,可以選擇jinja2,也可以選擇mako、Cheetah等等。
要統一模板的介面,函數可以返回dict並配合@view來渲染模板:
@view('index.html')@get('/')def index(): return dict(blogs=get_recent_blogs(), user=get_current_user())
如果需要從form表單或者URL的querystring擷取使用者輸入的資料,就需要訪問request對象,如果要設定特定的Content-Type、設定Cookie等,就需要訪問response對象。request和response對象應該從一個唯一的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()
基於以上介面,我們就可以實現Web架構了。
實現Web架構
最基本的幾個對象如下:
# transwarp/web.py# 全域ThreadLocal對象:ctx = threading.local()# HTTP錯誤類:class HttpError(Exception): pass# request對象:class Request(object): # 根據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 # 根據key返回Cookie value: def cookie(self, name, default=None): pass# response對象:class Response(object): # 設定header: def set_header(self, key, value): pass # 設定Cookie: def set_cookie(self, name, value, max_age=None, expires=None, path='/'): pass # 設定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的類,實現WSGI介面,然後,通過配置啟動,就完成了整個Web架構的工作。
設計WSGIApplication要充分考慮開發模式(Development Mode)和產品模式(Production Mode)的區分。在產品模式下,WSGIApplication需要直接提供WSGI介面給伺服器,讓伺服器調用該介面,而在開發模式下,我們更希望能通過app.run()直接啟動伺服器進行開發調試:
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 # 設定TemplateEngine: @property def template_engine(self): pass @template_engine.setter def template_engine(self, engine): pass # 返回WSGI處理函數: def get_wsgi_application(self): def wsgi(env, start_response): pass return wsgi # 開發模式下直接啟動伺服器: 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架構。