bzr branch lp:webpy
(安装bzr. 目前web.py 0.3还没有发布, 只能从bzr里取出)
安装web.py, MySQLdb(数据库驱动), DBUtils(连接池用到), Mako(备用的模板引擎, 可能需要安装setuptools).
数据库:
- 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');
建立tpl目录,放置模板.
新建一个main.py:
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import web
- urls = (
- '/(.*)', 'controler'
- )
- app = web.application(urls, globals())
- class controler:
- def GET(self, name):
- render = web.template.render('tpl/')
- return render.main(name)
- if __name__ == "__main__":
- app.run()
新建模板: tpl/main.html
$def with (name)
$if name:
你好阿, $name.
$else:
你好,世界.
运行: python main.py
加上数据库的东西:
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import web
- urls = (
- '/', 'controler'
- )
- app = web.application(urls, globals())
- db = web.database(dbn='mysql', db='web', user='root', pw='xixihaha')
- class controler:
- def GET(self):
- render = web.template.render('tpl/')
- todos = db.select('todo')
- return render.main(todos)
- if __name__ == "__main__":
- app.run()
模板也顺便改成:
$def with (todos)
<ul>
$for todo in todos:
<li id="t$todo.id">$todo.title</li>
</ul>
运行, 浏览.
添加todo:
改main.py:
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import web
- urls = (
- '/', 'controler',
- '/add', 'add'
- )
- app = web.application(urls, globals())
- db = web.database(dbn='mysql', db='web', user='root', pw='xixihaha')
- class controler:
- def GET(self):
- render = web.template.render('tpl/')
- todos = db.select('todo')
- return render.main(todos)
- class add:
- def POST(self):
- i = web.input()
- n = db.insert('todo', title=i.title)
- web.seeother('./#t' + str(n))
- if __name__ == "__main__":
- app.run()
模板main.html也改成:
$def with (todos)
<ul>
$for todo in todos:
<li id="t$todo.id">$todo.title</li>
</ul>
<form method="post" action="add">
<p><input type="text" name="title" /> <input type="submit" value="Add" /></p>
</form>
Layout模板:
<html>
$:content
</html>