📅  最后修改于: 2020-10-19 03:36:09             🧑  作者: Mango
TurboGears中通过三种方式将行为插入现有应用程序中。
挂钩-这是一种机制,通过它可以定义事件,并在事件发出时通知注册的侦听器。
控制器包装器-位于TurboGears和控制器之间,因此可以像装饰器一样扩展控制器。因此,它可以附加到任何第三方控制器应用程序。
Application Wrapper-它类似于任何WSGI中间件,但仅在TurboGears上下文中工作。
在本章的此处,我们将讨论如何在现有应用程序中使用挂钩。
挂钩是在应用程序的配置文件app_cfg.py中注册的事件。然后,任何控制器都会被事件装饰器挂接到这些事件。
以下挂钩在TurboGears中定义-
Sr.No. | Hooks & Description |
---|---|
1 |
Startup() application wide only, called when the application starts. |
2 |
shutdown() application wide only, called when the application exits. |
3 |
configure_new_app new application got created by the application configurator. |
4 |
before_config(app) application wide only, called right after creating application, but before setting up options and middleware |
5 |
after_config(app) application wide only, called after finishing setting everything up. |
6 |
before_validate Called before performing validation |
7 |
before_call Called after validation, before calling the actual controller method. |
8 |
before_render Called before rendering a controller template, output is the controller return value. |
9 |
after_render Called after finishing rendering a controller template. |
为了注册一个挂钩,请在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'}