app.py
from flask import Flask, jsonify, render_template
app = Flask(__name__)
# 定義首頁路由,渲染 React 的入口 HTML 文件
@app.route('/')
def index():
return render_template('index.html')
# 定義一個 API 路由,返回 JSON 數據
@app.route('/api/chart-data')
def chart_data():
data = {
"labels": ["January", "February", "March", "April", "May", "June"],
"datasets": [{
"label": "My First dataset",
"backgroundColor": "rgba(255, 99, 132, 0.2)",
"borderColor": "rgba(255, 99, 132, 1)",
"borderWidth": 1,
"data": [65, 59, 80, 81, 56, 55]
}]
}
return jsonify(data)
# 啟動 Flask 應用
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第十九天 - React 與 Flask 整合及數據可視化</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
function App() {
const [chartData, setChartData] = React.useState(null);
React.useEffect(() => {
fetch('/api/chart-data')
.then(response => response.json())
.then(data => setChartData(data));
}, []);
React.useEffect(() => {
if (chartData) {
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
}, [chartData]);
return (
<div>
<h1>第十九天的 React 與 Flask 整合及數據可視化示範</h1>
<canvas id="myChart"></canvas>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>