TurboGears - 編寫擴充套件



TurboGears 擴充套件由tgext.* 包標識。Gearbox 工具包提供 tgext 命令來建立示例擴充套件。例如 -

gearbox tgext -n myextension

此命令的其他可選引數為 -

  • --author - 包作者姓名。

  • --email - 包作者的電子郵件。

  • --licence - 用於包的許可證。預設為 MIT。

  • --description - 包的描述。

  • --keywords - 包關鍵詞(預設:turbogears2.extension)。

這將建立一個 tgext.myextension 目錄,其中包含一個簡單的示例擴充套件。

執行目錄內的 setup.py -

Python setup.py install

tgext/myextension 資料夾內的_init_.py 檔案包含 -

  • Plugme 函式 - 這是擴充套件的入口點。

  • SetupExtension 類 - 擴充套件初始化在此處進行。

  • On_startup 函式 - 類內是一個在類內的 __call__ 函式上註冊的鉤子。

tgext\myextension\__init__.py 的簡短版本。

from tg import config
from tg import hooks
from tg.configuration import milestones

import logging
log = logging.getLogger('tgext.myextension')

def plugme(configurator, options = None):
   if options is None:
      options = {}
   log.info('Setting up tgext.myextension extension...')
   milestones.config_ready.register(SetupExtension(configurator))
   
   return dict(appid='tgext.myextension')
	
class SetupExtension(object):
   def __init__(self, configurator):
      self.configurator = configurator
      
   def __call__(self):
      log.info('>>> Public files path is %s' % config['paths']['static_files'])
      hooks.register('startup', self.on_startup)
      
   def echo_wrapper_factory(handler, config):
      def echo_wrapper(controller, environ, context):
         log.info('Serving: %s' % context.request.path)
         return handler(controller, environ, context)
      return echo_wrapper
      
   self.configurator.register_wrapper(echo_wrapper_factory)
   
   def on_startup(self):
      log.info('+ Application Running!')

安裝擴充套件後,透過在應用程式的app_cfg.py配置檔案中進行以下新增來啟用它。

from tgext.myextension import plugme

plugme(base_config)

如果我們使用 gearbox server 命令啟動伺服器,則可以透過以下方式在控制檯上檢視新註冊擴充套件的通知 -

14:29:13,250 INFO [tgext.myextension] Setting up tgext.myextension extension...
14:29:13,453 INFO [tgext.myextension] >>> Public files path is c:\tghello\hello\hello\public
14:29:13,453 INFO [tgext.myextension] + Application Running!

Starting Standard HTTP server on http://127.0.0.1:8080
廣告