Chapter 3-7 Flask-SQLAlchemy 게시판 관리 웹 페이지 구축(routes/board.py)

2025. 4. 21. 10:34·Flask

📌 개념 정리

3-7. 사용자 관리 웹 페이지 구축

💻 전체 코드 예시 (templates/users.html)

<!DOCTYPE html>
<html>
  <head>
    <title>User Management</title>
  </head>
  <body>
    <h1>User Management</h1>

    <!-- 사용자 생성 폼 -->
    <form id="createUserForm">
      <input type="text" id="name" placeholder="Username" />
      <input type="text" id="email" placeholder="Email" />
      <button type="submit">Create User</button>
    </form>

    <!-- 사용자 조회 -->
    <button onclick="getUsers()">Get All Users</button>
    <div id="users"></div>

    <!-- 사용자 수정 폼 -->
    <form id="updateUserForm">
      <input type="number" id="updateUserId" placeholder="User ID" />
      <input type="text" id="updateUsername" placeholder="New Username" />
      <input type="text" id="updateEmail" placeholder="New Email" />
      <button type="submit">Update User</button>
    </form>

    <!-- 사용자 삭제 -->
    <form id="deleteUserForm">
      <input type="number" id="deleteUserId" placeholder="User ID" />
      <button type="submit">Delete User</button>
    </form>

    <script>
      // 함수 정의 (아래 스텝별로 나누어 설명)
    </script>
  </body>
</html>

🚦 단계별 프로세스 흐름 및 설명

📍 Step 1: 사용자 생성

document.getElementById("createUserForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;

  fetch("/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, email }),
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
    getUsers();
  });
});
  • 새로운 사용자를 서버에 추가하고, 변경 사항을 즉시 사용자 목록에 반영합니다.

📍 Step 2: 전체 사용자 조회

function getUsers() {
  fetch("/users")
  .then(response => response.json())
  .then(data => {
    const usersDiv = document.getElementById("users");
    usersDiv.innerHTML = "";
    data.forEach(user => {
      usersDiv.innerHTML += `<p>ID: ${user.id}, Name: ${user.name}, Email: ${user.email}</p>`;
    });
  });
}
  • 서버에서 모든 사용자 정보를 가져와서 화면에 표시합니다.

📍 Step 3: 사용자 정보 수정

document.getElementById("updateUserForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const userId = document.getElementById("updateUserId").value;
  const name = document.getElementById("updateUsername").value;
  const email = document.getElementById("updateEmail").value;

  fetch(`/users/${userId}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, email }),
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
    getUsers();
  });
});
  • 특정 사용자의 정보를 수정하여 서버에 업데이트합니다.
  • 변경된 정보는 즉시 반영됩니다.

📍 Step 4: 사용자 삭제

document.getElementById("deleteUserForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const userId = document.getElementById("deleteUserId").value;

  fetch(`/users/${userId}`, { method: "DELETE" })
  .then(response => response.json())
  .then(data => {
    console.log(data);
    getUsers();
  });
});
  • 서버에서 사용자를 삭제하고 변경된 사용자 목록을 갱신하여 화면에 다시 표시합니다.

✅ 마무리 요약 및 복습 포인트

  • 사용자 관리 웹 페이지를 구축하여 사용자 정보를 쉽게 추가, 조회, 수정, 삭제할 수 있습니다.
  • 비동기 요청을 통해 서버와 실시간으로 데이터를 주고받으며 사용자 경험을 개선합니다.

'Flask' 카테고리의 다른 글

Chapter 3-9 Flask-SQLAlchemy CRUD 테스트 방법  (0) 2025.04.21
Chapter 3-8 DB 객체 모델 정의 방법 2가지  (0) 2025.04.21
Chapter 3-6 Flask-SQLAlchemy 게시판 관리 웹 페이지 구축(routes/board.py)  (0) 2025.04.21
Chapter 3-5 Flask-SQLAlchemy 게시판 관리 라우트 구축 (routes/board.py)  (0) 2025.04.21
Chapter 3-4 Flask-SQLAlchemy 사용자 관리 라우트 구축(routes/user.py)  (0) 2025.04.21
'Flask' 카테고리의 다른 글
  • Chapter 3-9 Flask-SQLAlchemy CRUD 테스트 방법
  • Chapter 3-8 DB 객체 모델 정의 방법 2가지
  • Chapter 3-6 Flask-SQLAlchemy 게시판 관리 웹 페이지 구축(routes/board.py)
  • Chapter 3-5 Flask-SQLAlchemy 게시판 관리 라우트 구축 (routes/board.py)
Chansman
Chansman
안녕하세요! 코딩을 시작한 지 얼마 되지 않은 초보 개발자 찬스맨입니다. 이 블로그는 제 학습 기록을 남기고, 다양한 코딩 실습을 통해 성장하는 과정을 공유하려고 합니다. 초보자의 눈높이에 맞춘 실습과 팁, 그리고 개발하면서 겪은 어려움과 해결 과정을 솔직하게 풀어내려 합니다. 함께 성장하는 개발자 커뮤니티가 되기를 바랍니다.
  • Chansman
    찬스맨의 프로그래밍 스토리
    Chansman
  • 전체
    오늘
    어제
    • 분류 전체보기 (799) N
      • Python (32)
      • 프로젝트 (118) N
      • 과제 (25)
      • Database (40)
      • 멘토링 (11)
      • 특강 (37)
      • 기술블로그 (41)
      • 기술블로그-Fastapi편 (33)
      • 기술블로그-Django편 (153)
      • 기술블로그-Flask편 (36)
      • AI 분석 (5)
      • HTML & CSS (31)
      • JavaScript (17)
      • AWS_Cloud (21)
      • 웹스크래핑과 데이터 수집 (14)
      • Flask (42)
      • Django (77)
      • Fastapi (16)
      • 연예 (14)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    livebroadcast
    global politics
    homebartrend
    뷔
    self-growth
    americaparty
    lawsuitculture
    americanlaw
    basalcellcarcinoma
    titaniumcase
    classaction
    trumpmuskclash
    urbantrends
    btsjungkook
    btscomeback
    bts
    chatgpterror
    college reunions
    life reflection
    newpoliticalparty
    remittance
    gpterror
    travel ban
    btsreunion
    btsdischarge
    RM
    youngprofessionals
    chinanightlife
    smartphonedurability
    hotcoffeecase
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Chansman
Chapter 3-7 Flask-SQLAlchemy 게시판 관리 웹 페이지 구축(routes/board.py)
상단으로

티스토리툴바