安裝 Flask
pip install Flask
app.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
# 根路由,返回首頁
@app.route('/')
def index():
return render_template('index.html')
# 簡單的 API 路由,返回一些 JSON 數據
@app.route('/api/data', methods=['GET'])
def get_data():
data = {
"message": "Hello, Flask!",
"status": "success"
}
return jsonify(data)
# 接收 POST 請求的路由
@app.route('/api/post', methods=['POST'])
def post_data():
posted_data = request.get_json()
return jsonify({
"received": True,
"data": posted_data
})
if __name__ == '__main__':
app.run(debug=True)
templates/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>第二十一天 - 基本後端應用</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css">
</head>
<body class="bg-gray-100 text-gray-800">
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold mb-4">歡迎使用 Flask 後端應用</h1>
<p>這是你的基本後端應用首頁。</p>
</div>
</body>
</html>