Chủ Nhật, 20 tháng 7, 2025

🔍 BÀI 23: VIẾT REST API NÂNG CAO VỚI SQLALCHEMY – LỌC, TÌM KIẾM, PHÂN TRANG

🎯 1. Mục tiêu

  • Chuyển sang dùng SQLAlchemy ORM để dễ quản lý model

  • Viết API /api/students hỗ trợ:

    • /api/students?name=An → tìm theo tên

    • /api/students?page=2&size=5 → phân trang

    • /api/students?min_score=7 → lọc theo điểm


⚙️ 2. Cài đặt thư viện

bash
pip install flask flask_sqlalchemy

🧱 3. Cấu trúc thư mục

pgsql
flask_orm_advanced/ ├── app.py ├── templates/ │ └── index.html

🧠 4. File app.py – Flask + SQLAlchemy + REST API nâng cao

python
from flask import Flask, request, jsonify, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///students.db" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) # Mô hình Student class Student(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) score = db.Column(db.Float, nullable=False) def to_dict(self): return {"id": self.id, "name": self.name, "score": self.score} # Tạo bảng nếu chưa có with app.app_context(): db.create_all() @app.route("/") def index(): return render_template("index.html") @app.route("/api/students", methods=["GET", "POST"]) def students(): if request.method == "POST": data = request.get_json() s = Student(name=data["name"], score=data["score"]) db.session.add(s) db.session.commit() return jsonify({"message": "Đã thêm"}), 201 # --- GET với lọc, tìm kiếm, phân trang --- query = Student.query # Tìm theo tên name = request.args.get("name") if name: query = query.filter(Student.name.contains(name)) # Lọc theo điểm min_score = request.args.get("min_score", type=float) if min_score is not None: query = query.filter(Student.score >= min_score) # Phân trang page = request.args.get("page", default=1, type=int) size = request.args.get("size", default=10, type=int) students = query.offset((page - 1) * size).limit(size).all() return jsonify([s.to_dict() for s in students])

🧪 5. Thử nghiệm API nâng cao

📌 Lấy danh sách phân trang:

http
GET /api/students?page=2&size=5

🔍 Tìm sinh viên tên chứa “Minh”:

http
GET /api/students?name=Minh

🎯 Lọc điểm >= 7.5:

http
GET /api/students?min_score=7.5

🔁 Kết hợp:

http
GET /api/students?name=An&min_score=8&page=1&size=2

✅ 6. Ưu điểm của dùng SQLAlchemy

So với sqlite3Ưu điểm SQLAlchemy
Code dài, khó tái sử dụngORM dễ mở rộng, dễ đọc
Không có model rõ ràngCó class đại diện bảng
Không hỗ trợ chuyển CSDL dễDễ migrate sang PostgreSQL, MySQL
Phức tạp nếu nhiều bảngHỗ trợ quan hệ 1-n, n-n tốt

🧩 7. Mở rộng nâng cao

  • ✅ Thêm endpoint PUTDELETE dùng SQLAlchemy

  • ✅ Tạo API GET /students/<id> để xem chi tiết

  • ✅ Kết nối với biểu đồ Chart.js hoặc giao diện nhập như các bài trước


✅ 8. Kết luận

Bạn vừa:

  • Xây REST API với khả năng lọc, tìm kiếm, phân trang

  • Sử dụng SQLAlchemy ORM để dễ bảo trì và nâng cấp

  • Chuẩn bị nền tảng vững chắc cho hệ thống lớn hơn

