Python 기초 실습 C6

Python 기초 실습 C6입니다. Flask 라우팅, request.args, query string, HTML form, health endpoint와 curl 테스트를 정리했습니다.

Python 기초 실습 C6

C6 실습은 Flask에서 기본 라우팅, URL query parameter, HTML form 입력을 처리하는 단계로 정리한다. C7에서 목록/상세 템플릿으로 넘어가기 전에, 브라우저 요청이 Python 함수로 들어오고 다시 HTML 응답으로 나가는 흐름을 이해하는 것이 핵심이다.

프로젝트 구조

python-c6/
├── main.py
└── templates/
    └── index.html

환경 준비

mkdir -p python-c6/templates
cd python-c6

python3 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install Flask

main.py

request.args는 URL 뒤에 붙는 query string 값을 읽는다. /로 접속하면 기본값을 사용하고, /?name=devmes처럼 접속하면 화면에 전달되는 값이 바뀐다.

from flask import Flask, render_template, request

app = Flask(__name__)


@app.get("/")
def index():
    name = request.args.get("name", "guest")
    topic = request.args.get("topic", "python")
    return render_template("index.html", name=name, topic=topic)


@app.get("/health")
def health():
    return {"status": "ok"}


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)

templates/index.html

<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <title>Python C6</title>
</head>
<body>
  <h1>Hello {{ name }}</h1>
  <p>Current topic: {{ topic }}</p>

  <form method="get" action="/">
    <label>
      Name
      <input name="name" value="{{ name }}">
    </label>
    <label>
      Topic
      <input name="topic" value="{{ topic }}">
    </label>
    <button type="submit">Send</button>
  </form>
</body>
</html>

실행과 테스트

python main.py
curl http://127.0.0.1:5000/
curl 'http://127.0.0.1:5000/?name=devmes&topic=flask'
curl http://127.0.0.1:5000/health

확인 포인트

  • URL이 바뀌면 request.args로 읽는 값도 바뀐다.
  • Python 함수에서 넘긴 값은 Jinja 템플릿의 {{ name }} 형식으로 출력된다.
  • form의 method="get"은 입력값을 URL query string으로 보낸다.
  • 간단한 health endpoint를 두면 서버가 살아 있는지 빠르게 확인할 수 있다.
BGM EVER