Python 기초 실습 C7
Python 기초 실습 C7입니다. Flask main.py, templates/index.html, templates/detail.html로 목록/상세 라우팅과 404 처리를 정리했습니다.
Python 기초 실습 C7
이번 실습은 main.py, templates/index.html, templates/detail.html 세 파일로 Flask의 목록 페이지와 상세 페이지를 구성하는 예제다. C8에서 템플릿 렌더링을 더 확장하기 전, 여기서는 라우팅, URL 변수, 템플릿 반복문, 404 처리를 한 번에 정리한다.
프로젝트 구조
python-c7/
├── main.py
└── templates/
├── index.html
└── detail.html가상환경과 Flask 설치
mkdir -p python-c7/templates
cd python-c7
python3 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install Flaskmain.py
POSTS는 임시 데이터 역할을 한다. 실제 서비스에서는 DB에서 가져오지만, 기초 실습에서는 자료구조와 템플릿 흐름을 먼저 확인하는 편이 좋다.
from flask import Flask, abort, render_template
app = Flask(__name__)
POSTS = [
{
"id": 1,
"title": "Linux user management",
"summary": "useradd, groupadd, passwd 흐름 정리",
"body": "사용자와 그룹을 분리해서 권한을 관리한다.",
},
{
"id": 2,
"title": "Flask template basic",
"summary": "index/detail 템플릿 연결",
"body": "render_template 함수로 HTML에 데이터를 전달한다.",
},
]
@app.get("/")
def index():
return render_template("index.html", posts=POSTS)
@app.get("/detail/<int:post_id>")
def detail(post_id: int):
post = next((item for item in POSTS if item["id"] == post_id), None)
if post is None:
abort(404)
return render_template("detail.html", post=post)
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=True)templates/index.html
목록 페이지에서는 posts를 반복하면서 상세 페이지 링크를 만든다. URL을 직접 문자열로 쓰기보다 url_for를 사용하면 라우트 변경에 강하다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>Python C7</title>
</head>
<body>
<h1>Post list</h1>
<ul>
{% for post in posts %}
<li>
<a href="{{ url_for('detail', post_id=post.id) }}">{{ post.title }}</a>
<p>{{ post.summary }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>templates/detail.html
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>{{ post.title }}</title>
</head>
<body>
<p><a href="{{ url_for('index') }}">Back</a></p>
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
</body>
</html>실행과 확인
python main.pycurl http://127.0.0.1:5000/
curl http://127.0.0.1:5000/detail/1
curl -i http://127.0.0.1:5000/detail/999/detail/999가 404를 반환하면 존재하지 않는 게시물 처리까지 정상이다. 이 구조가 잡히면 다음 단계에서 데이터 파일, DB, 검색 기능을 붙이기 쉽다.