=============================
Website không chứa bất kỳ quảng cáo nào, mọi đóng góp để duy trì phát triển cho website (donation) xin vui lòng gửi về STK 90.2142.8888 - Ngân hàng Vietcombank Thăng Long - TRAN VAN BINH
=============================
Nếu bạn không muốn bị AI thay thế và tiết kiệm 3-5 NĂM trên con đường trở thành DBA chuyên nghiệp hay làm chủ Database thì hãy đăng ký ngay KHOÁ HỌC ORACLE DATABASE A-Z ENTERPRISE, được Coaching trực tiếp từ tôi với toàn bộ bí kíp thực chiến, thủ tục, quy trình của gần 20 năm kinh nghiệm (mà bạn sẽ KHÔNG THỂ tìm kiếm trên Internet/Google) từ đó giúp bạn dễ dàng quản trị mọi hệ thống Core tại Việt Nam và trên thế giới, đỗ OCP.
- CÁCH ĐĂNG KÝ: Gõ (.) hoặc để lại số điện thoại hoặc inbox https://m.me/tranvanbinh.vn hoặc Hotline/Zalo 090.29.12.888
- Chi tiết tham khảo:
https://bit.ly/oaz_w
=============================
2 khóa học online qua video giúp bạn nhanh chóng có những kiến thức nền tảng về Linux, Oracle, học mọi nơi, chỉ cần có Internet/4G:
- Oracle cơ bản: https://bit.ly/admin_1200
- Linux: https://bit.ly/linux_1200
=============================
KẾT NỐI VỚI CHUYÊN GIA TRẦN VĂN BÌNH:
📧 Mail: binhoracle@gmail.com
☎️ Mobile/Zalo: 0902912888
👨 Facebook: https://www.facebook.com/BinhOracleMaster
👨 Inbox Messenger: https://m.me/101036604657441 (profile)
👨 Fanpage: https://www.facebook.com/tranvanbinh.vn
👨 Inbox Fanpage: https://m.me/tranvanbinh.vn
👨👩 Group FB: https://www.facebook.com/groups/DBAVietNam
👨 Website: https://www.tranvanbinh.vn
👨 Blogger: https://tranvanbinhmaster.blogspot.com
🎬 Youtube: https://www.youtube.com/@binhguru
👨 Tiktok: https://www.tiktok.com/@binhguru
👨 Linkin: https://www.linkedin.com/in/binhoracle
👨 Twitter: https://twitter.com/binhguru
👨 Podcast: https://www.podbean.com/pu/pbblog-eskre-5f82d6
👨 Địa chỉ: Tòa nhà Sun Square - 21 Lê Đức Thọ - Phường Mỹ Đình 1 - Quận Nam Từ Liêm - TP.Hà Nội

=============================
AI, trí tuệ nhân tạo, artificial intelligence, machine learning, deep learning, LLM, ChatGPT, DeepSeek, Grok, oracle tutorial, học oracle database, Tự học Oracle, Tài liệu Oracle 12c tiếng Việt, Hướng dẫn sử dụng Oracle Database, Oracle SQL cơ bản, Oracle SQL là gì, Khóa học Oracle Hà Nội, Học chứng chỉ Oracle ở đầu, Khóa học Oracle online,sql tutorial, khóa học pl/sql tutorial, học dba, học dba ở việt nam, khóa học dba, khóa học dba sql, tài liệu học dba oracle, Khóa học Oracle online, học oracle sql, học oracle ở đâu tphcm, học oracle bắt đầu từ đâu, học oracle ở hà nội, oracle database tutorial, oracle database 12c, oracle database là gì, oracle database 11g, oracle download, oracle database 19c, oracle dba tutorial, oracle tunning, sql tunning , oracle 12c, oracle multitenant, Container Databases (CDB), Pluggable Databases (PDB), oracle cloud, oracle security, oracle fga, audit_trail,oracle RAC, ASM, oracle dataguard, oracle goldengate, mview, oracle exadata, oracle oca, oracle ocp, oracle ocm , oracle weblogic, postgresql tutorial, mysql tutorial, mariadb tutorial, ms sql server tutorial, nosql, mongodb tutorial, oci, cloud, middleware tutorial, hoc solaris tutorial, hoc linux tutorial, hoc aix tutorial, unix tutorial, securecrt, xshell, mobaxterm, putty

ĐỌC NHIỀU

Trần Văn Bình - Oracle Database Master