上面引用的 ancestors 属性要想有效,Category 模型类需要修改成包含一个 _get_ancestors 方法:
清单 12. 将 “ancestors” 属性的 “get” 方法添加到 Category 类中
class Category(SQLObject):
name = StringCol(length=64)
parent = ForeignKey('Category', default=None)
subcategories = MultipleJoin('Category', joinColumn='parent_id')
products = MultipleJoin('Product')
def _get_ancestors(self):
ancestor = self.parent
while ancestor:
yield ancestor
ancestor = ancestor.parent
创建控制器
TurboGears quickstart 提供了一个具有 controllers.py 模块的项目,该模块是 Root 控制器类所在的位置。这是应用程序的主入口点,也是添加新控制器方法的地方。
下面是 TurboGears expose 中与分类 HTML 模板有关的两个样例控制器方法。控制器方法会返回字典,它们在对指定的 Kid 模板进行呈现时被用作名称空间或上下文。
清单 13. 控制器类
from turbogears import controllers, expose
class Root(controllers.Root):
@expose("tgcommerce.templates.category")
def index(self):
from model import Category
category = Category.selectBy(parent=None)[0]
return dict(category=category)
@expose("tgcommerce.templates.category")
def category(self, categoryID):
from model import Category
category = Category.get(categoryID)
return dict(category=category)
在 TurboGears 中,URL 非常清楚地映射到方法上,它们都包含在 Root 控制器中。根 URL / 映射为一个名为 index 的特殊方法。通过向 Root 添加一个名为 category 的方法,它就可以通过 URL /category 进行访问了。任何提交的 URL 如果无法匹配给定方法,就会产生一个 404 错误,除非定义了一个 default 方法。
下面是一些可能的 URL 情况及其结果:
/:显示没有父 id 的第一个分类
/category?categoryID=2:显示 id 值为 2 的分类。
/category/1:显示 id 值为 1 的分类(格式为 TG 0.9)
/category:抛出一个 500 错误,这是因为缺少分类 id。
/xyz:抛出一个 404 错误
图 2 给出了分类显示的页面:
图 2. 分类显示
产品显示
对于产品显示页面来说,我们要创建一个 product 控制器,它会从数据库中检索出一个产品,并将其传递给 product Kid 模板进行呈现。
清单 14. 增加产品控制器方法
@expose("tgcommerce.templates.product")
def product(self, productID):
from model import Product
product = Product.get(productID)
return dict(product=product)
上一篇:给程序加个图标
下一篇:多继承详解
|