提神個醒腦!
靜態和模板文件的配置
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(<、
>
)字符。
輸出不被轉義的原始格式的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) }}