Cấu trúc Flask — routes, templates, static
Bài theo Python Machine Learning — Flask structure. Trước khi gắn model, tổ chức app rõ ràng giúp tách view (HTTP) khỏi inference (sklearn).
Mục tiêu
- Dùng thư mục
templates/vàstatic/theo convention Flask. - Viết route GET (form) và POST (submit) riêng biệt.
- Truyền biến từ Python sang Jinja2 (
render_template).
Lý thuyết
Pattern route cho ML UI
| Route | Method | Vai trò |
|---|---|---|
/ |
GET | Trang form nhập text |
/predict |
POST | Nhận review, gọi pipe.predict, render kết quả |
/health |
GET | Probe cho deploy |
Model load một lần ở module level hoặc @app.before_first_request (Flask 2.x+: dùng hàm init khi import).
Tham chiếu
Code Python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=["GET"])
def home():
return render_template("index.html", title="Sentiment demo")
@app.route("/predict", methods=["POST"])
def predict():
text = request.form.get("review", "")
# model.predict sẽ thêm ở bài sau
label = "pending"
return render_template("result.html", text=text, label=label)
if __name__ == "__main__":
app.run(debug=True)
templates/index.html (rút gọn):
<form action="/predict" method="post">
<textarea name="review" rows="4" cols="60"></textarea>
<button type="submit">Phân loại</button>
</form>
Lỗi thường gặp
- Đặt template ngoài
templates/—TemplateNotFound. - POST không có CSRF — chấp nhận được cho demo local; production cần token hoặc API JSON + auth.
- Logic train trong route — làm chậm và leak dữ liệu training vào request path.
Bài tập
- Thêm
static/style.cssvà link trongindex.html. - Route
/aboutrender template giải thích model dùng ở Ch.8.
Tóm tắt
Flask structure — routes + templates là khung UI trước khi nối file joblib từ bài serialize.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: Serialize sklearn Pipeline bằng joblib.