포슀트

[Python 100일 μ±Œλ¦°μ§€] Day 90 - 🎯 λ―Έλ‹ˆ ν”„λ‘œμ νŠΈ: λΈ”λ‘œκ·Έ μ›Ήμ‚¬μ΄νŠΈ

[Python 100일 μ±Œλ¦°μ§€] Day 90 - 🎯 λ―Έλ‹ˆ ν”„λ‘œμ νŠΈ: λΈ”λ‘œκ·Έ μ›Ήμ‚¬μ΄νŠΈ

πŸŽ‰ Phase 9의 λ§ˆμ§€λ§‰ λ‚ μž…λ‹ˆλ‹€!

μ§€λ‚œ 10일간 Flask둜 μ›Ή 개발의 핡심을 λͺ¨λ‘ λ°°μ› μŠ΅λ‹ˆλ‹€:

  • Day 81: Flask μ‹œμž‘ν•˜κΈ°
  • Day 82: λΌμš°νŒ…κ³Ό URL 처리
  • Day 83: ν…œν”Œλ¦Ώ μ—”μ§„ (Jinja2)
  • Day 84: 폼 처리
  • Day 85: λ°μ΄ν„°λ² μ΄μŠ€ 연동
  • Day 86: CRUD μ• ν”Œλ¦¬μΌ€μ΄μ…˜
  • Day 87: REST API
  • Day 88: μ‚¬μš©μž 인증
  • Day 89: 배포 μ€€λΉ„

μ˜€λŠ˜μ€ 이 λͺ¨λ“  것을 ν•˜λ‚˜λ‘œ ν•©μΉ©λ‹ˆλ‹€!

μ™„μ „ν•œ κΈ°λŠ₯을 κ°€μ§„ λΈ”λ‘œκ·Έ μ›Ήμ‚¬μ΄νŠΈλ₯Ό λ§Œλ“€μ–΄λ΄…μ‹œλ‹€: βœ… νšŒμ›κ°€μž…/둜그인 βœ… κΈ€ μž‘μ„±/μˆ˜μ •/μ‚­μ œ βœ… λŒ“κΈ€ μ‹œμŠ€ν…œ βœ… 검색 κΈ°λŠ₯ βœ… REST API βœ… κ΄€λ¦¬μž κΈ°λŠ₯

μ‹€μ „μ—μ„œ λ°”λ‘œ μ‚¬μš©ν•  수 μžˆλŠ” 완성도 높은 ν”„λ‘œμ νŠΈμž…λ‹ˆλ‹€! πŸ’ͺ

(60λΆ„ 완독 ⭐⭐⭐⭐⭐)

🎯 ν”„λ‘œμ νŠΈ κ°œμš”

κΈ°λŠ₯ λͺ…μ„Έ

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
# πŸ‘€ μ‚¬μš©μž κΈ°λŠ₯
- νšŒμ›κ°€μž… (이메일 인증 μ œμ™Έ)
- 둜그인/λ‘œκ·Έμ•„μ›ƒ
- ν”„λ‘œν•„ μˆ˜μ •
- λΉ„λ°€λ²ˆν˜Έ λ³€κ²½

# πŸ“ λΈ”λ‘œκ·Έ 포슀트
- κΈ€ μž‘μ„± (제λͺ©, λ‚΄μš©, μΉ΄ν…Œκ³ λ¦¬)
- κΈ€ μˆ˜μ • (μž‘μ„±μžλ§Œ)
- κΈ€ μ‚­μ œ (μž‘μ„±μž/κ΄€λ¦¬μžλ§Œ)
- κΈ€ λͺ©λ‘ (νŽ˜μ΄μ§€λ„€μ΄μ…˜)
- κΈ€ 상세 보기

# πŸ’¬ λŒ“κΈ€
- λŒ“κΈ€ μž‘μ„± (둜그인 ν•„μš”)
- λŒ“κΈ€ μ‚­μ œ (μž‘μ„±μž/κ΄€λ¦¬μžλ§Œ)

# πŸ” 검색
- 제λͺ©/λ‚΄μš©μœΌλ‘œ 검색
- μΉ΄ν…Œκ³ λ¦¬λ³„ 필터링

# πŸ”§ κ΄€λ¦¬μž
- λͺ¨λ“  κΈ€/λŒ“κΈ€ 관리
- μ‚¬μš©μž 관리

# 🌐 REST API
- GET /api/posts - 전체 κΈ€
- GET /api/posts/<id> - νŠΉμ • κΈ€
- POST /api/posts - κΈ€ μž‘μ„± (인증 ν•„μš”)

