tornado-模板,转义,上传静态文件

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("ces.html")

    def post(self, *args, **kwargs):
        user = self.get_argument("name")
        urllist = [
            ("https://www.shiguangkey.com","时光"),
            ("https://www.baidu.com","百度")
                   ]
        atga = '<a href="https://www.shiguangkey.com">时光钥匙</a>'
        self.render("4.1-ces.html",
                    username =user,
                    urllist = urllist,
                    atga = atga,
                    )


application = tornado.web.Application(
    handlers=[                      # 列表按顺序匹配
        (r"/", MainHandler),
        ],
    template_path='templates',  # 表明页面html的路径
    static_path='static',
    debug=True,           # 上传代码后服务器自动重启
    autoescape=None,
)

模板代码

<!DOCTYPE html>
{#% autoescape None %#}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    欢迎 {{username}}登录
    <br>

    {% if username!='no' %}
        欢迎 {{username}}登录
        <img src="static/images/1.png" alt="" style=" 200px;height:200px">
        <img src="{{static_url('images/2.jpg')}}" alt="" style=" 200px;height:200px">
    {% else %}
        what is your name?
    {% end %}
    <br>
    {% for i in urllist %}
    <a href="{{i[0]}}" target="_blank">{{i[1]}}</a>
    {% end%}
    <br>
    {% set a = 0 %}{% while a<5 %} {{a}}a{% set a += 1 %}{% end %}
    <br>
    {{ escape(atga) }}
    <br>
    {% raw atga %}
    {{  atga }}

</body>
</html>

知识点:
模版
tornado自带模板
# html文件 通过tornado服务渲染,可以往动态的网页传入数据

# {{ python表达式,变量 }}
# {% if a=0%} haha {%end %}
# {% for i in urllist %}a href="{{i[0]}}" target="_blank">{{i[1]}}</a>{% end %}
# {% set a = 0 %}{% while a<5 %} haha{% set a += 1 %}{% end %}
# {# 注释模板 #}
# {{!a=1}} 模板加上!直接将代码转义出来

   # {% apply upper %} hello world {% end %} def upper(a): return a.upper() 将所有的字符串都在upper执行一边
  # {% raw linkify('百度链接:https://www.baidu.com') %} 将内容变成a链接
取消转义:
    # tornado给模板传入字符串,都会转译成html编码
    #     变量atga = <a href="https://www.shiguangkey.com">时光钥匙</a>
    #  超链接标签传给模板{{ atga }}转译成
            # &lt;a href=&quot;https://www.shiguangkey.com&quot;&gt;时光钥匙&lt;/a&gt;
            # 在解析到浏览器就变成 <a href="https://www.shiguangkey.com">时光钥匙</a>
            # 不能成为链接
# 取消转移 # 模板内 不影响其他模板 # {% atga %} --模板局部取消转义 # <!DOCTYPE html>{% autoescape None %} --全模块 # 防止被取消转移 escape(atga) # 全局(整个项目,所有模块都不转义) # application autoescape=None,

引用静态文件:
# 传入图片 如果显示失败 检查是否上传到虚拟环境,和是否在application中表明路径路径 static_path='static'
# <img src="static/images/1.png" alt="">
# *** 或者用函数 static_url 该方法更强大
# <img src="{{static_url('images/2.jpg')}}"> 该函数自动补全路径
 
原文地址:https://www.cnblogs.com/tangpg/p/8489417.html