這篇文章將介紹如何使用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/zh-hk/n/373531.html