Turbogears-scaffolding

提供:Dev Guides
移動先:案内検索

TurboGears –足場

Gearboxツールキットにはscaffoldコマンドが含まれており、TurboGearsアプリケーションの新しいコンポーネントをすばやく作成するのに非常に便利です。 gearboxのクイックスタートコマンドで生成されたアプリケーションには、モデルフォルダー(model.py.template)、テンプレートフォルダー(templatel.template)、コントローラーフォルダー(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 内にインポートして、モデルをアプリケーション内で使用できるようにすることができます。

モデルを作成するには、次のコマンドを使用して、モデルを処理するコントローラークラスとこれら3つのコンポーネントすべてを同時に作成できます。

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')

このコントローラーの使用を開始するには、MymodelControllerのインスタンスを定義するためだけに、アプリケーションRootController内にマウントします。 controllers \ root.pyにこれらの行を追加します-

From hello.controller.mymodel import MymodelController

class RootController(BaseController): mymodel = MymodelController()

テンプレートのscaffold templates \ mymodellも、templatesフォルダーに作成されます。 「/mymodel」URLのインデックスページとして機能します。

テンプレートフォルダに生成された* mymodellファイル*は次のようになります-

<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 = "masterl"/>

   <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>