Python中如何使用Tornado搭建服务并快速用前端框架展示JSON接口数据?
null
Python中如何使用Tornado搭建服务并快速用前端框架展示JSON接口数据?
10 回复
渲染模板,填充到前端
核心思路:用Tornado搭建JSON API,前端用任意框架(这里以原生Fetch为例)调用并展示数据。
1. 后端Tornado服务(server.py):
import tornado.ioloop
import tornado.web
import json
class MainHandler(tornado.web.RequestHandler):
def get(self):
# 模拟JSON数据
data = {
"status": "success",
"users": [
{"id": 1, "name": "张三", "role": "开发"},
{"id": 2, "name": "李四", "role": "测试"}
]
}
self.set_header("Content-Type", "application/json")
self.write(json.dumps(data, ensure_ascii=False))
def make_app():
return tornado.web.Application([
(r"/api/data", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
print("Tornado服务已启动:http://localhost:8888/api/data")
tornado.ioloop.IOLoop.current().start()
2. 前端展示页面(index.html):
<!DOCTYPE html>
<html>
<head>
<title>Tornado数据展示</title>
<style>
table { border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 8px; }
</style>
</head>
<body>
<h2>用户数据展示</h2>
<button onclick="loadData()">加载数据</button>
<div id="result"></div>
<script>
async function loadData() {
try {
const response = await fetch('http://localhost:8888/api/data');
const result = await response.json();
if (result.status === 'success') {
let table = `<table>
<tr><th>ID</th><th>姓名</th><th>角色</th></tr>`;
result.users.forEach(user => {
table += `<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.role}</td>
</tr>`;
});
table += '</table>';
document.getElementById('result').innerHTML = table;
}
} catch (error) {
document.getElementById('result').innerHTML =
`<p style="color:red">请求失败:${error}</p>`;
}
}
</script>
</body>
</html>
操作步骤:
- 运行
python server.py启动Tornado服务 - 直接用浏览器打开
index.html(或通过本地HTTP服务) - 点击按钮即可获取并展示JSON数据
前端框架适配提示:
- 如果是Vue/React,只需将fetch逻辑放入组件生命周期,用响应式变量存储数据即可
- 注意跨域问题:正式部署时需配置CORS或同域部署
一句话总结:Tornado写接口,前端用Fetch调用,数据驱动视图渲染。
tornado 返回 json 数据,直接 self.write(dict),会自动添加 Content-Type:application/json
如果返回 json 方法转换后的数据,Content-Type:text/html
没注意看,如果是前后端分离的话,vue 渲染数据比较简单
我也是准备用 vue ! thanks
简单展示直接 jquery+bootstrap tabel 就好了
既然是简单显示,没有必要上 vue,一个 bootstrap、模块渲染就够了
感觉现在 vue 比 jq 还简单 jq 都不会写了
再弄个 echart 就可以装逼了
Vue,最适合学过三剑客的后端的前端框架

