当前位置: 首页 > news >正文

在 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 更合适
http://www.xdnf.cn/news/1003735.html

相关文章:

  • 爱普生SG5032EEN差分晶体振荡器的特点
  • Element UI 表格el-table宽度不能自适应的问题解决方法
  • 深度学习编译器
  • Docker搭建2FAuth服务
  • 数据结构 (树) 学习 2025年6月12日12:59:39
  • Vue 生命周期
  • 铸铁平台的制造工艺复杂而精细
  • 音视频之H.264/AVC编码器原理
  • 头歌之动手学人工智能-Pytorch 之torch.nn进阶
  • 算法导论第二章:递归与分治的数学艺术
  • 【MV】为什么需要DeepSeek 的分析: AI 替代编舞师
  • Docker 常用命令大全
  • 基于LangChain构建一个RAG多轮对话问答应用
  • LeetCode 868.二进制间距
  • 第三十八课:实战案例-飞鸟和飞机的识别
  • EtherCAT主站转Profinet网关与禾川伺服驱动器X4E快速通讯案例
  • 并行程序设计
  • Nuttx之mm_realloc
  • AtCoder-ABC-409 题解
  • java BIO/NIO/AIO
  • 工具+服务双驱动:创客匠人打造中医IP差异化竞争力
  • 搭建商城系统可能运用到的技术
  • Python告别数据处理卡顿之itertools模块使用详解
  • 立即体验|效果好、低延迟,Trae 已支持 Doubao-1.5-thinking-pro 新模型
  • faiss上的GPU流程,GPU与CPU之间的联系
  • MCP与FunctionCall的区别
  • HALCON第七讲->标定
  • 西电【计算机与网络安全实验】课程期末复习遗留情报
  • git添加全局忽略.DS_Store文件
  • MySQL 和 PostgreSQL,到底选择哪个?