쇼핑몰 재고 관리 시스템을 프론트엔드(React) + 백엔드(Python Flask) + API로 구현하는 전체 코드를 단계별로 설명해 보자.
1. 시스템 아키텍처
[React 프론트엔드] ← HTTP → [Flask 백엔드 API] ←→ [메모리 DB]
2. 백엔드 (Python Flask)
(1) 설치
pip install flask flask-cors
(2) server.py
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # CORS 허용 (프론트-백엔드 통신)
# 임시 데이터베이스 (메모리 저장)
inventory = {
"A": { "id": "A", "name": "상품 A", "price": 10000, "stock": 10 },
"B": { "id": "B", "name": "상품 B", "price": 20000, "stock": 5 }
}
# 재고 조회 API
@app.route('/api/inventory', methods=['GET'])
def get_inventory():
return jsonify(list(inventory.values()))
# 주문 처리 API
@app.route('/api/orders', methods=['POST'])
def create_order():
try:
data = request.get_json()
product_id = data['productId']
quantity = data['quantity']
if product_id not in inventory:
return jsonify({ "success": False, "error": "상품 없음" }), 404
if inventory[product_id]['stock'] < quantity:
return jsonify({ "success": False, "error": "재고 부족" }), 400
# 재고 차감
inventory[product_id]['stock'] -= quantity
return jsonify({
"success": True,
"message": f"{inventory[product_id]['name']} {quantity}개 구매 성공"
})
except Exception as e:
return jsonify({ "success": False, "error": str(e) }), 500
if __name__ == '__main__':
app.run(debug=True, port=5000)
3. 프론트엔드 (React)
(1) 설치
npx create-react-app frontend
cd frontend
npm install axios
(2) src/ProductList.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function ProductList() {
const [products, setProducts] = useState([]);
// 재고 데이터 불러오기
useEffect(() => {
axios.get('http://localhost:5000/api/inventory')
.then(response => setProducts(response.data))
.catch(error => console.error("재고 불러오기 실패:", error));
}, []);
return (
<div>
<h2>상품 목록</h2>
<ul>
{products.map(product => (
<li key={product.id}>
{product.name} - {product.price}원 (재고: {product.stock}개)
</li>
))}
</ul>
</div>
);
}
export default ProductList;
(3) src/OrderForm.js
import React, { useState } from 'react';
import axios from 'axios';
function OrderForm() {
const [productId, setProductId] = useState('A');
const [quantity, setQuantity] = useState(1);
const [message, setMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('http://localhost:5000/api/orders', {
productId: productId,
quantity: parseInt(quantity)
});
setMessage(response.data.message);
} catch (error) {
setMessage(error.response?.data.error || "주문 실패");
}
};
return (
<div>
<h2>주문하기</h2>
<form onSubmit={handleSubmit}>
<label>
상품 선택:
<select value={productId} onChange={(e) => setProductId(e.target.value)}>
<option value="A">상품 A</option>
<option value="B">상품 B</option>
</select>
</label>
<label>
수량:
<input
type="number"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
min="1"
/>
</label>
<button type="submit">구매</button>
</form>
{message && <p>{message}</p>}
</div>
);
}
export default OrderForm;
(4) src/App.js
import React from 'react';
import ProductList from './ProductList';
import OrderForm from './OrderForm';
function App() {
return (
<div>
<h1>쇼핑몰 재고 관리 시스템</h1>
<ProductList />
<OrderForm />
</div>
);
}
export default App;
4. 실행 방법
- 백엔드 실행:
python server.py # http://localhost:5000 에서 API 서버 실행
- 프론트엔드 실행:
cd frontend npm start # http://localhost:3000 에서 React 앱 실행
5. 주요 기능 시연
- 초기 화면
- 상품 A 3개 주문
- 재고: 10 → 7개
- 메시지: "상품 A 3개 구매 성공"
- 재고 부족 시
- 상품 B 6개 주문 → "재고 부족" 오류
6. 코드 설명
코드 부분 | 설명 |
---|---|
Flask CORS | 프론트-백엔드 도메인 다를 때 차단 방지 |
/api/inventory |
모든 상품 재고 데이터 반환 |
/api/orders |
주문 처리 및 재고 업데이트 |
React useEffect |
컴포넌트 마운트 시 재고 데이터 패치 |
Axios | HTTP 클라이언트 라이브러리 (fetch 대체) |
try-catch |
API 호출 에러 처리 |
7. 확장 가능한 기능
- 실제 데이터베이스 연동 (MySQL, MongoDB)
- JWT 인증 추가
- 관리자 페이지 구현
- 주문 이력 저장 기능
- 실시간 재고 업데이트 (WebSocket)
이 코드를 기반으로 필요에 따라 기능을 추가해보세요! 🚀
'Programming' 카테고리의 다른 글
Flask : Python으로 웹서버를 만들기 위한 마이크로 프레임워크 (0) | 2025.02.18 |
---|---|
풀스택 프레임워크 Vs 마이크로 프레임워크 비교 (1) | 2025.02.17 |
쇼핑몰 관리자 페이지에 쓰이는 코드 모음 (0) | 2025.02.16 |
API(Application Programming Interface)의 원리 (0) | 2025.02.14 |