这篇文章将介绍如何使用Python Flask和Echarts制作一个能够展示疫情统计数据的网页。
一、安装依赖库
首先,需要安装Python Flask和Echarts的依赖库。
pip install flask
pip install pyecharts
二、获取数据
我们需要从网络上获取疫情数据,并将其存储在本地文件中。这里以新冠疫情数据为例。
import requests
# 从网络上获取数据
response = requests.get('https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=318423444501')
# 将数据存储到本地文件中
with open('data.json', 'w') as file:
file.write(response.json())
三、使用 Flask 构建 Web 服务器
下面是一份使用 Flask 快速构建 Web 服务器的代码。
from flask import Flask, jsonify
app = Flask(__name__)
# 从文件中读取疫情数据
with open('data.json', 'r') as file:
data = file.read()
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/data')
def data():
return jsonify(data)
这份代码包含了 Flask 的最基本用法,当我们访问http://localhost:5000/时,将看到“Hello, World!”,当访问http://localhost:5000/data时,将返回我们从文件中读取到的疫情数据。
四、使用 Echarts 展示数据
Echarts 可以让我们方便地在 Web 服务器上展示数据。
from flask import Flask, jsonify, render_template
from pyecharts.charts import Line
app = Flask(__name__)
# 从文件中读取疫情数据
with open('data.json', 'r') as file:
data = file.read()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/data')
def data():
return jsonify(data)
@app.route('/chart')
def chart():
# 解析疫情数据
data = json.loads(data)
# 处理数据
date = []
confirmed_count = []
for item in data['data']['list']:
date.append(item['date'])
confirmed_count.append(item['total']['confirm'])
# 使用 Echarts 画图
chart = Line()
chart.add_xaxis(date)
chart.add_yaxis('确诊人数', confirmed_count)
chart.render('chart.html')
# 返回图表
with open('chart.html', 'r') as file:
chart_data = file.read()
return chart_data
这份代码中,我们增加了一个新的路由http://localhost:5000/chart,它展示了疫情的确诊人数随时间的变化趋势。
五、网页布局
最后,我们需要使用 HTML 和 CSS 对网页进行美化。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新冠疫情统计数据</title>
<script src="https://cdn.staticfile.org/echarts/4.7.0/echarts.min.js"></script>
</head>
<body>
<h1>新冠疫情统计数据</h1>
<div id="chart" style="width: 100%; height: 600px"></div>
<script>
fetch('/chart')
.then(response => response.text())
.then(data => {
document.getElementById('chart').innerHTML = data
})
</script>
</body>
</html>
这份代码使用了 Echarts 提供的 JS 库来展示数据,并使用了 Fetch API 从服务器获取数据。
六、总结
通过这篇文章,我们学习了如何使用 Flask 和 Echarts 展示疫情数据,并最终实现了一个简单的疫情数据统计网页。
原创文章,作者:FANPJ,如若转载,请注明出处:https://www.506064.com/n/373531.html