在正式開始Web開發前,我們需要編寫一個Web框架。
為什么不選擇一個現成的Web框架而是自己從頭開發呢?我們來考察一下現有的流行的Web框架:
Django:一站式開發框架,但不利于定制化; web.py:使用類而不是更簡單的函數來處理URL,并且URL映射是單獨配置的; Flask:使用@decorator的URL路由不錯,但框架對應用程序的代碼入侵太強; bottle:缺少根據URL模式進行攔截的功能,不利于做權限檢查。所以,我們綜合幾種框架的優點,設計一個簡單、靈活、入侵性極小的Web框架。
設計Web框架
一個簡單的URL框架應該允許以@decorator方式直接把URL映射到函數上:
# 首頁:@get('/')def index(): return '<h1>Index page</h1>'# 帶參數的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中獲?。?/p>
@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')
新聞熱點
疑難解答