1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
| from flask import Flask, request, jsonify, render_template_string
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
import redis
import json
app = Flask(__name__)
# 데이터베이스 설정
engine = create_engine('sqlite:///complete_blog.db')
Base = declarative_base()
Session = sessionmaker(bind=engine)
# Redis 설정 (선택사항)
try:
redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
redis_client.ping() # 연결 테스트
USE_REDIS = True
except:
USE_REDIS = False
print("Redis 연결 실패 - 캐시 기능 비활성화")
# 모델 정의
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(80), unique=True, nullable=False)
email = Column(String(120), unique=True, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
posts = relationship("Post", back_populates="author")
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
content = Column(Text)
created_at = Column(DateTime, default=datetime.utcnow)
user_id = Column(Integer, ForeignKey('users.id'))
author = relationship("User", back_populates="posts")
Base.metadata.create_all(engine)
class BlogAPI:
def __init__(self):
self.session = Session()
def create_user(self, username, email):
user = User(username=username, email=email)
self.session.add(user)
self.session.commit()
return user
def get_user(self, user_id):
# 캐시 확인
if USE_REDIS:
cached_user = redis_client.get(f"user:{user_id}")
if cached_user:
return json.loads(cached_user)
# 데이터베이스에서 조회
user = self.session.query(User).get(user_id)
if user:
user_data = {
'id': user.id,
'username': user.username,
'email': user.email,
'created_at': user.created_at.isoformat()
}
# 캐시에 저장 (5분)
if USE_REDIS:
redis_client.setex(f"user:{user_id}", 300, json.dumps(user_data))
return user_data
return None
def create_post(self, user_id, title, content):
post = Post(user_id=user_id, title=title, content=content)
self.session.add(post)
self.session.commit()
# 캐시 무효화
if USE_REDIS:
redis_client.delete(f"user_posts:{user_id}")
redis_client.delete("recent_posts")
return post
def get_posts(self, user_id=None, limit=10):
if user_id:
cache_key = f"user_posts:{user_id}"
else:
cache_key = "recent_posts"
# 캐시 확인
if USE_REDIS:
cached_posts = redis_client.get(cache_key)
if cached_posts:
return json.loads(cached_posts)
# 데이터베이스에서 조회
query = self.session.query(Post)
if user_id:
query = query.filter(Post.user_id == user_id)
posts = query.order_by(Post.created_at.desc()).limit(limit).all()
posts_data = [{
'id': post.id,
'title': post.title,
'content': post.content,
'created_at': post.created_at.isoformat(),
'author': post.author.username
} for post in posts]
# 캐시에 저장 (2분)
if USE_REDIS:
redis_client.setex(cache_key, 120, json.dumps(posts_data))
return posts_data
blog_api = BlogAPI()
# REST API 엔드포인트
@app.route('/api/users', methods=['POST'])
def create_user():
data = request.json
try:
user = blog_api.create_user(data['username'], data['email'])
return jsonify({'id': user.id, 'username': user.username})
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/api/users/<int:user_id>')
def get_user(user_id):
user = blog_api.get_user(user_id)
if user:
return jsonify(user)
return jsonify({'error': 'User not found'}), 404
@app.route('/api/posts', methods=['POST'])
def create_post():
data = request.json
try:
post = blog_api.create_post(data['user_id'], data['title'], data['content'])
return jsonify({'id': post.id, 'title': post.title})
except Exception as e:
return jsonify({'error': str(e)}), 400
@app.route('/api/posts')
def get_posts():
user_id = request.args.get('user_id', type=int)
limit = request.args.get('limit', 10, type=int)
posts = blog_api.get_posts(user_id, limit)
return jsonify(posts)
# 웹 인터페이스
@app.route('/')
def index():
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<title>블로그 시스템</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
.post { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
.form-group { margin: 10px 0; }
input, textarea { width: 100%; padding: 8px; box-sizing: border-box; }
button { background: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; border-radius: 3px; }
button:hover { background: #0056b3; }
.error { color: red; margin: 10px 0; }
.success { color: green; margin: 10px 0; }
</style>
</head>
<body>
<h1>블로그 시스템</h1>
<div id="messages"></div>
<h2>사용자 생성</h2>
<div class="form-group">
<input type="text" id="username" placeholder="사용자명">
</div>
<div class="form-group">
<input type="email" id="email" placeholder="이메일">
</div>
<button onclick="createUser()">사용자 생성</button>
<h2>게시글 작성</h2>
<div class="form-group">
<input type="number" id="user_id" placeholder="사용자 ID">
</div>
<div class="form-group">
<input type="text" id="title" placeholder="제목">
</div>
<div class="form-group">
<textarea id="content" placeholder="내용" rows="4"></textarea>
</div>
<button onclick="createPost()">게시글 작성</button>
<h2>최근 게시글</h2>
<button onclick="loadPosts()">새로고침</button>
<div id="posts"></div>
<script>
function showMessage(message, isError = false) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = isError ? 'error' : 'success';
messageDiv.textContent = message;
messagesDiv.appendChild(messageDiv);
setTimeout(() => messageDiv.remove(), 3000);
}
async function createUser() {
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username: document.getElementById('username').value,
email: document.getElementById('email').value
})
});
if (response.ok) {
const result = await response.json();
showMessage('사용자 생성됨: ID ' + result.id);
document.getElementById('username').value = '';
document.getElementById('email').value = '';
} else {
const error = await response.json();
showMessage('오류: ' + error.error, true);
}
} catch (e) {
showMessage('네트워크 오류: ' + e.message, true);
}
}
async function createPost() {
try {
const response = await fetch('/api/posts', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
user_id: parseInt(document.getElementById('user_id').value),
title: document.getElementById('title').value,
content: document.getElementById('content').value
})
});
if (response.ok) {
const result = await response.json();
showMessage('게시글 작성됨: ' + result.title);
document.getElementById('title').value = '';
document.getElementById('content').value = '';
loadPosts();
} else {
const error = await response.json();
showMessage('오류: ' + error.error, true);
}
} catch (e) {
showMessage('네트워크 오류: ' + e.message, true);
}
}
async function loadPosts() {
try {
const response = await fetch('/api/posts');
const posts = await response.json();
const postsDiv = document.getElementById('posts');
if (posts.length === 0) {
postsDiv.innerHTML = '<p>게시글이 없습니다.</p>';
return;
}
postsDiv.innerHTML = posts.map(post => `
<div class="post">
<h3>${post.title}</h3>
<p>${post.content}</p>
<small>작성자: ${post.author} | 작성일: ${new Date(post.created_at).toLocaleString()}</small>
</div>
`).join('');
} catch (e) {
showMessage('게시글 로드 오류: ' + e.message, true);
}
}
// 페이지 로드 시 게시글 로드
loadPosts();
</script>
</body>
</html>
''')
if __name__ == '__main__':
print("블로그 시스템 시작")
print("Redis 캐시:", "사용" if USE_REDIS else "미사용")
app.run(debug=True)
|