codecamp

web.py 数据库操作

注意: 在你开始使用数据库之前,确保你已经安装了合适的数据库访问库。比如对于MySQL数据库,使用 pymysql,对于Postgres数据库使用psycopg2。

首先你需要创建一个数据库对象。

db = web.database(dbn='postgres', user='username', pw='password', db='dbname')

(根据需要修改这里 – 尤其是username 、 password 、 dbname – 。 MySQL用户还需要把 dbn 定义改为 mysql。)

这就是所有你需要做的 – web.py将会自动处理与数据库的连接和断开。

使用的的数据库引擎管理工具,在你的库中创建一个简单的表:

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 ,把 index.GET 改成下面的样子,替换整个函数:

    def GET(self):
        todos = db.select('todo')
        return render.index(todos)

然后把URL列表改回来,只保留 /:

'/', 'index',

像这样编辑并替换 index.html 的全部内容:

$def with (todos)
<ul>
$for todo in todos:
    <li id="t$todo.id">$todo.title</li>
</ul>

再访问你的网站,然后你可以看到你的todo item: “Learn web.py”。恭喜你!你已经完整地写好了一个可以从数据库读取数据的程序。现在让我们同样再写一个可以把数据写入数据库的程序。

在 index.html尾部添加:

<form method="post" action="add">
<p><input type="text" name="title" /> <input type="submit" value="Add" /></p>
</form>

然后把你的URL列表改为:

'/', 'index',
'/add', 'add'

(你必须要非常小心那些逗号。如果你省略他们,Python会把所有字符串连接起来,变成 '/index/addadd')

现在添加另一个类:

class add:
    def POST(self):
        i = web.input()
        n = db.insert('todo', title=i.title)
        raise web.seeother('/')

(注意现在我们正在使用 POST)

web.input 可以让你访问用户通过form提交的任何数据。

注意: 如果要访问多个相同名字的字段,请使用list的格式(比如:一串name=”name”的多选框):

post_data=web.input(name=[])

db.insert 把数据插入数据表 todo ,然后把新的行号返回给你。 seeother 把用户重定向到指定的URL。

一些快速补充说明: db.update 与 db.insert 差不多,除了它返回的行号是直接从sql语句里面提取的(WHERE ID=2)。

web.input、 db.query已经其他web.py中的函数返回”Storage objects”,这些东西就像字典,你除了可以 d['foo']之外,你还可以 d.foo。这可以让代码更加干净。

web.py 表单
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }