Web.py 之 Processor
-
Processor
-
web.py 的processor 分爲兩種,api中有相關的convenient
loadhook
和unloadhook
對應了處理http響應以前和以後web -
codeapi
loadhook(h)session
def loadhook(h): """ Converts a load hook into an application processor. >>> app = auto_application() >>> def f(): "something done before handling request" ... >>> app.add_processor(loadhook(f)) """ def processor(handler): h() return handler() return processor
unloadhook(h)app
def unloadhook(h): """ Converts an unload hook into an application processor. >>> app = auto_application() >>> def f(): "something done after handling request" ... >>> app.add_processor(unloadhook(f)) """ def processor(handler): try: result = handler() is_generator = result and hasattr(result, 'next') except: # run the hook even when handler raises some exception h() raise if is_generator: return wrap(result) else: h() return result def wrap(result): def next(): try: return result.next() except: # call the hook at the and of iterator h() raise result = iter(result) while True: yield next() return processor
-
相對loadhook,unloadhook要複雜一點,主要是體如今返回值是可迭代對象的時候。wrap函數主要是處理了迭代協議next。當迭代結束調用h進行處理。須要特別注意的是h在返回值是iter對象時的處理。wrap的做用只是在迭代結束以後給h調用的機會,而沒有將iter對象迭代完成。由於這是考慮到大文件的處理函數
-
使用起來也很簡單設計
app = auto_application() def hook_load(): "something done before handling request" def hook_unload(): "something done after handling request" app.add_processor(web.loadhook(hook_load)) app.add_processor(web.unloadhook(hook_unload))
-
實際的例子code
web.py的官方文檔中對sub-application不能使用主應用中的session的解決方案對象
def session_hook(): web.ctx.session = session
這樣就能夠在sub-application裏面經過web.ctx.session調用到主應用的session了。事件
-
也能夠仿照上面的代碼本身寫一些處理,來處理http響應事件,好比文檔
def words_hook(words): def delegate(handler): return words + ':' + handler() return delegate
-
上面的處理看似合理,其實和設計初衷不符,本意的loadhook和unloadhook除了簡化processor函數的操做,還進一步指明瞭processor的用法,不會對handler的返回值作任何改動。由於根據hook_unload的實現,當返回iter對象的時候,處理會變的複雜,iter對象完成的每每是大文件操做。具體的應用能夠具體分析,最後的分析只是針對通常狀況。
-