Thứ Ba, 4 tháng 11, 2025

Bài 3: Flask + SQLite + Form lưu thông tin học sinh

📘 BÀI 3: FLASK + CƠ SỞ DỮ LIỆU SQLITE + FORM LƯU HỌC SINH


🎯 Mục tiêu bài học

  • Biết cách sử dụng SQLite trong Flask.
  • Tạo form nhập thông tin học sinh (họ tên, lớp, điểm trung bình).
  • Lưu dữ liệu vào cơ sở dữ liệu SQLite.
  • Hiển thị danh sách học sinh đã nhập.
Flask SQLite form illustration

🧩 1. Cấu trúc thư mục dự án


flask_sqlite/
 ├─ app.py
 ├─ students.db
 └─ templates/
      ├─ index.html
      └─ list.html

📂 File students.db là cơ sở dữ liệu SQLite. Flask sẽ tự tạo nếu chưa có.


⚙️ 2. File app.py


import sqlite3
from flask import Flask, render_template, request, redirect

app = Flask(__name__)

# --- Hàm khởi tạo database ---
def init_db():
    conn = sqlite3.connect('students.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS students (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    hoten TEXT NOT NULL,
                    lop TEXT NOT NULL,
                    diem REAL
                )''')
    conn.commit()
    conn.close()

# --- Trang chủ: Form nhập thông tin ---
@app.route('/')
def index():
    return render_template('index.html')

# --- Xử lý lưu dữ liệu ---
@app.route('/add', methods=['POST'])
def add_student():
    hoten = request.form.get('hoten')
    lop = request.form.get('lop')
    diem = request.form.get('diem')

    conn = sqlite3.connect('students.db')
    c = conn.cursor()
    c.execute("INSERT INTO students (hoten, lop, diem) VALUES (?, ?, ?)",
              (hoten, lop, diem))
    conn.commit()
    conn.close()

    return redirect('/list')

# --- Trang hiển thị danh sách ---
@app.route('/list')
def list_students():
    conn = sqlite3.connect('students.db')
    c = conn.cursor()
    c.execute("SELECT * FROM students")
    data = c.fetchall()
    conn.close()
    return render_template('list.html', students=data)

if __name__ == '__main__':
    init_db()
    app.run(debug=True)
💡 Giải thích:
- Hàm init_db() tạo bảng “students” nếu chưa có.
- / là trang nhập thông tin học sinh.
- /add nhận dữ liệu POST và lưu vào database.
- /list hiển thị danh sách học sinh đã lưu.

🧾 3. File templates/index.html – Form nhập dữ liệu


<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <title>Nhập thông tin học sinh</title>
  <style>
    body {
      font-family: Arial;
      background: linear-gradient(120deg,#6dd5fa,#2980b9);
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    .form-box {
      background: #fff;
      padding: 30px;
      border-radius: 8px;
      width: 400px;
      box-shadow: 0 0 10px rgba(0,0,0,0.2);
    }
    h2 {
      text-align: center;
      color: #2980b9;
    }
    label {
      display: block;
      margin-top: 10px;
      font-weight: bold;
    }
    input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }
    button {
      margin-top: 20px;
      background: #2980b9;
      color: #fff;
      border: none;
      padding: 10px;
      border-radius: 5px;
      width: 100%;
      cursor: pointer;
    }
    button:hover {
      background: #1a5f8a;
    }
  </style>
</head>
<body>
  <form class="form-box" action="/add" method="POST">
    <h2>🧾 Nhập thông tin học sinh</h2>
    <label>Họ và tên:</label>
    <input type="text" name="hoten" required>

    <label>Lớp:</label>
    <input type="text" name="lop" required>

    <label>Điểm trung bình:</label>
    <input type="number" name="diem" min="0" max="10" step="0.1" required>

    <button type="submit">Lưu học sinh</button>
  </form>
</body>
</html>

📋 4. File templates/list.html – Hiển thị danh sách học sinh


<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <title>Danh sách học sinh</title>
  <style>
    body {
      font-family: Arial;
      background: #f0f4f8;
      padding: 30px;
    }
    h2 {
      text-align: center;
      color: #2980b9;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    th, td {
      border: 1px solid #ccc;
      padding: 10px;
      text-align: center;
    }
    th {
      background: #e9f2ff;
    }
    a {
      display: inline-block;
      margin-top: 20px;
      text-decoration: none;
      color: white;
      background: #2980b9;
      padding: 10px 20px;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <h2>📚 Danh sách học sinh</h2>

  <table>
    <tr>
      <th>Mã</th>
      <th>Họ và tên</th>
      <th>Lớp</th>
      <th>Điểm TB</th>
    </tr>
    {% for hs in students %}
      <tr>
        <td>{{ hs[0] }}</td>
        <td>{{ hs[1] }}</td>
        <td>{{ hs[2] }}</td>
        <td>{{ hs[3] }}</td>
      </tr>
    {% endfor %}
  </table>

  <div style="text-align:center;">
    <a href="/">➕ Thêm học sinh mới</a>
  </div>
</body>
</html>

🚀 5. Khi chạy Flask

Sau khi chạy python app.py và mở trình duyệt tại http://127.0.0.1:5000:

  • Trang đầu: nhập thông tin học sinh.
  • Khi bấm Lưu học sinh, dữ liệu được lưu vào SQLite.
  • Trang /list hiển thị bảng danh sách học sinh đã nhập.
Flask list demo

🏁 6. Thử thách mở rộng cho học sinh

  • Thêm cột “Email” vào form và cơ sở dữ liệu.
  • Thêm nút “Xóa” hoặc “Sửa” học sinh.
  • Trang “Thống kê” hiển thị học sinh có điểm > 8.

📚 Kết luận

  • Học sinh đã biết cách lưu và đọc dữ liệu thực bằng SQLite trong Flask.
  • Đây là nền tảng của lập trình web thực tế – dữ liệu, giao diện, xử lý backend.
  • Có thể mở rộng sang CRUD (Create, Read, Update, Delete).

© 2025 Trường THPT Phan Chu Trinh – Gia Lai | Bài giảng thực hành Flask – Phần 3

Không có nhận xét nào:

Đăng nhận xét

Bài đăng phổ biến

💬 Bình luận

💬 Bình luận

📌 Danh sách bình luận