Some reminiscences, some memories

Just another boring day
« RatProxy 在 cygwin 下的编译
为什么“is_file比file_exists快N倍” »

26

Aug

TurboGears 学习笔记-控制器

mikespook 

这部分内容虽然不多,但是看了好多天。

在 tgadmin 自动生成的 appname/appname/controller.py 中有如下代码:

1 import turbogears as tg
2 from turbogears import controllers, expose, flash
3 from cherrypy import request
4 # from sandbox import model
5 # import logging
6 # log = logging.getLogger(“sandbox.controllers”)
7
8 class Root(controllers.RootController):
9 @expose(template=“sandbox.templates.welcome“)
10 def index(self):
11 import time
12 # log.debug(“Happy TurboGears Controller Responding For Duty”)
13 flash(“Your application is now running“)
14 return dict(now=time.ctime())

Root.index 是 http://127.0.0.1:8080/index 的控制器。如果需要添加新的“页面”,只要在 Root 中添加新的方法即可:

16 @expose()
17 def foobar(self):
18 return ‘Just another page‘

@expose() 是一定要加的,不加这个,无法定位控制器的方法。

我这里没有添加 template,所以框架将返回的内容直接作为字符串输出在页面上了。

如果想使用模板(默认为Kid),则指定模板名称 template=”appname.appname.foobar”,这个对应的是项目根开始的目录和模板文件名的结构。实际模板应保存在 appname/appname/foobar.kid 文件中。

控制器通过 expose 出来的方法的参数获得浏览器传递过来的变量,对上面的方法稍加改造即可:

16 @expose()
17 def foobar(self, *args, **kv):
18 if (kv.has_key(‘name‘)):
19 name = kv['name']
20 else:
21 name = ‘unknown‘
22 return ‘Your name is ‘ + name

当访问 http://127.0.0.1:8080/foobar 时,页面显示 Your name is unknown。当访问 http://127.0.0.1:8080/foobar?name=fool 时,页面显示 Your name is fool。

当提供一个名为 default 的方法 expose 时,所有未定义的访问都会转到这个方法上去。这时,args 参数包含了访问所用的名字。例如访问 http://127.0.0.1:8080/barfoo,而 barfoo 未定义,那么default 方法被调用。同时 args[0] = “barfoo“。

好像控制器最基本的使用就这么些东西了,有点类似 Zend Framework 的 Controller->Action 的形式,仅仅是形式。

This entry was posted on Tuesday, August 26th, 2008 at 10:28 and is filed under Python. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Trackback URI | Comments RSS

 

September 2010
M T W T F S S
« Aug    
 12345
6789101112
13141516171819
20212223242526
27282930  

Recent Comments

  • cbf107 on 我们精通精通
  • mikespook on 我们精通精通
  • == on 我们精通精通
  • 老熊 on 关于Web编程异步模型的白日梦
  • Some reminiscences, some memories » Blog Archive » Akihabara 指南目录 on Akihabara 指南

Tags

乱码 协程 地震 备案 安装 广州 异步 性能 我爱发明 扯淡 招聘 游戏 漏洞 翻译 豆瓣 39.com Adobe akihabara config countdown Demo Flash game engine golang google html5 issue linux Micromedia MongoDB mysql NetBeans nginx NoSQL oracle PHP phpunit Python trac ubuntu xdebug xml xubuntu yield Zend Framework

Blogroll

  • Blog on 27th Floor
  • DBA notes
  • Tim[后端技术]
  • 唐海燕
  • 小众音乐
  • 抚琴居
  • 某人的栖息地
  • 番茄’s Blog
  • 網站製作學習誌
  • 纸老虎传媒

Old friends

  • cbf107

Only

  • 媚惑桃花

OurPNP

  • Biaoest:标的最高级
  • flexsns-官方博客
  • PNP University
  • PNP街坊
  • smallfish 鱼哥的窝子
  • 冰山日志
  • 墙外的光神V5
  • 夜雨's Blog
  • 小冬kobe
  • 小路的奇异世界
  • 广州萌芽工作室
  • 老甘blog
  • 赖勇浩的编程私伙局

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Powered by WordPress
mikespook.com 粤ICP备09065095号