[python] 웹 서버에 게시판 기능 추가하기
이 블로그에서는 Python으로 작성된 웹 서버에 게시판 기능을 추가하는 방법을 알려드리고자 합니다. 게시판은 사용자들이 글을 작성하고 읽을 수 있는 웹 애플리케이션의 핵심 기능 중 하나입니다.
목차
게시판 데이터베이스 설계
게시판을 구현하기 위해 먼저 데이터베이스를 설계해야 합니다. 게시글과 댓글을 저장하기 위한 테이블을 생성하고, 각 테이블 간의 관계를 설정해야 합니다.
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts (id)
);
게시글 작성 기능 구현
웹 애플리케이션에서는 사용자가 게시글을 작성할 수 있어야 합니다. 이를 위해 필요한 기능은 다음과 같습니다.
- 게시글 작성 폼을 사용자에게 제공한다.
- 사용자가 게시글 작성 폼을 제출하면, 입력된 정보를 데이터베이스에 저장한다.
from flask import Flask, request, render_template
import sqlite3
app = Flask(__name__)
@app.route('/write', methods=['GET', 'POST'])
def write_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
conn = sqlite3.connect('board.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO posts (title, content) VALUES (?, ?)', (title, content))
conn.commit()
conn.close()
return '게시글이 작성되었습니다.'
return render_template('write.html')
if __name__ == '__main__':
app.run()
게시글 목록 조회 기능 구현
이제 작성된 게시글을 목록으로 조회할 수 있는 기능을 구현해보겠습니다.
@app.route('/')
def view_posts():
conn = sqlite3.connect('board.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM posts ORDER BY created_at DESC')
posts = cursor.fetchall()
conn.close()
return render_template('view_posts.html', posts=posts)
게시글 상세 보기 기능 구현
게시글 목록에서 특정 게시글을 클릭하면 상세 내용을 볼 수 있어야 합니다.
@app.route('/post/<int:post_id>')
def view_post(post_id):
conn = sqlite3.connect('board.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM posts WHERE id = ?', (post_id,))
post = cursor.fetchone()
cursor.execute('SELECT * FROM comments WHERE post_id = ? ORDER BY created_at', (post_id))
comments = cursor.fetchall()
conn.close()
return render_template('view_post.html', post=post, comments=comments)
댓글 작성 기능 구현
게시글 상세 보기 페이지에서 댓글을 작성할 수 있도록 기능을 추가합니다.
@app.route('/post/<int:post_id>/comment', methods=['POST'])
def add_comment(post_id):
content = request.form['content']
conn = sqlite3.connect('board.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO comments (post_id, content) VALUES (?, ?)', (post_id, content))
conn.commit()
conn.close()
return redirect(url_for('view_post', post_id=post_id))
위의 예시 코드를 참고하여 Python으로 웹 서버에 게시판 기능을 추가할 수 있습니다. 이를 통해 사용자들은 게시글을 작성하고, 조회하며, 댓글을 작성할 수 있는 기능을 사용할 수 있게 됩니다.