[python] 웹 서버에 댓글 기능 추가하기
개요
이번 튜토리얼에서는 Python을 이용하여 웹 서버에 댓글 기능을 추가하는 방법을 알아보겠습니다. 웹 애플리케이션의 사용자들이 게시물에 댓글을 작성하고 조회할 수 있는 기본적인 기능을 구현할 것입니다.
필요한 도구
- Python 3.x
- Flask 웹 프레임워크
Flask 설치하기
먼저 Flask를 설치해야 합니다. 터미널 또는 명령 프롬프트를 열고 다음 명령을 실행하세요.
pip install flask
프로젝트 설정
다음으로, 프로젝트 디렉토리를 만들고 필요한 파일을 생성해야 합니다.
mkdir myproject
cd myproject
touch app.py templates/index.html templates/post.html static/style.css
app.py
: Flask 애플리케이션의 핵심 로직을 담을 파일입니다.templates/index.html
: 홈 페이지 템플릿 파일입니다.templates/post.html
: 게시물 상세 페이지 템플릿 파일입니다.static/style.css
: 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)
/
경로에 접속하면index.html
템플릿을 렌더링하고,comments
리스트를 템플릿에 전달합니다./post
경로로 POST 요청을 보내면, 댓글을 가져와comments
리스트에 추가한 후post.html
템플릿을 렌더링합니다.
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>
<form>
요소에서action
속성을/post
로 설정하고,method
속성을post
로 설정하여 폼 데이터를/post
경로에 POST 요청으로 보내도록 합니다.comments
리스트의 각 요소를 순회하며 댓글을 표시합니다.
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는 높은 수준의 유연성과 확장성을 제공하여 웹 개발을 더 쉽고 효율적으로 할 수 있게 해줍니다.