
- TurboGears 教程
- TurboGears - 首頁
- TurboGears - 概述
- TurboGears - 環境
- TurboGears - 第一個程式
- TurboGears - 依賴項
- TurboGears - 服務模板
- TurboGears - HTTP 方法
- Genshi 模板語言
- TurboGears - 包含
- TurboGears - JSON 渲染
- TurboGears - URL 層次結構
- TurboGears - Toscawidgets 表單
- TurboGears - 驗證
- TurboGears - 快閃記憶體訊息
- TurboGears - Cookie 和會話
- TurboGears - 快取
- TurboGears - SQLAlchemy
- TurboGears - 建立模型
- TurboGears - CRUD 操作
- TurboGears - 資料表格
- TurboGears - 分頁
- TurboGears - 管理員訪問
- 授權與身份驗證
- TurboGears - 使用 MongoDB
- TurboGears - 腳手架
- TurboGears - 鉤子
- TurboGears - 編寫擴充套件
- TurboGears - 可插拔應用程式
- TurboGears - RESTful 應用程式
- TurboGears - 部署
- TurboGears 有用資源
- TurboGears - 快速指南
- TurboGears - 有用資源
- TurboGears - 討論
TurboGears – 鉤子
在 TurboGears 中,有三種方法可以將行為插入現有應用程式。
鉤子 (Hook) − 這是一種機制,可以透過它定義事件,並在發出事件時通知已註冊的監聽器。
控制器包裝器 (Controller Wrapper) − 它位於 TurboGears 和控制器之間,因此可以像裝飾器一樣擴充套件控制器。因此,它可以附加到任何第三方控制器應用程式。
應用程式包裝器 (Application Wrapper) − 它類似於任何 WSGI 中介軟體,但僅在 TurboGears 上下文中工作。
本章將討論如何在現有應用程式中使用鉤子。
鉤子
鉤子是在應用程式的配置檔案 app_cfg.py 中註冊的事件。然後,任何控制器都透過事件裝飾器連線到這些事件。
TurboGears 中定義了以下鉤子:
序號 | 鉤子及描述 |
---|---|
1 | Startup() 僅限於應用程式範圍,在應用程式啟動時呼叫。 |
2 | shutdown() 僅限於應用程式範圍,在應用程式退出時呼叫。 |
3 | configure_new_app 應用程式配置器建立了新的應用程式。 |
4 | before_config(app) 僅限於應用程式範圍,在建立應用程式後立即呼叫,但在設定選項和中介軟體之前。 |
5 | after_config(app) 僅限於應用程式範圍,在完成所有設定後呼叫。 |
6 | before_validate 在執行驗證之前呼叫。 |
7 | before_call 在驗證之後、呼叫實際控制器方法之前呼叫。 |
8 | before_render 在渲染控制器模板之前呼叫,輸出是控制器返回值。 |
9 | after_render 在完成渲染控制器模板後呼叫。 |
註冊鉤子
為了註冊鉤子,請在 app_cfg.py 中建立函式,然後使用以下程式碼註冊它們:
tg.hooks.register(hookane, function, controller)
在以下程式碼中,on_startup、on_shutdown 和 before_render 鉤子在 app_cfg.py 中註冊。
def on_startup(): print 'hello, startup world' def on_shutdown(): print 'hello, shutdown world' def before_render(remainder, params, output): print 'system wide before render' # ... (base_config init code) tg.hooks.register('startup', on_startup) tg.hooks.register('shutdown', on_shutdown) tg.hooks.register('before_render', before_render)
before_render 鉤子在 Rootcontroller 中使用控制器函式註冊。在 controllers\root.py 中新增以下程式碼。
from tg.decorators import before_render class RootController(BaseController): @expose('hello.templates.index') @before_render(before_render_cb) def index(self, *args, **kw): return dict(page = 'index')
當應用程式啟動時,啟動訊息將顯示在控制檯中。
hello, startup world Starting Standard HTTP server on http://127.0.0.1:8080
當在瀏覽器中輸入“/”URL 時,與 before_render 鉤子對應的訊息將顯示在控制檯中。
system wide before render Going to render {'page': 'index'}