[python] 웹 서버에 댓글 기능 추가하기

개요

이번 튜토리얼에서는 Python을 이용하여 웹 서버에 댓글 기능을 추가하는 방법을 알아보겠습니다. 웹 애플리케이션의 사용자들이 게시물에 댓글을 작성하고 조회할 수 있는 기본적인 기능을 구현할 것입니다.

필요한 도구

Flask 설치하기

먼저 Flask를 설치해야 합니다. 터미널 또는 명령 프롬프트를 열고 다음 명령을 실행하세요.

pip install flask

프로젝트 설정

다음으로, 프로젝트 디렉토리를 만들고 필요한 파일을 생성해야 합니다.

mkdir myproject
cd myproject
touch app.py templates/index.html templates/post.html static/style.css

app.py 작성하기

아래와 같이 app.py 파일을 작성하세요.

from flask import Flask, render_template, request

app = Flask(__name__)

# 댓글을 저장할 리스트
comments = []

@app.route('/')
def index():
    return render_template('index.html', comments=comments)

@app.route('/post', methods=['GET', 'POST'])
def post():
    if request.method == 'POST':
        comment = request.form.get('comment')
        comments.append(comment)
    return render_template('post.html', comments=comments)

templates/index.html 작성하기

아래와 같이 index.html 파일을 작성하세요.


<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>댓글 기능 추가하기</h1>

    <form action="/post" method="post">
        <textarea name="comment" placeholder="댓글을 입력하세요."></textarea>
        <button type="submit">작성</button>
    </form>

    <h2>댓글 목록</h2>
    <ul>
        {% for comment in comments %}
            <li>{{ comment }}</li>
        {% endfor %}
    </ul>
</body>
</html>

templates/post.html 작성하기

아래와 같이 post.html 파일을 작성하세요.


<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>댓글이 등록되었습니다!</h1>

    <a href="/">돌아가기</a>

    <h2>댓글 목록</h2>
    <ul>
        {% for comment in comments %}
            <li>{{ comment }}</li>
        {% endfor %}
    </ul>
</body>
</html>

실행하기

터미널 또는 명령 프롬프트에서 다음 명령을 실행하여 웹 서버를 실행하세요.

python app.py

웹 브라우저에서 http://localhost:5000에 접속하여 댓글 기능이 추가된 웹 애플리케이션을 확인할 수 있습니다.

결론

이 튜토리얼에서는 Flask를 사용하여 간단한 웹 서버에 댓글 기능을 추가하는 방법을 알아보았습니다. 이를 바탕으로 더 다양한 기능을 추가해 나갈 수 있습니다. Flask는 높은 수준의 유연성과 확장성을 제공하여 웹 개발을 더 쉽고 효율적으로 할 수 있게 해줍니다.

참고 자료