python后台框架web.py使用render模板

在上一个案例中,我们使用从文件中读取的方式,代码如下:

# -*- encoding:UTF-8 -*-
import web

urls = (
    '/index','index',
    '/blog/\d+','Blog',
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self,name):
        return open(r'hello.html').read()
class index:
    def GET(self):
        return web.input()
class Blog:
    def POST(self):
        return web.input()
    def GET(self):
        return web.ctx.env
if __name__ == "__main__":
    app.run()

对于hello路由我们使用文件读取return open(r’hello.html’).read()
接下来我们进行改造,使用render模板,同样可以实现,而且功能更强大。
主要是有如下方法:

模板文件读取
render.index("参数")
结果数据获取
model.select("sql")
URL跳转
web.seeother("/")

第一步改造:

# -*- encoding:UTF-8 -*-
import web
render = web.template.render("templates")
urls = (
    '/index','index',
    '/blog/\d+','Blog',
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self,name):
        return render.hello()
class index:
    def GET(self):
        return web.input()
class Blog:
    def POST(self):
        return web.input()
    def GET(self):
        return web.ctx.env
if __name__ == "__main__":
    app.run()

这里的templates是指文件夹名称,render.hello()指向hello.html文件。
重启,项目正常访问。

render传递参数

class hello:
    def GET(self,name):
        return render.hello(name)#把name传递到hello.html页面

hello.html页面接收解析

$def with (name)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<form action="/blog/111" method="post">
    用户名:<input name="username" value="$name" type="text"/><br>
    密码:<input name="password" type="text"><br>
    <input type="submit" value="提交">


</form>
</body>
</html>

使用$def with (name)告知这个是python语法,效果如下:
这里写图片描述

URL跳转

class index:
    def GET(self):
        return web.seeother("http://www.baidu.com")

当访问http://localhost:8080/index的时候将跳转到百度的页面。

专业墙纸贴纸厨房用具装饰出售,本人网店经营,访问即是爱

博客对你有用记得访问下哦,增加下访问量,如有需要可以下单购买哦^_^。店铺地址https://item.taobao.com/item.htm?id=570637716145

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/81502250