TurboGears – 脚手架
Gearbox 工具包包含 scaffold 命令,该命令对于快速创建 TurboGears 应用程序的新组件非常有用。由 gearbox 的 quickstart 命令生成的应用程序在模型文件夹 (model.py.template)、模板文件夹 (template.html.template) 和控制器文件夹 (controller.py.template) 中有一个骨架模板。这些".template"文件用作为应用程序创建新脚手架的基础
例如,为了创建一个名为 mymodel 的新模型,只需运行以下命令 −
gearbox scaffold model mymodel
此命令将生成 model/mymodel.py,其中定义了 newmodel 类。
# -*- coding: utf-8 -*-
"""Mymodel model module."""
from sqlalchemy import *
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, LargeBinary
from sqlalchemy.orm import relationship, backref
from hello.model import DeclarativeBase, metadata, DBSession
class Mymodel(DeclarativeBase):
__tablename__ = 'mymodels'
uid = Column(Integer, primary_key = True)
data = Column(Unicode(255), nullable = False)
user_id = Column(Integer, ForeignKey('tg_user.user_id'), index = True)
user = relationship('User', uselist = False,
backref = backref('mymodels',cascade = 'all, delete-orphan'))
__all__ = ['Mymodel']
用户现在可以根据需要修改表结构,然后将其导入 model/__init__.py 中,以使模型在应用程序中可用。
为了创建模型、处理它的控制器类和索引页,可以通过以下命令同时创建这三个组件。
gearbox scaffold model controller template mymodel
此命令将导致 controllers\mymodel.py,其中正确定义了 MymodelController 类。
# -*- coding: utf-8 -*-
"""Mymodel 控制器模块"""
来自 tg 导入 reveal、redirect、validate、flash、url
# 来自 tg.i18n 导入 ugettext as _
# 来自 tg 导入谓词
来自 hello.lib.base 导入 BaseController
# 来自hello.model import DBSession
class MymodelController(BaseController):
# 如果您的控制器需要经过身份验证的用户,请取消注释此行
# allow_only = predicates.not_anonymous()
@expose('hello.templates.mymodel')
def index(self, **kw):
return dict(page = 'mymodel-index')
要开始使用此控制器,请将其安装在应用程序 RootController 中,以定义 MymodelController 的一个实例。在控制器 oot.py 中添加以下行 −
从 hello.controller.mymodel 导入 MymodelController class RootController(BaseController): mymodel = MymodelController()
还将在 templates 文件夹中创建模板支架 templates\mymodel.html。它将充当"/mymodel"URL 的索引页。
templates 文件夹中生成的 mymodel.html 文件将如下所示 −
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:py = "http://genshi.edgewall.org/"
xmlns:xi = "http://www.w3.org/2001/XInclude">
<xi:include href = "master.html" />
<head>
<title>Mymodel</title>
</head>
<body>
<div class = "row">
<div class = "col-md-12">
<h2>Mymodel</h2>
<p>Template page for Mymodel</p>
</div>
</div>
</body>
</html>

