다음은 간단한 게시판 기능 구현에 대한 Flask 코드 튜토리얼 예제입니다. 이 튜토리얼은 프로젝트 구조 설계, 게시글 작성 기능 구현, 게시판 조회 기능 구현의 순서로 진행됩니다.
먼저 아래와 같이 프로젝트 디렉토리를 구성합니다.
my_flask_app/
├── app.py
├── templates/
│ ├── base.html
│ ├── index.html
│ ├── create_post.html
│ └── post_detail.html
└── static/
└── css/
└── style.css
- app.py: Flask 애플리케이션의 메인 파일
- templates/: HTML 템플릿 파일들을 저장
- base.html: 공통 레이아웃 (헤더, 네비게이션 등)
- index.html: 게시글 목록 페이지
- create_post.html: 게시글 작성 폼 페이지
- post_detail.html: 개별 게시글 상세 페이지
- static/: CSS, JavaScript, 이미지 등 정적 파일을 저장
게시글을 작성할 수 있는 폼을 만들고, 제출된 데이터를 서버에 저장합니다. 여기서는 간단하게 파이썬의 리스트에 게시글을 저장합니다.
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# 임시 게시글 저장용 리스트
posts = []
post_id = 1
@app.route('/')
def index():
return render_template('index.html', posts=posts)
@app.route('/post/<int:post_id>')
def post_detail(post_id):
# post_id에 해당하는 게시글 찾기
post = next((post for post in posts if post['id'] == post_id), None)
if post:
return render_template('post_detail.html', post=post)
else:
return "게시글을 찾을 수 없습니다.", 404
@app.route('/create', methods=['GET', 'POST'])
def create_post():
global post_id
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
new_post = {
'id': post_id,
'title': title,
'content': content
}
posts.append(new_post)
post_id += 1
return redirect(url_for('index'))
return render_template('create_post.html')
if __name__ == '__main__':
app.run(debug=True)
/create
라우트: GET 요청 시 게시글 작성 폼을 보여주고, POST 요청 시 폼 데이터를 받아 새 게시글을 리스트에 추가합니다.posts
리스트: 게시글 데이터를 임시 저장 (실제 서비스에서는 데이터베이스를 사용).
저장된 게시글을 메인 페이지에 나열하고, 각 게시글의 상세 페이지를 구현합니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>{% block title %}게시판{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<header>
<h1><a href="{{ url_for('index') }}">간단한 게시판</a></h1>
<nav>
<a href="{{ url_for('create_post') }}">게시글 작성</a>
</nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
- 모든 템플릿에 공통으로 적용되는 기본 레이아웃입니다.
{% extends 'base.html' %}
{% block title %}게시글 목록{% endblock %}
{% block content %}
<h2>게시글 목록</h2>
<ul>
{% for post in posts %}
<li>
<a href="{{ url_for('post_detail', post_id=post.id) }}">{{ post.title }}</a>
</li>
{% else %}
<li>게시글이 없습니다.</li>
{% endfor %}
</ul>
{% endblock %}
- 메인 페이지에서 저장된 모든 게시글을 리스트 형식으로 표시합니다.
- 각 게시글 제목은 해당 게시글의 상세 페이지로 이동하는 링크로 연결됩니다.
{% extends 'base.html' %}
{% block title %}게시글 작성{% endblock %}
{% block content %}
<h2>게시글 작성</h2>
<form method="POST" action="{{ url_for('create_post') }}">
<label for="title">제목:</label>
<input type="text" id="title" name="title" required>
<br>
<label for="content">내용:</label>
<textarea id="content" name="content" required></textarea>
<br>
<button type="submit">작성하기</button>
</form>
{% endblock %}
- 사용자가 제목과 내용을 입력할 수 있는 게시글 작성 폼입니다.
{% extends 'base.html' %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<a href="{{ url_for('index') }}">목록으로 돌아가기</a>
{% endblock %}
- 선택한 게시글의 제목과 내용을 상세히 보여줍니다.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #f0f0f0;
padding: 10px;
}
header h1 a {
text-decoration: none;
color: #333;
}
nav a {
margin-right: 10px;
text-decoration: none;
color: #007BFF;
}
main {
padding: 20px;
}
- 기본적인 스타일을 적용하여 레이아웃을 개선합니다.
- 가상 환경을 생성하고 활성화한 후 Flask를 설치합니다.
- 위 파일 구조대로 코드를 작성합니다.
- 터미널에서
python app.py
명령어로 서버를 실행합니다. - 웹 브라우저에서
http://127.0.0.1:5000/
주소로 접속하여 게시판 기능을 확인합니다.
이 튜토리얼을 통해 간단한 게시판 기능(게시글 작성, 목록 조회, 상세 조회)을 Flask로 구현하는 기본적인 방법을 익힐 수 있습니다. 이후 데이터베이스 연동이나 추가 기능(수정, 삭제 등)을 구현하며 프로젝트를 확장해 보세요.