TurboGears - URL 层次结构
有时,Web 应用程序可能需要具有多个级别的 URL 结构。TurboGears 可以遍历对象层次结构以找到可以处理您的请求的适当方法。
使用 gearbox"快速启动"的项目在项目的 lib 文件夹中有一个 BaseController 类。它以"Hello/hello/lib/base.py"的形式提供。它作为所有子控制器的基类。为了在应用程序中添加 URL 的子级别,请设计一个从 BaseController 派生的名为 BlogController 的子类。
此 BlogController 有两个控制器函数,index() 和 post()。两者都旨在公开一个模板,blog.html 和 post.html。
注意 − 这些模板放在子文件夹 − templates/blog 中
class BlogController(BaseController):
@expose('hello.templates.blog.blog')
def index(self):
return {}
@expose('hello.templates.blog.post')
def post(self):
from datetime import date
now = date.today().strftime("%d-%m-%y")
return {'date':now}
现在在 RootController 类(在 root.py 中)中声明此类的对象,如下所示 −
class RootController(BaseController):
blog = BlogController()
顶级 URL 的其他控制器函数将与之前一样存在于此类中。
当输入 URL http://localhost:8080/blog/ 时,它将映射到 BlogController 类内的 index() 控制器函数。同样,http://localhost:8080/blog/post 将调用 post() 函数。
blog.html 和 post.html 的代码如下 −
Blog.html
<html>
<body>
<h2>My Blog</h2>
</body>
</html>
post.html
<html>
<body>
<h2>My new post dated $date</h2>
</body>
</html>
当输入 URL http://localhost:8080/blog/ 时,将产生以下输出 −
当输入 URL http://localhost:8080/blog/post 时,将产生以下输出 −