ν”„λ‘œμ νŠΈ ꡬ쑰

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
blog-website/
β”œβ”€β”€ app.py                  # 메인 μ• ν”Œλ¦¬μΌ€μ΄μ…˜
β”œβ”€β”€ config.py               # μ„€μ • 파일
β”œβ”€β”€ init_db.py              # DB μ΄ˆκΈ°ν™”
β”œβ”€β”€ models.py               # 데이터 λͺ¨λΈ (선택)
β”œβ”€β”€ requirements.txt        # νŒ¨ν‚€μ§€ λͺ©λ‘
β”œβ”€β”€ .env                    # ν™˜κ²½ λ³€μˆ˜
β”œβ”€β”€ database.db             # SQLite DB
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ base.html           # 베이슀 ν…œν”Œλ¦Ώ
β”‚   β”œβ”€β”€ index.html          # 메인 νŽ˜μ΄μ§€
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”œβ”€β”€ register.html
β”‚   β”‚   └── login.html
β”‚   β”œβ”€β”€ posts/
β”‚   β”‚   β”œβ”€β”€ list.html
β”‚   β”‚   β”œβ”€β”€ detail.html
β”‚   β”‚   β”œβ”€β”€ create.html
β”‚   β”‚   └── edit.html
β”‚   └── user/
β”‚       └── profile.html
└── static/
    β”œβ”€β”€ css/
    β”‚   └── style.css
    └── js/
        └── main.js

πŸ“¦ 1단계: ν”„λ‘œμ νŠΈ 초기 μ„€μ •

1. 가상 ν™˜κ²½ 생성

1
2
3
4
5
6
7
8
9
10
11
12
# ν”„λ‘œμ νŠΈ 폴더 생성
mkdir blog-website
cd blog-website

# 가상 ν™˜κ²½ 생성
python -m venv venv

# ν™œμ„±ν™”
# Windows
venv\Scripts\activate
# Mac/Linux
source venv/bin/activate

2. νŒ¨ν‚€μ§€ μ„€μΉ˜

1
pip install flask python-dotenv bcrypt

requirements.txt:

1
2
3
Flask==3.0.0
python-dotenv==1.0.0
bcrypt==4.1.1

3. ν™˜κ²½ λ³€μˆ˜ μ„€μ •

.env:

1
2
3
SECRET_KEY=your-secret-key-change-this-in-production
DATABASE_URI=sqlite:///database.db
DEBUG=True

4. λ°μ΄ν„°λ² μ΄μŠ€ μŠ€ν‚€λ§ˆ

init_db.py:

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
import sqlite3
import bcrypt

DATABASE = 'database.db'

def hash_password(password):
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

