Flask

Chapter 3-5 Flask-SQLAlchemy 게시판 관리 라우트 구축 (routes/board.py)

Chansman 2025. 4. 21. 10:24

📌 개념 정리

3-5. 게시판 관리 라우트 구축

💻 전체 코드 예시 (routes/board.py)

from flask import request, jsonify
from flask.views import MethodView
from flask_smorest import Blueprint
from db import db
from models import Board

board_blp = Blueprint('Boards', 'boards', description='Operations on boards', url_prefix='/board')

@board_blp.route('/')
class BoardList(MethodView):
    def get(self):
        boards = Board.query.all()
        return jsonify([{"user_id": board.user_id, 
                         "id": board.id,
                         "title": board.title, "content": board.content, "author": board.author.name} for board in boards])

    def post(self):
        data = request.json
        new_board = Board(title=data['title'], content=data['content'], user_id=data['user_id'])
        db.session.add(new_board)
        db.session.commit()
        return jsonify({"message": "Board created"}), 201

@board_blp.route('/<int:board_id>')
class BoardResource(MethodView):
    def get(self, board_id):
        board = Board.query.get_or_404(board_id)
        return jsonify({"title": board.title, "content": board.content, "author": board.author.name})

    def put(self, board_id):
        board = Board.query.get_or_404(board_id)
        data = request.json
        board.title = data['title']
        board.content = data['content']
        db.session.commit()
        return jsonify({"message": "Board updated"})

    def delete(self, board_id):
        board = Board.query.get_or_404(board_id)
        db.session.delete(board)
        db.session.commit()
        return jsonify({"message": "Board deleted"})

🚦 단계별 프로세스 흐름 및 설명

📍 Step 1: Blueprint 설정

board_blp = Blueprint('Boards', 'boards', description='Operations on boards', url_prefix='/board')
  • 게시판 관련 라우트를 관리하기 위해 Blueprint를 설정하고 URL 접두사를 /board로 지정합니다.

📍 Step 2: 게시판 전체 목록 조회 및 게시글 추가

GET 요청 (전체 게시글 조회)

@board_blp.route('/')
class BoardList(MethodView):
    def get(self):
        boards = Board.query.all()
        return jsonify([{"user_id": board.user_id, 
                         "id": board.id,
                         "title": board.title, "content": board.content, "author": board.author.name} for board in boards])
  • 모든 게시글을 조회하여 JSON 형태로 반환합니다.

POST 요청 (새 게시글 추가)

    def post(self):
        data = request.json
        new_board = Board(title=data['title'], content=data['content'], user_id=data['user_id'])
        db.session.add(new_board)
        db.session.commit()
        return jsonify({"message": "Board created"}), 201
  • 게시글 정보를 받아 데이터베이스에 추가하고 새 게시글 생성 메시지를 반환합니다.

📍 Step 3: 특정 게시글 조회, 수정, 삭제

GET 요청 (특정 게시글 조회)

@board_blp.route('/<int:board_id>')
class BoardResource(MethodView):
    def get(self, board_id):
        board = Board.query.get_or_404(board_id)
        return jsonify({"title": board.title, "content": board.content, "author": board.author.name})
  • 특정 게시글의 상세 정보를 조회하여 반환합니다.

PUT 요청 (게시글 수정)

    def put(self, board_id):
        board = Board.query.get_or_404(board_id)
        data = request.json
        board.title = data['title']
        board.content = data['content']
        db.session.commit()
        return jsonify({"message": "Board updated"})
  • 특정 게시글의 제목과 내용을 수정하여 변경사항을 저장합니다.

DELETE 요청 (게시글 삭제)

    def delete(self, board_id):
        board = Board.query.get_or_404(board_id)
        db.session.delete(board)
        db.session.commit()
        return jsonify({"message": "Board deleted"})
  • 특정 게시글을 데이터베이스에서 삭제합니다.

마무리 요약 및 복습 포인트

  • 게시판 관리 기능을 위한 RESTful API를 구축하여 게시글 조회, 추가, 수정, 삭제를 효율적으로 수행합니다.
  • Flask와 SQLAlchemy의 간편한 데이터 처리 방식을 활용하여 명확하고 간결한 코드 구조를 유지합니다.