后端(Python Flask)0512px.cn
首先,我们使用 Flask 框架来创建一个简单的 Web API。
安装 Flask:
bash
pip install Flask
app.py (Flask 后端代码):
python
from flask import Flask, jsonify, request
app = Flask(name)
假设的游戏商品列表
games = [
{“id”: 1, “name”: “Cyberpunk 2077”, “price”: 59.99},
{“id”: 2, “name”: “The Witcher 3”, “price”: 39.99},
{“id”: 3, “name”: “Minecraft”, “price”: 26.95}
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
game = next((item for item in games if item[“id”] == game_id), None)
if game:
return jsonify(game)
else:
return jsonify({“error”: “Game not found”}), 404
if name == ‘main’:
app.run(debug=True)
前端(HTML/JavaScript)
前端部分我们将使用 HTML 来创建页面结构,并用 JavaScript(通过 Fetch API)来调用后端 API。
index.html:
html
Game Store
Load Games<script>
async function fetchGames() {
const response = await fetch('http://localhost:5000/games');
const data = await response.json();
const list = document.getElementById('gamesList');
list.innerHTML = ''; // 清空现有列表
data.forEach(game => {
const item = document.createElement('li');
item.textContent = `Name: ${game.name}, Price:
$$
{game.price}`;
list.appendChild(item);
});
}
后端(Python Flask)
首先,我们使用 Flask 框架来创建一个简单的 Web API。
安装 Flask:
bash
pip install Flask
app.py (Flask 后端代码):
python
from flask import Flask, jsonify, request
app = Flask(name)
假设的游戏商品列表
games = [
{“id”: 1, “name”: “Cyberpunk 2077”, “price”: 59.99},
{“id”: 2, “name”: “The Witcher 3”, “price”: 39.99},
{“id”: 3, “name”: “Minecraft”, “price”: 26.95}
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
game = next((item for item in games if item[“id”] == game_id), None)
if game:
return jsonify(game)
else:
return jsonify({“error”: “Game not found”}), 404
if name == ‘main’:
app.run(debug=True)
前端(HTML/JavaScript)
前端部分我们将使用 HTML 来创建页面结构,并用 JavaScript(通过 Fetch API)来调用后端 API。
index.html:
html
Game Store
Load Games<script>
async function fetchGames() {
const response = await fetch('http://localhost:5000/games');
const data = await response.json();
const list = document.getElementById('gamesList');
list.innerHTML = ''; // 清空现有列表
data.forEach(game => {
const item = document.createElement('li');
item.textContent = `Name: ${game.name}, Price:
$$
{game.price}`;
list.appendChild(item);
});
}