web.py框架入门

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

	
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值