zoukankan      html  css  js  c++  java
  • Tornado——静态和模板文件的配置,模板语言

    提神个醒脑!

    静态和模板文件的配置

    1.静态文件路径

    我们可以通过向web.Application类的构造函数传递一个名为static_path的参数来告诉Tornado从文件系统的一个特定位置提供静态文件,如:

    app = tornado.web.Application(
        [(r'/', IndexHandler)],
        static_path=os.path.join(os.path.dirname(__file__), "static"),  # 配置静态文件路径
    )

    在这里,我们设置了一个当前应用目录下名为statics的子目录作为static_path的参数。现在应用将以读取statics目录下的filename.ext来响应诸如/static/filename.ext的请求,并在响应的主体中返回。

    注:对于静态文件目录的命名,为了便于部署,建议使用static

    2.配置静态文件的url

    我们再看刚刚内种方式访问页面时使用的路径http://127.0.0.1/static/html/index.html,这中url显然对用户是不友好的,访问很不方便。我们可以通过tornado.web.StaticFileHandler来自由映射静态文件与其访问路径url。

    tornado.web.StaticFileHandler是tornado预置的用来提供静态资源文件的handler。

    import os
    from tornado.web import StaticFileHandler    # 引入StaticFileHandler模块
    
    	current_path = os.path.dirname(__file__)    # 上一层目录
    	
        app = tornado.web.Application(
            [
            (r"/$",IndexHandler),
            (r"/(.*)",StaticFileHandler,{"path":os.path.join(current_path, "statics/html"), "default_filename":"index.html"}),  # 优化文件路径(不用在url打那么多),设置默认值为index
            ],
            debug = True,
            static_path = os.path.join(current_path,'static'),   # 配置静态文件路径
        )
    
    • path 用来指明提供静态文件的根路径,并在此目录中寻找在路由中用正则表达式提取的文件名。
    • default_filename 用来指定访问路由中未指明文件名时,默认提供的文件。

    3.配置模板文件路径

    import os
    from tornado.web import StaticFileHandler    # 引入StaticFileHandler模块
    
    	current_path = os.path.dirname(__file__)    # 上一层目录
    	
        app = tornado.web.Application(
            [
            (r"/$",IndexHandler),
            (r"/(.*)",StaticFileHandler,{"path":os.path.join(current_path, "statics/html"), "default_filename":"index.html"}),  # 优化文件路径(不用在url打那么多),设置默认值为index
            ],
            debug = True,
            static_path = os.path.join(current_path,'static'),   # 配置静态文件路径
            template_path = os.path.join(current_path,'template'),   # 配置模板路径
        )
    

    注:在handler中使用self.render()方法来渲染模板并返回给客户端。

    模板语言

    tornado的母版语言和Django/jinja2差不多,这里着重不同的地方。

    1.变量与表达式

    tornado中的{{}}不仅可以是变量,还可以是表达式:

    前端:

    <li class="house-item">
        <a href=""><img src="/static/images/home01.jpg"></a>
        <div class="house-desc">
            <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div>
            <div class="house-price">¥<span>{{p1 + p2}}</span>/晚</div>
            <div class="house-intro">
                <span class="house-title">{{"123".join(titles)}}</span>
                <em>整套出租 - {{score}}分/{{comments}}点评 - {{position}}</em>
            </div>
        </div>
    </li>
    

    后端渲染:

    class IndexHandler(RequestHandler):
        def get(self):
            house_info = {
                "price": 398,
                "title": "宽窄巷子+160平大空间+文化保护区双地铁",
                "score": 5,
                "comments": 6,
                "position": "北京市丰台区六里桥地铁"
            }
            self.render("index.html", **house_info)
    

    2.for,if,while控制语句

    {% if ... %} ... {% elif ... %} ... {% else ... %} ... {% end %}
    {% for ... in ... %} ... {% end %}
    {% while ... %} ... {% end %}
    

    3.函数

    static_url()

    Tornado模板模块提供了一个叫作static_url的函数来生成静态文件目录下文件的URL。如下面的示例代码:

    <link rel="stylesheet" href="{{ static_url("style.css") }}">

    优点:

    • static_url函数创建了一个基于文件内容的hash值,并将其添加到URL末尾(查询字符串的参数v)。这个hash值确保浏览器总是加载一个文件的最新版而不是之前的缓存版本。无论是在你应用的开发阶段,还是在部署到生产环境使用时,都非常有用,因为你的用户不必再为了看到你的静态内容而清除浏览器缓存了。
    • 另一个好处是你可以改变你应用URL的结构,而不需要改变模板中的代码。例如,可以通过设置static_url_prefix来更改Tornado的默认静态路径前缀/static。如果使用static_url而不是硬编码的话,代码不需要改变。

    4.自定义函数

    在模板中还可以传自己编写的函数,只需要将函数名作为模板的参数传递即可,就像其他变量一样。

    可以在后端直接定义一个函数,传到前端:

    def house_title_join(titles):
        return "+".join(titles)
    
    class IndexHandler(RequestHandler):
        def get(self):
            house_list = [
            {
                "price": 398,
                "titles": ["宽窄巷子", "160平大空间", "文化保护区双地铁"],
                "score": 5,
                "comments": 6,
                "position": "北京市丰台区六里桥地铁"
            },
            {
                "price": 398,
                "titles": ["宽窄巷子", "160平大空间", "文化保护区双地铁"],
                "score": 5,
                "comments": 6,
                "position": "北京市丰台区六里桥地铁"
            }]
            self.render("index.html", houses=house_list, title_join = house_title_join)

    前端就像我们在python中一样,可以直接调用:

    <ul class="house-list">
        {% if len(houses) > 0 %}
            {% for house in houses %}
            <li class="house-item">
                <a href=""><img src="/static/images/home01.jpg"></a>
                <div class="house-desc">
                    <div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div>
                    <div class="house-price">¥<span>{{house["price"]}}</span>/晚</div>
                    <div class="house-intro">
                        <span class="house-title">{{title_join(house["titles"])}}</span>
                        <em>整套出租 - {{house["score"]}}分/{{house["comments"]}}点评 - {{house["position"]}}</em>
                    </div>
                </div>
            </li>
            {% end %}
        {% else %}
            对不起,暂时没有房源。
        {% end %}
    </ul>
    

    5.母版继承

    和Django差不多,tornado结尾用end。

    {% extends "xxx.html" %}

    {% block block_name %} {% end %}

    6.转义

    当我们在页面写<、>、"等时,被转换为对应的html(&lt;、&gt;)字符。

    输出不被转义的原始格式的3种方式:

    1、{{ xxx }} ==> {% raw xxx %} ;

    2、在Application构造函数中传递autoescape=None,关闭转义;

    3、在每页模板中修改自动转义行为,添加{% autoescape None %}语句;

    注意:在Firefox浏览器中会直接弹出alert窗口,而在Chrome浏览器中,需要set_header("X-XSS-Protection", 0),可以在self.write()前添加响应头self.set_header("X-XSS-Protection",0)解决

    关闭自动转义后,可以使用escape()函数来对特定变量进行转义{{ escape(xxx) }}

  • 相关阅读:
    Linux安装配置nginx
    Linux下apache安装php
    Linux安装配置apache
    Linux安装mysql
    安装Linux CentOS与用Xshell实现远程连接
    关于IIS上Yii2的Url路由美化
    安装android Studio和运行react native项目(跳坑篇)
    安装android Studio和运行react native项目(基础篇)
    第10章 同步设备I/O和异步设备I/O(3)_接收I/O请求完成通知的4种方法
    第10章 同步设备I/O和异步设备I/O(2)_同步IO和异步IO基础
  • 原文地址:https://www.cnblogs.com/x54256/p/8195928.html
Copyright © 2011-2022 走看看