欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 在 Flask 或 Tornado 中返回渲染后的页面内容

在 Flask 或 Tornado 中返回渲染后的页面内容

2025/6/18 10:49:47 来源:https://blog.csdn.net/u014158430/article/details/148619235  浏览:    关键词:在 Flask 或 Tornado 中返回渲染后的页面内容

在 Flask 或 Tornado 中返回渲染后的页面内容,主要涉及模板渲染和异步处理。以下是两种框架的实现方法:


1. Flask 方案(同步)

Flask 使用 Jinja2 模板引擎渲染页面:

from flask import Flask, render_templateapp = Flask(__name__)@app.route('/')
def index():# 渲染 templates/index.html,传递变量return render_template('index.html', title='首页', message='欢迎!')if __name__ == '__main__':app.run(port=5000)

文件结构

project/
├── app.py
└── templates/└── index.html  <-- 模板文件

模板示例 (templates/index.html):

<!DOCTYPE html>
<html>
<head><title>{{ title }}</title>
</head>
<body><h1>{{ message }}</h1>
</body>
</html>

2. Tornado 方案(异步)

Tornado 内置异步支持和模板引擎:

import tornado.ioloop
import tornado.webclass MainHandler(tornado.web.RequestHandler):async def get(self):# 模拟异步操作(如数据库查询)data = await self.fetch_data()# 渲染模板并传递数据self.render("index.html", title="首页", items=data)async def fetch_data(self):# 示例异步函数(实际替换为数据库调用等)return ["项目1", "项目2", "项目3"]def make_app():return tornado.web.Application(handlers=[(r"/", MainHandler)],template_path="templates"  # 模板目录)if __name__ == "__main__":app = make_app()app.listen(8888)tornado.ioloop.IOLoop.current().start()

模板示例 (templates/index.html):

<!DOCTYPE html>
<html>
<head><title>{{ title }}</title>
</head>
<body><h1>列表内容:</h1><ul>{% for item in items %}<li>{{ item }}</li>{% end %}</ul>
</body>
</html>

关键点说明:

特性FlaskTornado
渲染方法render_template('模板名', 变量)self.render('模板名', 变量)
模板目录默认 ./templates需手动指定 template_path
异步支持需扩展(如 Quart)原生支持异步 async/await
适用场景传统同步应用高并发、长连接(WebSocket)

常见问题解决:

  1. 模板路径错误

    • 确保模板文件在 templates 目录内
    • Tornado 需在 Application 中指定 template_path="templates"
  2. 变量未渲染

    • 检查模板中的变量名 {{ var }} 是否和 Python 代码中传递的名称一致
  3. Tornado 异步操作

    • 使用 async def get() 定义异步处理器
    • 在 I/O 操作前加 await(如数据库查询)

根据需求选择框架:

  • 简单 CRUD 应用 → Flask 更快捷
  • 高并发/实时应用 → Tornado 更合适

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词