Tornado 模板(StaticFileHandler/static_path/template_path等) 筆記


使用StaticFileHandler進行首頁默認訪問頁面,最好將StaticFileHandler放在最后面,這樣不會覆蓋要匹配自定義的路徑

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.options import options
from tornado.web import RequestHandler, StaticFileHandler
import os

current_path = os.path.dirname(__file__)
tornado.options.define('port', type=int, default=8000, help="服務器端口")

class IndexHandler(RequestHandler):
    def get(self):
        self.write('OK')

if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application([
        (r'/(.*)', StaticFileHandler, dict(path=os.path.join(current_path, 'static/html'), default_filename='index.html')),
    ], debug=True)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

 

static_path/template_path

static_path:設置靜態文件的訪問目錄

template_path:設置靜態頁面路徑

static_url(): 根據設置的靜態,目錄尋找靜態文件

render():跳轉文件,使用render默認的是模板轉義。

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.options import options
from tornado.web import RequestHandler, StaticFileHandler
import os

current_path = os.path.dirname(__file__)
tornado.options.define('port', type=int, default=8000, help="服務器端口")

class IndexHandler(RequestHandler):
    def get(self):
        # self.render('index.html')  # 跳轉靜態頁面
        dict1 = {'name': 'namejr', 'age':22}
        self.render('index.html',dict1=dict1)  # 使用render()還可以傳遞參數

if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application([
        (r'/', IndexHandler),
        # 使用StaticFileHandler進行首頁默認訪問頁面,最好將StaticFileHandler放在最后面,這樣不會覆蓋要匹配自定義的路徑
        (r'/(.*)', StaticFileHandler, dict(path=os.path.join(current_path, 'static/html'), default_filename='index.html')),
    ], debug=True, static_path=os.path.join(current_path, 'static'), template_path=os.path.join(current_path, 'templates'))
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

 

使用render()傳遞參數接收方法:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <!-- static_url使用靜態資源文件 -->
    <link rel="stylesheet" type="text/css" href="{{ static_url('css/index.css') }}">
</head>
<body>
<h1>namejr</h1>
<p>name :{{ dict1['name'] }}, age:{{ dict1['age'] }}</p>
</body>
</html>

 

除了上述案例中的將每個debug/static_path/template_path單獨添加到tornado.web.Application()中之外,還可以使用**setting

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.options import options
from tornado.web import RequestHandler
import os

tornado.options.define('port', type=int, default=8000, help="服務器端口")
current_path = os.path.dirname(__file__)
setting = dict(debug=True, template_path=os.path.join(current_path, 'templates'), static_path=os.path.join(current_path, 'static'))

class IndexHandler(RequestHandler):
    def get(self):
        self.render('new.html')

if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application([
        (r'/', IndexHandler),
    ], **setting)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

 

關於靜態文件使用if..else..等語句

{% if %}...{% elif %}..{% else %}...{% end %}

{% for %} {% end %}

即使用{%%}方式執行python語句,使用{{ num }} 接收靜態參數

 

如何修改render()不進行轉義?

下面有這幾種方法:

第一種:關閉整個網站的模板轉義

在tornado.web.Application()添加參數autoescape=None

app = tornado.web.Application([
        (r'/', IndexHandler),
    ], debug=True, template_path=os.path.join(current_path, 'templates'), autoescape=None)

注:在谷歌瀏覽器會自動攔截,可在控制台查看攔截原因

第二種:關閉單個頁面轉義,{% autoescape None %}

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form method="post">
    <textarea name='text'></textarea>
    <input type="submit" value="sub">
</form>
{% autoescape None %}
{{ texts }}
</body>
</html>

第三種:單條語句轉義,{% raw texts %}

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form method="post">
    <textarea name='text'></textarea>
    <input type="submit" value="sub">
</form>
{% raw texts %}
</body>
</html>

第四種:關閉全局轉義后想在單個頁面進行不轉義,{{ escape(texts) }}

 

關於自定義處理函數

# index.py
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.options import options
from tornado.web import RequestHandler
import os

tornado.options.define('port', type=int, default=8000, help="服務器端口")
current_path = os.path.dirname(__file__)

# 構建處理函數
def deal_dict(names):
    return ''.join(names)

class IndexHandler(RequestHandler):
    def get(self):
        # 構建數據
        dict1 = [
            {
                'name': ['n', 'a', 'm', 'e', 'j', 'r'],
                'age': 21
            },
            {
                'name': ['n', 'a', 'm', 'e', 'm', 'm'],
                'age': 22
            },
            {
                'name': ['n', 'a', 'm', 'e', 'm', 'b'],
                'age': 23
            },
            {
                'name': ['n', 'a', 'm', 'e', 'a', 'b'],
                'age': 24
            }
        ]
        self.render('index.html', texts=dict1, func_deal_dict=deal_dict)

if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application([
        (r'/', IndexHandler),
    ], debug=True, template_path=os.path.join(current_path, 'templates'))
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()
index.html:
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <table border="1">
        <!-- 進行解析數據 -->
        {% for text in texts %}
            <tr>
                <!-- 使用函數處理 -->
                <td>{{ func_deal_dict(text['name']) }}</td>
                <td>{{ text['age'] }}</td>
            </tr>
        {% end %}
    </table>
</body>
</html>

 

 父子模板的使用:

# 父模板(index.html)

<!DOCTYPE html>
<html>
<head>
    <title>父模板</title>
</head>
<body>
<header>
    <p>這是請求頭</p>
    {% block header %}{% end %}
</header>
<center>
    <p>這是請求內容</p>
    {% block content %}{% end %}
</center>
</body>
</html>

# 子模板,使用extends繼承父模板,用block來填充父模板挖的坑

{% extends 'index.html' %}
{% block header %}
    <span>標題</span>
{% end %}
{% block content %}
    <span>內容</span>
{% end %}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM