web.py is a web framework for Python that is as simple as it is powerful.
Github源码:https://github.com/webpy/webpy
先安装active-python,安装后在环境变量中添加python路径。
active-python 自带pypm
pypm install {moduleName}
安装第三方组件:web.py, flup, psycopg2 , Postgres
psycopg2是Postgres的python driver,如果用mysql,就pypm install mysql-python来装mysqldb。
import web
urls = (
'/', 'index'
)
class index:
def GET(self):
return "Hello, world!"
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
Hello world程序添加了url引导和服务器对get的处理。
在主函数中我们创建一个应用程序并在全局范围内包含了对urls的处理并运行。urls内第一部分是匹配URL的正则表达式,会捕捉参数,第二部分是接受请求的类名称。
这行也就是说对于127.0.0.1/ 直接调用index函数。
使用模版的话 在工程下新建template文档然后在内新建index.html
$def with (name)
$if name:
I just wanted to say <em>hello</em> to $name.
$else:
<em>Hello</em>, world!
$name对应之前url正则表达式获取到的参数,此外在python代码内加入如下
render = web.template.render('templates/')
这会告诉web.py到你的模板目录中去查找模板。然后把 index.GET
改成:
name = 'Bob'
return render.index(name)
读取写入数据库,以mysql为例子
对mysql进行操作,use test;选择数据库
CREATE TABLE todo (
id serial primary key,
title text,
created timestamp default now(),
done boolean default '0' );
创建一个名为todo的表
INSERT INTO todo (title) VALUES ('Learn web.py');
随便插一个进去
以下是python代码段和html代码段,对比着看
import web db = web.database(dbn='mysql', user='root', pw='password', db='test') render = web.template.render('templates/') urls = ( '/', 'index', '/add', 'add' ) class index: def GET(self): todos = db.select('todo') #数据库的操作 return render.index(todos) #对于客户端的GET请求,服务器访问数据库的todo表并在模版index.html内传入数据库数据,for循环展示所有数据
class add: def POST(self): i = web.input() #获取文本 n = db.insert('todo', title=i.title) #表名和插入的数据值 raise web.seeother('/') #重定向到首页 if __name__ == "__main__": app = web.application(urls, globals()) app.run()
以下是index.html代码段
$def with (todos) <ul> $for todo in todos: <!-- for循环 --> <li id="t$todo.id">$todo.title</li> </ul> <form method="post" action="add"> <!-- 输入框 响应客户端post操作--> <p><input type="text" name="title" /> <input type="submit" value="Add" /></p> </form>