- 数据库设计(SQL)sidaotech.com
首先,我们需要一个简单的数据库表来存储游戏信息。
sql
CREATE TABLE Games (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
stock INT DEFAULT 10
);
2. 后端(Python,使用 Flask 框架)
接下来,我们将使用 Python 的 Flask 框架来构建后端 API。
安装 Flask:
bash
pip install Flask
Flask 应用代码 (app.py):
python
from flask import Flask, jsonify, request
import sqlite3
app = Flask(name)
连接数据库
conn = sqlite3.connect(‘game_store.db’)
cursor = conn.cursor()
@app.route(‘/games’, methods=[‘GET’])
def get_games():
cursor.execute(“SELECT * FROM Games”)
games = cursor.fetchall()
return jsonify([{‘id’: game[0], ‘title’: game[1], ‘description’: game[2], ‘price’: game[3], ‘stock’: game[4]} for game in games])
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
cursor.execute(“SELECT * FROM Games WHERE id = ?”, (game_id,))
game = cursor.fetchone()
if game:
return jsonify({‘id’: game[0], ‘title’: game[1], ‘description’: game[2], ‘price’: game[3], ‘stock’: game[4]})
else:
return jsonify({‘error’: ‘Game not found’}), 404
if name == ‘main’:
app.run(debug=True)
3. 前端(HTML + JavaScript)
这里我们使用简单的 HTML 和 JavaScript 来调用上面定义的 Flask API。
HTML (index.html):
html
Game Store
Fetch Games<script>
function fetchGames() {
$.getJSON('http://127.0.0.1:5000/games', function(data) {
var html = '<ul>';
data.forEach(function(game) {
html += `<li>${game.title} -
$$
{game.price} (${game.stock} in stock)`;
});
html += ‘’;
$(‘#games’).html(html);
});
}
- 数据库设计(SQL)
首先,我们需要一个简单的数据库表来存储游戏信息。
sql
CREATE TABLE Games (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
stock INT DEFAULT 10
);
2. 后端(Python,使用 Flask 框架)
接下来,我们将使用 Python 的 Flask 框架来构建后端 API。
安装 Flask:
bash
pip install Flask
Flask 应用代码 (app.py):
python
from flask import Flask, jsonify, request
import sqlite3
app = Flask(name)
连接数据库
conn = sqlite3.connect(‘game_store.db’)
cursor = conn.cursor()
@app.route(‘/games’, methods=[‘GET’])
def get_games():
cursor.execute(“SELECT * FROM Games”)
games = cursor.fetchall()
return jsonify([{‘id’: game[0], ‘title’: game[1], ‘description’: game[2], ‘price’: game[3], ‘stock’: game[4]} for game in games])
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
cursor.execute(“SELECT * FROM Games WHERE id = ?”, (game_id,))
game = cursor.fetchone()
if game:
return jsonify({‘id’: game[0], ‘title’: game[1], ‘description’: game[2], ‘price’: game[3], ‘stock’: game[4]})
else:
return jsonify({‘error’: ‘Game not found’}), 404
if name == ‘main’:
app.run(debug=True)
3. 前端(HTML + JavaScript)
这里我们使用简单的 HTML 和 JavaScript 来调用上面定义的 Flask API。
HTML (index.html):
html
Game Store
Fetch Games<script>
function fetchGames() {
$.getJSON('http://127.0.0.1:5000/games', function(data) {
var html = '<ul>';
data.forEach(function(game) {
html += `<li>${game.title} -
$$
{game.price} (${game.stock} in stock)`;
});
html += ‘’;
$(‘#games’).html(html);
});
}