学习webpy官网示例笔记

今天在优化自动化运维脚本的过程中发现github上,很有借鉴意义的项目:https://github.com/luxiaok/SaltAdmin.git,顿时被webpy简单的语法吸引(和django相比)。

参考资料:
http://webpy.org/docs/0.3/tutorial.zh-cn

代码结构

.
├── demo.py
└── templates
    ├── db.html
    └── test.html

cat demo.py

# -*- coding: utf-8 -*-

import web
render = web.template.render('templates/')
#urls = ( '/(.*)','index')
urls = ('/demo','index')
urls = urls + ('/demo2','index2')
urls = urls + ('/demo3','index3')
urls = urls + ('/demo4/(.*)','index4')
urls = urls +  ('/db','db')
urls = urls  + ('/add','add')

# 日志
web.config.debug=True

#http://192.168.3.106:8080/demo
class index:
    def GET(self):
        return "hello,world"

# http://192.168.3.106:8080/demo2?name=patrick
class index2:
    def GET(self):
        i = web.input(name=None)
        return render.test(i.name)

#http://192.168.3.106:8080/demo3
class index3:
    def GET(self):
        name = 'Patrick'
        return render.test(name)

# http://192.168.3.106:8080/demo4/Patrick
class index4:
    def GET(self,name):
        # test is template name
        return render.test(name)

class db:
    def GET(self):
        db = web.database(dbn='mysql',
                user='xxxx',
                pw='xxxx',
                db='webpy_test',
                host='xxxxx')
        todos = db.select('todo')
        return render.db(todos)

class add:
    def POST(self):
        i = web.input()
        db = web.database(dbn='mysql',
                user='xxxx',
                pw='xxxxx',
                db='webpy_test',
                host='xxxxxx')
        n = db.insert('todo',title=i.title)
        raise web.seeother('/db')

if __name__ == '__main__':
    app = web.application(urls,globals())
    app.run()

cat templates/test.html

$def with(name)

$if name:
    I just wanted to say <em>hello</em> to $name.
$else:
    <em> hello</em>,world!

cat templates/db.html

$def with(todos)

<url>
$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>

启动服务

python demo.py 8080

相关内容
1,创建数据库webpy_test
2,创建表

CREATE TABLE webpy_test.todo (
  id serial primary key,
  title text,
  created timestamp default now(),
  done boolean default false);

3,添加数据

INSERT INTO todo (title) VALUES ('Learn web.py');
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值