web.py 0.3 - 无废话实例

web.py 0.3 - 无废话实例

分类: Python Web 2239人阅读 评论(1) 收藏 举报
 取最新版的web.py:

bzr branch lp:webpy

(安装bzr. 目前web.py 0.3还没有发布, 只能从bzr里取出)

 

安装web.py, MySQLdb(数据库驱动), DBUtils(连接池用到), Mako(备用的模板引擎, 可能需要安装setuptools).

 

数据库:

 

  1. CREATE TABLE todo ( 
  2.   id serial primary key, 
  3.   title text, 
  4.   created timestamp default now(), 
  5.   done boolean default 'f' 
  6. ); 
  7. INSERT INTO todo (title) VALUES ('Learn web.py'); 

 

 

建立tpl目录,放置模板.

 

新建一个main.py:

 

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import web
  4. urls = (
  5.         '/(.*)''controler'
  6. )
  7. app = web.application(urls, globals())
  8. class controler:
  9.         def GET(self, name):
  10.                 render = web.template.render('tpl/')
  11.                 return render.main(name)
  12. if __name__ == "__main__":
  13.         app.run()

 

 

 

新建模板: tpl/main.html

 

$def with (name)

$if name:

        你好阿, $name.

$else:

        你好,世界.

 

 

运行: python main.py

 

浏览: http://localhost/

http://localhost/daniel/

http://localhost/杨丹尼

 

 

加上数据库的东西:

 

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import web
  4. urls = (
  5.         '/''controler'
  6. )
  7. app = web.application(urls, globals())
  8. db = web.database(dbn='mysql', db='web', user='root', pw='xixihaha')
  9. class controler:
  10.         def GET(self):
  11.                 render = web.template.render('tpl/')
  12.                 todos = db.select('todo')
  13.                 return render.main(todos)
  14. if __name__ == "__main__":
  15.         app.run()

 

 

模板也顺便改成:

 

$def with (todos)

<ul>

        $for todo in todos:

                <li id="t$todo.id">$todo.title</li>

</ul>

 

 

运行, 浏览.

 

 

添加todo:

 

改main.py:

 

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import web
  4. urls = (
  5.         '/''controler',
  6.         '/add''add'
  7. )
  8. app = web.application(urls, globals())
  9. db = web.database(dbn='mysql', db='web', user='root', pw='xixihaha')
  10. class controler:
  11.         def GET(self):
  12.                 render = web.template.render('tpl/')
  13.                 todos = db.select('todo')
  14.                 return render.main(todos)
  15. class add:
  16.         def POST(self):
  17.                 i = web.input()
  18.                 n = db.insert('todo', title=i.title)
  19.                 web.seeother('./#t' + str(n))
  20. if __name__ == "__main__":
  21.         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>

 

 

posted @ 2013-06-06 12:48  顶顶顶顶  阅读(183)  评论(0)    收藏  举报