📅  最后修改于: 2020-10-19 03:35:48             🧑  作者: Mango
Gearbox工具箱包含scaffold命令,这对于快速创建TurboGears应用程序的新组件非常有用。由gearbox的quickstart命令生成的应用程序在model文件夹(model.py.template),templates文件夹(template.html.template)和controllers文件夹(controller.py.template)中具有骨架模板。这些“ .template”文件用作为应用程序创建新支架的基础
例如,为了创建一个名为mymodel的新模型,只需运行以下命令-
gearbox scaffold model mymodel
此命令将使用在其中定义的newmodel类生成model / mymodel.py。
# -*- 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 controller module"""
from tg import expose, redirect, validate, flash, url
# from tg.i18n import ugettext as _
# from tg import predicates
from hello.lib.base import BaseController
# from hello.model import DBSession
class MymodelController(BaseController):
# Uncomment this line if your controller requires an authenticated user
# allow_only = predicates.not_anonymous()
@expose('hello.templates.mymodel')
def index(self, **kw):
return dict(page = 'mymodel-index')
要开始使用此控制器,请将其安装在应用程序RootController内,只是为了定义MymodelController的实例。将这些行添加到controllers \ root.py-
From hello.controller.mymodel import MymodelController
class RootController(BaseController): mymodel = MymodelController()
还将在模板文件夹中创建模板脚手架templates \ mymodel.html。它将充当“ / mymodel” URL的索引页。
模板文件夹中生成的mymodel.html文件将如下所示-
Mymodel
Mymodel
Template page for Mymodel