web.py是python web开发的一个轻量级框架。
web.py可以通过pip命令安装,pip install web.py
编写官网示例代码:
$ vi index.py
import web
urls = (
"/" , 'hello',
)
class hello:
def GET(self):
return "Hello,World!"
app = web.application(urls,globals())
if __name__=="__main__":
app.run()
运行:
$ python index.py
浏览器查看结果 http://localhost:8080
以上是一个最简单的官网示例。通过直接返回文字字符串,得到请求结果,我们可以利用web.py提供的模板工具,指定html页面来达到使用模板的效果。
在第一行代码之后增加如下语句:
render = web.template.render('template/')
这句代码指定模板目录在template文件夹中,这样,我们还需要在项目中建立template目录,用来存放html页面。
修改index的GET方法,使用render.index(name='feiy')来代替返回的内容,还带着name参数到页面,这样页面就可以显示$name。
class index:
def GET(self):
return render.index(name='feiy');
编辑页面template/index.html内容如下:
$def with(name)
$if name:
I just wanted to say <em>hello</em> to $name.
$else:
<em>Hello</em>,world!
启动web,通过浏览器访问http://localhost:8080/
连接数据库,这里选择postgres数据库
准备数据库和表
在第二行代码之后增加连接数据库的语句,如下:
db = web.database(dbn='postgres',user='postgres',pw='',db='mydb')
想要在代码中连接postgres,需要安装postgres数据库驱动库,可以使用pip install pgdb,如果没有安装则会报错:ImportError: Unable to import psycopg2 or psycopg or pgdb
为了测试数据库连接,我们设定,获取数据库中的xx_user表中的数据,并显示在用户列表页面中。
1、修改路由配置
urls = (
"/" , "index",
"/list" , "userlist",
)
2、增加路由映射
class userlist:
def GET(self):
userlist = db.select("xx_user")
return render.userlist(userlist)
3、编写页面
vi template/userlist.html
$def with(userlist)
<ul>
$for user in userlist
<li>$user.id|$user.name|$user.mobile</li>
</ul>
最后贴出index.py全部代码
import web
render = web.template.render('template/')
db = web.database(dbn='postgres',user='postgres',pw='',db='mydb')
urls = (
"/" , 'index',
"/list" , 'userlist',
)
class index:
def GET(self):
return render.index(name='feiy')
class userlist:
def GET(self):
userlist = db.select('xx_user')
return render.userlist(userlist)
app = web.application(urls,globals())
if __name__=="__main__":
app.run()
4、运行python index.py
5、浏览器查看 http://localhost:8080/list