def init_database():
    """λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™” 및 ν…Œμ΄λΈ” 생성"""
    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()

    # κΈ°μ‘΄ ν…Œμ΄λΈ” μ‚­μ œ (개발용)
    cursor.execute('DROP TABLE IF EXISTS comments')
    cursor.execute('DROP TABLE IF EXISTS posts')
    cursor.execute('DROP TABLE IF EXISTS users')

    # μ‚¬μš©μž ν…Œμ΄λΈ”
    cursor.execute('''
        CREATE TABLE users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            email TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL,
            role TEXT DEFAULT 'user',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')

    # 포슀트 ν…Œμ΄λΈ”
    cursor.execute('''
        CREATE TABLE posts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL,
            category TEXT,
            author_id INTEGER NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (author_id) REFERENCES users(id)
        )
    ''')

    # λŒ“κΈ€ ν…Œμ΄λΈ”
    cursor.execute('''
        CREATE TABLE comments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            post_id INTEGER NOT NULL,
            author_id INTEGER NOT NULL,
            content TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (post_id) REFERENCES posts(id),
            FOREIGN KEY (author_id) REFERENCES users(id)
        )
    ''')

    # κ΄€λ¦¬μž 계정 생성
    admin_password = hash_password('admin123')
    cursor.execute('''
        INSERT INTO users (username, email, password_hash, role)
        VALUES (?, ?, ?, ?)
    ''', ('admin', 'admin@blog.com', admin_password, 'admin'))

    # μƒ˜ν”Œ μ‚¬μš©μž
    user_password = hash_password('user123')
    cursor.execute('''
        INSERT INTO users (username, email, password_hash)
        VALUES (?, ?, ?)
    ''', ('홍길동', 'hong@example.com', user_password))

    # μƒ˜ν”Œ 포슀트
    cursor.execute('''
        INSERT INTO posts (title, content, category, author_id)
        VALUES (?, ?, ?, ?)
    ''', ('Flask λΈ”λ‘œκ·Έ μ‹œμž‘ν•˜κΈ°', 'Flask둜 λΈ”λ‘œκ·Έλ₯Ό λ§Œλ“€μ–΄λ΄…μ‹œλ‹€!', '기술', 1))

    cursor.execute('''
        INSERT INTO posts (title, content, category, author_id)
        VALUES (?, ?, ?, ?)
    ''', ('Python 100일 μ±Œλ¦°μ§€', '100μΌκ°„μ˜ Python ν•™μŠ΅ μ—¬μ •', '일상', 2))

    # μƒ˜ν”Œ λŒ“κΈ€
    cursor.execute('''
        INSERT INTO comments (post_id, author_id, content)
        VALUES (?, ?, ?)
    ''', (1, 2, '쒋은 κΈ€ κ°μ‚¬ν•©λ‹ˆλ‹€!'))

    conn.commit()
    conn.close()

    print("βœ… λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™” μ™„λ£Œ!")
    print("πŸ“ κ΄€λ¦¬μž: admin / admin123")
    print("πŸ‘€ μ‚¬μš©μž: 홍길동 / user123")

if __name__ == '__main__':
    init_database()

μ‹€ν–‰:

1
python init_db.py

πŸ”§ 2단계: 핡심 κΈ°λŠ₯ κ΅¬ν˜„

app.py (메인 μ• ν”Œλ¦¬μΌ€μ΄μ…˜)

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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
import sqlite3
import bcrypt
from datetime import datetime
from functools import wraps
import os
from dotenv import load_dotenv

# ν™˜κ²½ λ³€μˆ˜ λ‘œλ“œ
load_dotenv()

app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'dev-secret-key')

DATABASE = 'database.db'

# ========== λ°μ΄ν„°λ² μ΄μŠ€ 헬퍼 ==========
def get_db():
    db = sqlite3.connect(DATABASE)
    db.row_factory = sqlite3.Row
    return db

def hash_password(password):
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

def check_password(password, hashed):
    return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))

# ========== λ°μ½”λ ˆμ΄ν„° ==========
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('둜그인이 ν•„μš”ν•©λ‹ˆλ‹€', 'error')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('둜그인이 ν•„μš”ν•©λ‹ˆλ‹€', 'error')
            return redirect(url_for('login'))

        db = get_db()
        cursor = db.cursor()
        cursor.execute('SELECT role FROM users WHERE id = ?', (session['user_id'],))
        user = cursor.fetchone()
        db.close()

        if not user or user['role'] != 'admin':
            flash('κ΄€λ¦¬μžλ§Œ μ ‘κ·Όν•  수 μžˆμŠ΅λ‹ˆλ‹€', 'error')
            return redirect(url_for('index'))

        return f(*args, **kwargs)
    return decorated_function

# ========== 메인 νŽ˜μ΄μ§€ ==========
@app.route('/')
def index():
    db = get_db()
    cursor = db.cursor()

    # 졜근 포슀트
    cursor.execute('''
        SELECT posts.*, users.username
        FROM posts
        JOIN users ON posts.author_id = users.id
        ORDER BY posts.created_at DESC
        LIMIT 5
    ''')
    recent_posts = cursor.fetchall()

    # 톡계
    cursor.execute('SELECT COUNT(*) as count FROM posts')
    total_posts = cursor.fetchone()['count']

    cursor.execute('SELECT COUNT(*) as count FROM users')
    total_users = cursor.fetchone()['count']

    db.close()

    return render_template('index.html',
                           recent_posts=recent_posts,
                           total_posts=total_posts,
                           total_users=total_users)

# ========== 인증 ==========
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username', '').strip()
        email = request.form.get('email', '').strip()
        password = request.form.get('password')
        password_confirm = request.form.get('password_confirm')

        # 검증
        if not username or not email or not password:
            flash('λͺ¨λ“  ν•„λ“œλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”', 'error')
            return redirect(url_for('register'))

        if password != password_confirm:
            flash('λΉ„λ°€λ²ˆν˜Έκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€', 'error')
            return redirect(url_for('register'))

        # λΉ„λ°€λ²ˆν˜Έ ν•΄μ‹±
        password_hash = hash_password(password)

        db = get_db()
        cursor = db.cursor()

        try:
            cursor.execute('''
                INSERT INTO users (username, email, password_hash)
                VALUES (?, ?, ?)
            ''', (username, email, password_hash))
            db.commit()

            flash('νšŒμ›κ°€μž… 성곡! λ‘œκ·ΈμΈν•΄μ£Όμ„Έμš”', 'success')
            return redirect(url_for('login'))

        except sqlite3.IntegrityError:
            flash('이미 μ‘΄μž¬ν•˜λŠ” 아이디 λ˜λŠ” μ΄λ©”μΌμž…λ‹ˆλ‹€', 'error')

        finally:
            db.close()

    return render_template('auth/register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        db = get_db()
        cursor = db.cursor()
        cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
        user = cursor.fetchone()
        db.close()

        if user and check_password(password, user['password_hash']):
            session['user_id'] = user['id']
            session['username'] = user['username']
            session['role'] = user['role']

            flash(f'ν™˜μ˜ν•©λ‹ˆλ‹€, {username}λ‹˜!', 'success')
            return redirect(url_for('index'))
        else:
            flash('아이디 λ˜λŠ” λΉ„λ°€λ²ˆν˜Έκ°€ ν‹€λ ΈμŠ΅λ‹ˆλ‹€', 'error')

    return render_template('auth/login.html')

@app.route('/logout')
def logout():
    session.clear()
    flash('λ‘œκ·Έμ•„μ›ƒ λ˜μ—ˆμŠ΅λ‹ˆλ‹€', 'success')
    return redirect(url_for('index'))

# ========== 포슀트 ==========
@app.route('/posts')
def posts_list():
    db = get_db()
    cursor = db.cursor()

    # 검색/ν•„ν„°
    search = request.args.get('search', '')
    category = request.args.get('category', '')

    query = '''
        SELECT posts.*, users.username
        FROM posts
        JOIN users ON posts.author_id = users.id
        WHERE 1=1
    '''
    params = []

    if search:
        query += ' AND (posts.title LIKE ? OR posts.content LIKE ?)'
        params.extend([f'%{search}%', f'%{search}%'])

    if category:
        query += ' AND posts.category = ?'
        params.append(category)

    query += ' ORDER BY posts.created_at DESC'

    cursor.execute(query, params)
    posts = cursor.fetchall()
    db.close()

    return render_template('posts/list.html', posts=posts, search=search, category=category)

@app.route('/posts/<int:post_id>')
def post_detail(post_id):
    db = get_db()
    cursor = db.cursor()

    # 포슀트 쑰회
    cursor.execute('''
        SELECT posts.*, users.username
        FROM posts
        JOIN users ON posts.author_id = users.id
        WHERE posts.id = ?
    ''', (post_id,))
    post = cursor.fetchone()

    if not post:
        db.close()
        flash('포슀트λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('posts_list'))

    # λŒ“κΈ€ 쑰회
    cursor.execute('''
        SELECT comments.*, users.username
        FROM comments
        JOIN users ON comments.author_id = users.id
        WHERE comments.post_id = ?
        ORDER BY comments.created_at DESC
    ''', (post_id,))
    comments = cursor.fetchall()

    db.close()

    return render_template('posts/detail.html', post=post, comments=comments)

@app.route('/posts/create', methods=['GET', 'POST'])
@login_required
def create_post():
    if request.method == 'POST':
        title = request.form.get('title', '').strip()
        content = request.form.get('content', '').strip()
        category = request.form.get('category', '').strip()

        if not title or not content:
            flash('제λͺ©κ³Ό λ‚΄μš©μ„ μž…λ ₯ν•΄μ£Όμ„Έμš”', 'error')
            return redirect(url_for('create_post'))

        db = get_db()
        cursor = db.cursor()
        cursor.execute('''
            INSERT INTO posts (title, content, category, author_id)
            VALUES (?, ?, ?, ?)
        ''', (title, content, category, session['user_id']))
        db.commit()
        post_id = cursor.lastrowid
        db.close()

        flash('ν¬μŠ€νŠΈκ°€ μž‘μ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€', 'success')
        return redirect(url_for('post_detail', post_id=post_id))

    return render_template('posts/create.html')

@app.route('/posts/<int:post_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_post(post_id):
    db = get_db()
    cursor = db.cursor()

    # κΆŒν•œ 확인
    cursor.execute('SELECT * FROM posts WHERE id = ?', (post_id,))
    post = cursor.fetchone()

    if not post:
        db.close()
        flash('포슀트λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('posts_list'))

    if post['author_id'] != session['user_id'] and session.get('role') != 'admin':
        db.close()
        flash('μˆ˜μ • κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('post_detail', post_id=post_id))

    if request.method == 'POST':
        title = request.form.get('title', '').strip()
        content = request.form.get('content', '').strip()
        category = request.form.get('category', '').strip()

        cursor.execute('''
            UPDATE posts
            SET title = ?, content = ?, category = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ''', (title, content, category, post_id))
        db.commit()
        db.close()

        flash('ν¬μŠ€νŠΈκ°€ μˆ˜μ •λ˜μ—ˆμŠ΅λ‹ˆλ‹€', 'success')
        return redirect(url_for('post_detail', post_id=post_id))

    db.close()
    return render_template('posts/edit.html', post=post)

@app.route('/posts/<int:post_id>/delete', methods=['POST'])
@login_required
def delete_post(post_id):
    db = get_db()
    cursor = db.cursor()

    cursor.execute('SELECT * FROM posts WHERE id = ?', (post_id,))
    post = cursor.fetchone()

    if not post:
        db.close()
        flash('포슀트λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('posts_list'))

    if post['author_id'] != session['user_id'] and session.get('role') != 'admin':
        db.close()
        flash('μ‚­μ œ κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('post_detail', post_id=post_id))

    # λŒ“κΈ€λ„ ν•¨κ»˜ μ‚­μ œ
    cursor.execute('DELETE FROM comments WHERE post_id = ?', (post_id,))
    cursor.execute('DELETE FROM posts WHERE id = ?', (post_id,))
    db.commit()
    db.close()

    flash('ν¬μŠ€νŠΈκ°€ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€', 'success')
    return redirect(url_for('posts_list'))

# ========== λŒ“κΈ€ ==========
@app.route('/posts/<int:post_id>/comments', methods=['POST'])
@login_required
def add_comment(post_id):
    content = request.form.get('content', '').strip()

    if not content:
        flash('λŒ“κΈ€ λ‚΄μš©μ„ μž…λ ₯ν•΄μ£Όμ„Έμš”', 'error')
        return redirect(url_for('post_detail', post_id=post_id))

    db = get_db()
    cursor = db.cursor()
    cursor.execute('''
        INSERT INTO comments (post_id, author_id, content)
        VALUES (?, ?, ?)
    ''', (post_id, session['user_id'], content))
    db.commit()
    db.close()

    flash('λŒ“κΈ€μ΄ μž‘μ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€', 'success')
    return redirect(url_for('post_detail', post_id=post_id))

@app.route('/comments/<int:comment_id>/delete', methods=['POST'])
@login_required
def delete_comment(comment_id):
    db = get_db()
    cursor = db.cursor()

    cursor.execute('SELECT * FROM comments WHERE id = ?', (comment_id,))
    comment = cursor.fetchone()

    if not comment:
        db.close()
        flash('λŒ“κΈ€μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('index'))

    if comment['author_id'] != session['user_id'] and session.get('role') != 'admin':
        db.close()
        flash('μ‚­μ œ κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€', 'error')
        return redirect(url_for('post_detail', post_id=comment['post_id']))

    post_id = comment['post_id']
    cursor.execute('DELETE FROM comments WHERE id = ?', (comment_id,))
    db.commit()
    db.close()

    flash('λŒ“κΈ€μ΄ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€', 'success')
    return redirect(url_for('post_detail', post_id=post_id))

# ========== REST API ==========
@app.route('/api/posts', methods=['GET'])
def api_get_posts():
    db = get_db()
    cursor = db.cursor()
    cursor.execute('''
        SELECT posts.*, users.username
        FROM posts
        JOIN users ON posts.author_id = users.id
        ORDER BY posts.created_at DESC
    ''')
    posts = cursor.fetchall()
    db.close()

    return jsonify({
        'count': len(posts),
        'posts': [dict(post) for post in posts]
    })

@app.route('/api/posts/<int:post_id>', methods=['GET'])
def api_get_post(post_id):
    db = get_db()
    cursor = db.cursor()
    cursor.execute('''
        SELECT posts.*, users.username
        FROM posts
        JOIN users ON posts.author_id = users.id
        WHERE posts.id = ?
    ''', (post_id,))
    post = cursor.fetchone()
    db.close()

    if not post:
        return jsonify({'error': 'Post not found'}), 404

    return jsonify(dict(post))

# ========== μ—λŸ¬ ν•Έλ“€λŸ¬ ==========
@app.errorhandler(404)
def not_found(error):
    return render_template('errors/404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    return render_template('errors/500.html'), 500

if __name__ == '__main__':
    app.run(debug=True)

🎨 3단계: ν…œν”Œλ¦Ώ μž‘μ„±

templates/base.html (베이슀 ν…œν”Œλ¦Ώ)

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
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}λΈ”λ‘œκ·Έ{% endblock %}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background: #f8f9fa; }
        .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }

        /* 헀더 */
        header { background: #2c3e50; color: white; padding: 1rem 0; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        header .container { display: flex; justify-content: space-between; align-items: center; }
        header h1 { font-size: 1.5rem; }
        header h1 a { color: white; text-decoration: none; }
        header nav a { color: white; margin-left: 1.5rem; text-decoration: none; transition: opacity 0.3s; }
        header nav a:hover { opacity: 0.8; }

        /* 메인 */
        main { padding: 2rem 0; min-height: calc(100vh - 200px); }

        /* ν”Œλž˜μ‹œ λ©”μ‹œμ§€ */
        .flash-messages { margin: 1rem 0; }
        .flash { padding: 1rem; margin-bottom: 1rem; border-radius: 5px; }
        .flash-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .flash-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }

        /* μΉ΄λ“œ */
        .card { background: white; border-radius: 10px; padding: 2rem; margin-bottom: 2rem; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }

        /* λ²„νŠΌ */
        .btn { display: inline-block; padding: 0.75rem 1.5rem; border-radius: 5px; text-decoration: none; border: none; cursor: pointer; font-size: 1rem; transition: all 0.3s; }
        .btn-primary { background: #007bff; color: white; }
        .btn-primary:hover { background: #0056b3; }
        .btn-success { background: #28a745; color: white; }
        .btn-success:hover { background: #218838; }
        .btn-danger { background: #dc3545; color: white; }
        .btn-danger:hover { background: #c82333; }
        .btn-secondary { background: #6c757d; color: white; }
        .btn-secondary:hover { background: #5a6268; }

        /* 폼 */
        .form-group { margin-bottom: 1.5rem; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: bold; }
        .form-group input, .form-group textarea, .form-group select { width: 100%; padding: 0.75rem; border: 1px solid #ddd; border-radius: 5px; font-size: 1rem; }
        .form-group textarea { resize: vertical; min-height: 150px; }

        /* ν‘Έν„° */
        footer { background: #2c3e50; color: white; text-align: center; padding: 2rem 0; margin-top: 3rem; }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1><a href="{{ url_for('index') }}">πŸ“ My Blog</a></h1>
            <nav>
                <a href="{{ url_for('index') }}">ν™ˆ</a>
                <a href="{{ url_for('posts_list') }}">κΈ€ λͺ©λ‘</a>
                {% if session.user_id %}
                    <a href="{{ url_for('create_post') }}">κΈ€ μ“°κΈ°</a>
                    <a href="{{ url_for('logout') }}">λ‘œκ·Έμ•„μ›ƒ ({{ session.username }})</a>
                {% else %}
                    <a href="{{ url_for('login') }}">둜그인</a>
                    <a href="{{ url_for('register') }}">νšŒμ›κ°€μž…</a>
                {% endif %}
            </nav>
        </div>
    </header>

    <main>
        <div class="container">
            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    <div class="flash-messages">
                        {% for category, message in messages %}
                            <div class="flash flash-{{ category }}">{{ message }}</div>
                        {% endfor %}
                    </div>
                {% endif %}
            {% endwith %}

            {% block content %}{% endblock %}
        </div>
    </main>

    <footer>
        <div class="container">
            <p>&copy; 2025 My Blog. Made with Flask ❀️</p>
            <p><a href="/api/posts" style="color: white;">API λ¬Έμ„œ</a></p>
        </div>
    </footer>
</body>
</html>

templates/index.html (메인 νŽ˜μ΄μ§€)

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
{% extends "base.html" %}

{% block content %}
<div class="card" style="text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
    <h1 style="font-size: 2.5rem; margin-bottom: 1rem;">✨ ν™˜μ˜ν•©λ‹ˆλ‹€!</h1>
    <p style="font-size: 1.2rem;">Flask둜 λ§Œλ“  λΈ”λ‘œκ·Έμ— μ˜€μ‹  것을 ν™˜μ˜ν•©λ‹ˆλ‹€</p>

    <div style="display: flex; gap: 2rem; justify-content: center; margin-top: 2rem;">
        <div>
            <h2 style="font-size: 2rem;">{{ total_posts }}</h2>
            <p>총 포슀트</p>
        </div>
        <div>
            <h2 style="font-size: 2rem;">{{ total_users }}</h2>
            <p>총 μ‚¬μš©μž</p>
        </div>
    </div>
</div>

<h2 style="margin-bottom: 1.5rem;">πŸ“Œ 졜근 포슀트</h2>

{% for post in recent_posts %}
    <div class="card">
        <h3 style="margin-bottom: 0.5rem;">
            <a href="{{ url_for('post_detail', post_id=post['id']) }}" style="color: #333; text-decoration: none;">
                {{ post['title'] }}
            </a>
        </h3>
        <p style="color: #666; font-size: 0.9rem; margin-bottom: 1rem;">
            {{ post['username'] }} Β· {{ post['created_at'] }}
            {% if post['category'] %}
                · 🏷️ {{ post['category'] }}
            {% endif %}
        </p>
        <p style="color: #555;">{{ post['content'][:200] }}{% if post['content']|length > 200 %}...{% endif %}</p>
        <a href="{{ url_for('post_detail', post_id=post['id']) }}" class="btn btn-primary" style="margin-top: 1rem;">읽기 β†’</a>
    </div>
{% else %}
    <div class="card" style="text-align: center; color: #999;">
        <p>아직 ν¬μŠ€νŠΈκ°€ μ—†μŠ΅λ‹ˆλ‹€. 첫 번째 글을 μž‘μ„±ν•΄λ³΄μ„Έμš”!</p>
        {% if session.user_id %}
            <a href="{{ url_for('create_post') }}" class="btn btn-primary" style="margin-top: 1rem;">κΈ€ μ“°κΈ°</a>
        {% endif %}
    </div>
{% endfor %}
{% endblock %}

templates/posts/list.html (포슀트 λͺ©λ‘)

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
{% extends "base.html" %}

{% block title %}κΈ€ λͺ©λ‘ - λΈ”λ‘œκ·Έ{% endblock %}

{% block content %}
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>πŸ“š 전체 포슀트 ({{ posts|length }}개)</h2>
    {% if session.user_id %}
        <a href="{{ url_for('create_post') }}" class="btn btn-primary">✏️ μƒˆ κΈ€ μ“°κΈ°</a>
    {% endif %}
</div>

<!-- 검색 폼 -->
<div class="card">
    <form method="GET" style="display: flex; gap: 1rem;">
        <input type="text" name="search" placeholder="제λͺ© λ˜λŠ” λ‚΄μš© 검색" value="{{ search }}" style="flex: 2; padding: 0.75rem; border: 1px solid #ddd; border-radius: 5px;">
        <select name="category" style="flex: 1; padding: 0.75rem; border: 1px solid #ddd; border-radius: 5px;">
            <option value="">λͺ¨λ“  μΉ΄ν…Œκ³ λ¦¬</option>
            <option value="기술" {% if category == '기술' %}selected{% endif %}>기술</option>
            <option value="일상" {% if category == '일상' %}selected{% endif %}>일상</option>
            <option value="리뷰" {% if category == '리뷰' %}selected{% endif %}>리뷰</option>
        </select>
        <button type="submit" class="btn btn-primary">πŸ” 검색</button>
    </form>
</div>

<!-- 포슀트 λͺ©λ‘ -->
{% for post in posts %}
    <div class="card">
        <h3 style="margin-bottom: 0.5rem;">
            <a href="{{ url_for('post_detail', post_id=post['id']) }}" style="color: #333; text-decoration: none;">
                {{ post['title'] }}
            </a>
        </h3>
        <p style="color: #666; font-size: 0.9rem; margin-bottom: 1rem;">
            πŸ‘€ {{ post['username'] }} Β· πŸ“… {{ post['created_at'] }}
            {% if post['category'] %}· 🏷️ {{ post['category'] }}{% endif %}
        </p>
        <p style="color: #555;">{{ post['content'][:300] }}{% if post['content']|length > 300 %}...{% endif %}</p>
        <a href="{{ url_for('post_detail', post_id=post['id']) }}" class="btn btn-primary" style="margin-top: 1rem;">μžμ„Ένžˆ 보기 β†’</a>
    </div>
{% else %}
    <div class="card" style="text-align: center; color: #999;">
        <h3>검색 κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€</h3>
        <p>λ‹€λ₯Έ ν‚€μ›Œλ“œλ‘œ κ²€μƒ‰ν•΄λ³΄μ„Έμš”</p>
    </div>
{% endfor %}
{% endblock %}

templates/posts/detail.html (포슀트 상세)

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
{% extends "base.html" %}

{% block title %}{{ post['title'] }} - λΈ”λ‘œκ·Έ{% endblock %}

{% block content %}
<div class="card">
    <h1 style="margin-bottom: 1rem;">{{ post['title'] }}</h1>
    <p style="color: #666; margin-bottom: 2rem;">
        πŸ‘€ {{ post['username'] }} Β· πŸ“… {{ post['created_at'] }}
        {% if post['category'] %}· 🏷️ {{ post['category'] }}{% endif %}
    </p>

    <div style="line-height: 1.8; white-space: pre-wrap;">{{ post['content'] }}</div>

    {% if session.user_id and (session.user_id == post['author_id'] or session.role == 'admin') %}
        <div style="margin-top: 2rem; padding-top: 2rem; border-top: 1px solid #ddd; display: flex; gap: 1rem;">
            <a href="{{ url_for('edit_post', post_id=post['id']) }}" class="btn btn-secondary">✏️ μˆ˜μ •</a>
            <form method="POST" action="{{ url_for('delete_post', post_id=post['id']) }}" style="display: inline;">
                <button type="submit" class="btn btn-danger" onclick="return confirm('정말 μ‚­μ œν•˜μ‹œκ² μŠ΅λ‹ˆκΉŒ?')">πŸ—‘οΈ μ‚­μ œ</button>
            </form>
        </div>
    {% endif %}
</div>

<!-- λŒ“κΈ€ μ„Ήμ…˜ -->
<div class="card">
    <h2 style="margin-bottom: 1.5rem;">πŸ’¬ λŒ“κΈ€ ({{ comments|length }}개)</h2>

    {% if session.user_id %}
        <form method="POST" action="{{ url_for('add_comment', post_id=post['id']) }}" style="margin-bottom: 2rem;">
            <div class="form-group">
                <textarea name="content" placeholder="λŒ“κΈ€μ„ μž…λ ₯ν•˜μ„Έμš”" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">λŒ“κΈ€ μž‘μ„±</button>
        </form>
    {% else %}
        <p style="text-align: center; color: #999; padding: 2rem; background: #f8f9fa; border-radius: 5px;">
            λŒ“κΈ€μ„ μž‘μ„±ν•˜λ €λ©΄ <a href="{{ url_for('login') }}">둜그인</a>ν•΄μ£Όμ„Έμš”
        </p>
    {% endif %}

    {% for comment in comments %}
        <div style="border-left: 3px solid #007bff; padding-left: 1rem; margin-bottom: 1.5rem;">
            <p style="font-weight: bold; margin-bottom: 0.5rem;">
                {{ comment['username'] }}
                <span style="font-weight: normal; color: #666; font-size: 0.9rem;">Β· {{ comment['created_at'] }}</span>
            </p>
            <p style="white-space: pre-wrap;">{{ comment['content'] }}</p>
            {% if session.user_id and (session.user_id == comment['author_id'] or session.role == 'admin') %}
                <form method="POST" action="{{ url_for('delete_comment', comment_id=comment['id']) }}" style="margin-top: 0.5rem;">
                    <button type="submit" class="btn btn-danger" style="font-size: 0.9rem; padding: 0.4rem 1rem;" onclick="return confirm('λŒ“κΈ€μ„ μ‚­μ œν•˜μ‹œκ² μŠ΅λ‹ˆκΉŒ?')">μ‚­μ œ</button>
                </form>
            {% endif %}
        </div>
    {% else %}
        <p style="text-align: center; color: #999;">아직 λŒ“κΈ€μ΄ μ—†μŠ΅λ‹ˆλ‹€</p>
    {% endfor %}
</div>

<a href="{{ url_for('posts_list') }}" class="btn btn-secondary">← λͺ©λ‘μœΌλ‘œ</a>
{% endblock %}

πŸŽ‰ μ™„μ„±!

μ‹€ν–‰ν•˜κΈ°

1
2
3
4
5
6
7
8
# λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™”
python init_db.py

# μ„œλ²„ μ‹€ν–‰
python app.py

# λΈŒλΌμš°μ €μ—μ„œ 접속
# http://localhost:5000

ν…ŒμŠ€νŠΈ 계정

1
2
3
4
5
6
7
κ΄€λ¦¬μž:
- 아이디: admin
- λΉ„λ°€λ²ˆν˜Έ: admin123

일반 μ‚¬μš©μž:
- 아이디: 홍길동
- λΉ„λ°€λ²ˆν˜Έ: user123

πŸ“ 마무리

Phase 9μ—μ„œ 배운 것듀

1
2
3
4
5
6
7
8
9
10
βœ… Day 81: Flask 기초
βœ… Day 82: λΌμš°νŒ…
βœ… Day 83: ν…œν”Œλ¦Ώ
βœ… Day 84: 폼 처리
βœ… Day 85: λ°μ΄ν„°λ² μ΄μŠ€
βœ… Day 86: CRUD
βœ… Day 87: REST API
βœ… Day 88: μ‚¬μš©μž 인증
βœ… Day 89: 배포 μ€€λΉ„
βœ… Day 90: μ’…ν•© ν”„λ‘œμ νŠΈ

λ‹€μŒ 단계

1
2
3
4
5
6
7
8
9
10
11
12
# ν”„λ‘œμ νŠΈ κ°œμ„  아이디어:

1. 파일 μ—…λ‘œλ“œ (이미지 첨뢀)
2. νŽ˜μ΄μ§€λ„€μ΄μ…˜ (ν•œ νŽ˜μ΄μ§€μ— 10κ°œμ”©)
3. μ’‹μ•„μš” κΈ°λŠ₯
4. νƒœκ·Έ μ‹œμŠ€ν…œ
5. 이메일 인증
6. μ†Œμ…œ 둜그인 (Google, GitHub)
7. λ§ˆν¬λ‹€μš΄ 지원
8. 검색 고도화
9. μ•Œλ¦Ό μ‹œμŠ€ν…œ
10. μ‹€μ‹œκ°„ μ±„νŒ…

πŸ† μΆ•ν•˜ν•©λ‹ˆλ‹€!

Phase 9: μ›Ή 개발 μž…λ¬Έμ„ μ™„λ£Œν–ˆμŠ΅λ‹ˆλ‹€!

10일 λ™μ•ˆ Flask둜 μ™„μ „ν•œ μ›Ή μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ„ λ§Œλ“œλŠ” 방법을 λ°°μ› μŠ΅λ‹ˆλ‹€. 이제 μ—¬λŸ¬λΆ„μ€ μžμ‹ λ§Œμ˜ μ›Ήμ‚¬μ΄νŠΈλ₯Ό λ§Œλ“€ 수 μžˆμŠ΅λ‹ˆλ‹€!

λ‹€μŒ Phaseμ—μ„œ λ΅™κ² μŠ΅λ‹ˆλ‹€! πŸš€


β€œμ™„μ„±λœ ν”„λ‘œμ νŠΈλŠ” μ‹œμž‘μ˜ 끝이자, μƒˆλ‘œμš΄ μ‹œμž‘μ˜ μ‹œμž‘μž…λ‹ˆλ‹€!” 🎯

Day 90/100 Phase 9: μ›Ή 개발 μž…λ¬Έ μ™„λ£Œ! #100DaysOfPython
이 κΈ°μ‚¬λŠ” μ €μž‘κΆŒμžμ˜ CC BY 4.0 λΌμ΄μ„ΌμŠ€λ₯Ό λ”°λ¦…λ‹ˆλ‹€.

Β© YonYonWare. 일뢀 ꢌ리 보μœ