Tornado框架配置使用Jinja2模板引擎

安装jinja2包

pip install jinja2

定义继承tornado.web.RequestHandler的子类BaseHandler。如果请求处理类继承这个类将会使用jinja模板引擎;如果请求处理类继承tornado.web.RequestHandler,则会使用Tornado框架的模板引擎。

 import os

 from jinja2 import Environment, FileSystemLoader, TemplateNotFound
from tornado.web import RequestHandler, Application
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop class TemplateRendering(object):
"""
A simple class to hold methods for rendering templates.
"""
def render_html_file(self, template_name, **kwargs):
template_dirs = []
if self.settings.get('template_path', ''):
template_dirs.append(self.settings['template_path'])
env = Environment(loader=FileSystemLoader(template_dirs))
try:
template = env.get_template(template_name)
except TemplateNotFound:
raise TemplateNotFound(template_name)
content = template.render(kwargs)
return content class BaseHandler(RequestHandler, TemplateRendering): def initialize(self):
pass def get_current_user(self):
user = self.get_secure_cookie("user")
return user or None def render_template(self, template_name, **kwargs):
kwargs.update({
"settings": self.settings,
"STATIC_URL": self.settings.get("static_url_prefix", "/static/"),
"request": self.request,
"current_user": self.current_user,
"xsrf_token": self.xsrf_token,
"xsrf_form_html": self.xsrf_form_html
})
content = self.render_html_file(template_name, **kwargs)
self.finish(content) class NewHandler(BaseHandler): def get(self, *args, **kwargs):
self.render_template("new.html", text="") def post(self, *args, **kwargs):
text = self.get_argument("text", "")
print(text)
self.set_header("X-XSS-Protection", 0)
self.render_template("new.html", text=text) class OldHandler(RequestHandler): def get(self, *args, **kwargs):
self.render("old.html", text="") def post(self, *args, **kwargs):
text = self.get_argument("text", "")
print(text)
self.set_header("X-XSS-Protection", 0)
self.render("old.html", text=text) if __name__ == '__main__':
current_path = os.path.dirname(__file__)
app = Application([
(r"/new", NewHandler),
(r"/old", OldHandler)
],
cookie_secret="HelloWorld",
static_path=os.path.join(current_path, "static"),
template_path=os.path.join(current_path, "templates")
)
http_server = HTTPServer(app)
http_server.bind(8080)
http_server.start()
IOLoop.current().start()

HTML代码如下

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>escape</title>
</head>
<body>
<form method="post">
<textarea name="text" id="js" cols="30" rows="10"></textarea>
<input type="submit" value="提交">
</form>
{{ text|escape}} <!-- 开启转义 -->
{{ text }} <!-- 关闭转义,js代码将会执行 -->
</body>
</html>

new.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>escape</title>
</head>
<body>
<form method="post">
<textarea name="text" id="js" cols="30" rows="10"></textarea>
<input type="submit" value="提交">
</form>
{{ text }} <!-- Tornado模板自动开启转义 -->
{% raw text %} <!-- 使用模板语法{% raw *text* %}, JS代码将执行 -->
</body>
</html>

old.html

注意:在Firefox浏览器中会直接弹出alert窗口,而在Chrome浏览器中,需要set_header("X-XSS-Protection", 0)

Tornado还有两种方法关闭自动转义:

  1. 在Application构造函数中传递autoescape=None参数;
  2. 在每页模板中修改自动转义行为,添加语句:{% autoescape None %}
上一篇:C++ 调用 opencv 读取视频文件列表并处理


下一篇:Django框架(六)--模板层:变量、过滤器、标签、自定义标签和过滤器