emplates/')
这告诉web.py 在哪里可以搜索得到模板目录。
提示:可在render 调用里添加cache = False 使得每次访问页面时都重载模板。
下面继续修改code.py 文件的GET 方法:
def GET(self):
name = ‘Bob’
print render.index(name)
上面的”index“ 是模板的名字,”name“ 是传递过去的参数。
修改code.py 文件的urls 变量:
urls=(
'/(.*)', 'index')
上面的“/(.*)” 是一个正则表达式。
再将GET 方法修改如下:
def GET(self,name):
print render.index(name)
现在,访问”/“的话,会显示”Hello, world!“;访问”/Joe“ 的话,会显示”I just want to say hello to Joe“。
如果你想学习更多关于web.py templates 的话,可以访问templetor page。
5. 数据库
注意:在你开始连接数据库之前,请先安装正确的数据库驱动。例 如,MySQL 使用MySALdb,Postgre 使用psycopg2。
添加以下代码,则可以正确配置你的数据库:
web.config.db_parameters = dict(
dbn='postgres',
user='username',
pw='password',
db='dbname'
)
现在,先行在数据库里创建一个简单的表:
CREATE TABLE todo (
id serial primary key,
title text,
created timestamp default now(),
done boolean default 'f'
);
初始化一行:
INSERT INTO todo (title) VALUES ('Learn web.py');
回到code.py,修改GET 方法如下:
def GET(self):
todos = web.select('todo')
print render.index(todos)
修改urls 变量:
urls = (
'/', 'index')
重新编辑index.html 文件如下:
$def with (todos)
<ul>
$for todo in todos:
<li id="t$todo.id">$todo.title</li>
</ul>
现在,可以访问”/“,如果显示”Learn web.py“,则祝贺你成功了!
现在,再让我们看看如何向数据库写入。
在index.html 文件的尾部添加如下内容:
<form method="post" action="add">
<p>
<input type="text" name="title" />
<input type="submit" value="Add" />
</p>
</form>
修改code.py 文件的urls 变量如下:
urls = (
'/', 'index',
'/add', 'add'
)
在code.py 里添加一个类:
class add:
def POST(self):
i = web.input()
n = web.insert('todo', title=i.title)
web.seeother('/')
web.input 使你能够方便地访问用户通过表单提交上来的变量。web.insert 用于向数据库的 “todo” 表插入数据,并且返回新插入行的ID。web.seeother 用于重转向到”/“。
提示:对于数据库的操作,还有web.transact(), web.commit(), web.rollback(),web.update()。
在web.py 里,还有web.input,web.query 和其它的函数,返回”Storage objects”,可以像字典型类(dictionaries) 的使用。
6. 总结
web.py 的确相当的小巧,应当归属于轻量级的web 框架。但这并不影响web.py 的强大,而且使用起来很简单、很直接。在实际应用上,web.py 更多的是学术上的价