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

🛠️ BÀI 25: CHUYỂN TỪ SQLITE SANG POSTGRESQL TRONG FLASK – TRIỂN KHAI DB LÊN CLOUD

🎯 1. Mục tiêu

  • Chuyển cấu hình Flask từ SQLitePostgreSQL

  • Sử dụng PostgreSQL trên Render hoặc Supabase (hoặc ElephantSQL – Free Plan)

  • Cập nhật Flask app để hoạt động với DB mới

  • Deploy lại ứng dụng lên Internet


💡 2. Tại sao cần chuyển sang PostgreSQL?

So sánhSQLitePostgreSQL
Dùng file đơn lẻ
Dễ mất dữ liệu sau restart cloud
Chạy production
Kết nối nhiều client
Có stored procedure, indexing, role
Phù hợp cloud, team work

🌐 3. Tạo PostgreSQL miễn phí

✅ Option 1: https://render.com

  • Vào dashboard → New → PostgreSQL

  • Đặt tên: students-db

  • Sau 30s sẽ có:

    • host

    • user

    • password

    • port

    • database

✅ Option 2: https://www.elephantsql.com

  • Đăng nhập bằng GitHub

  • Chọn Free Plan → Tạo database

  • Bạn sẽ nhận được URL kết nối PostgreSQL


🧱 4. Cập nhật app.py với SQLAlchemy + PostgreSQL

✅ Cài driver PostgreSQL:

bash
pip install psycopg2-binary

✅ Cập nhật app.py:

python
from flask import Flask, request, jsonify, render_template from flask_sqlalchemy import SQLAlchemy import os app = Flask(__name__) # Dùng biến môi trường hoặc URL trực tiếp (không khuyến nghị hard-code) POSTGRES_URL = os.environ.get("DATABASE_URL") or "postgresql://user:pass@host:port/dbname" app.config["SQLALCHEMY_DATABASE_URI"] = POSTGRES_URL app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) 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} @app.route("/") def home(): 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 students = Student.query.all() return jsonify([s.to_dict() for s in students]) # Khởi tạo bảng (chỉ gọi 1 lần nếu chưa có) with app.app_context(): db.create_all()

📄 5. Cập nhật file .env (tuỳ chọn)

Bạn có thể lưu biến môi trường vào .env và dùng python-dotenv:

bash
pip install python-dotenv
python
from dotenv import load_dotenv load_dotenv()

☁️ 6. Deploy lên Render (hoặc Railway)

✅ Cập nhật requirements.txt:

txt
Flask Flask_SQLAlchemy psycopg2-binary gunicorn python-dotenv

✅ Cập nhật Procfile:

txt
web: gunicorn app:app

✅ Tạo biến môi trường DATABASE_URL trên Render:

  • Trong phần Environment > Add Environment Variable

  • Key: DATABASE_URL

  • Value: postgresql://username:password@host:port/dbname


📈 7. Sau khi deploy

Bạn có thể:

  • Gọi API từ trình duyệt, Postman hoặc web app

  • Dữ liệu sẽ lưu trong PostgreSQL cloud

  • Dễ truy xuất, backup, chia sẻ, kiểm soát


✅ 8. Kiểm thử kết nối

Test CRUD:

bash
curl -X POST https://your-app.onrender.com/api/students \ -H "Content-Type: application/json" \ -d '{"name": "Linh", "score": 8.0}'
bash
curl https://your-app.onrender.com/api/students

💡 9. Lưu ý bảo mật

Vấn đềGiải pháp
Lộ DB URLDùng biến môi trường
Không dùng HTTPSRender có sẵn HTTPS
Dữ liệu dễ mất nếu xài SQLitePostgreSQL ổn định hơn
Ghi log sensitiveHạn chế log toàn bộ request

✅ 10. Kết luận

Bạn đã:

✅ Chuyển từ SQLite sang PostgreSQL (database thật)
✅ Cập nhật Flask app dùng SQLAlchemy ORM
✅ Deploy cloud-ready với DB connection qua biến môi trường
✅ Chuẩn bị tốt cho scale hệ thống production

=============================
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