模板介绍

在 Python 中写 HTML 不是聪明的选择,相反在 HTML 中写 Python 则有趣的多。幸运的是,web.py 让这件事情做得简单而又漂亮。

在webpy中,一般采用templates来存放html页面文件。大概的访问方式如下:

urls = (
    '/renderTest', 'Test'
)

render = web.template.render('templates')

class Test:
    def GET(self):
        return render.showRender('hello world')
if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
  1. urls中定义了url映射,访问 /renderTest 会直接条用 class Test 来处理;

  2. web.template.render(path)是用来指定存放html模板的目录,上面指定了html的指定存放位置位于当前文件夹下的 templates 文件下;

  3. 返回的render.showRender()表示在render所指定的目录下寻找 showRender.html文件并作为返回结果。

1. 在main.py中添加以上内容

内容如上

2. 创建模板文件showRender.html

2.1 在项目根目录下,创建模版目录templates

2.2 编辑showRender.html模板文件,内容如下:

$def with(str)
<html>
    <body>
         $for i in range(5):
            <h1>$str</h1>
    </body>
</html>

webpy支持模板,支持参数以$def with()开始作为函数的开始;

在html中可以使用python语句,但语句前需要添加$,在上面的html中str会在页面上打印5次。

$# 用来注释

定义模板函数时,使用 $def

在webpy中,提供了默认的静态文件的访问方式

  • webpy作为服务器时,在当前目录下建立static目录,webpy会自动在该目录下寻找静态文件

  • 处理 web.py 之前将请求映射到指定的目录。

更多参考: http://webpy.org/docs/0.3/templetor

http://webpy.org/docs/0.3/tutorial.zh-cn#templating

3. postman测试用例