今天在优化自动化运维脚本的过程中发现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');