Upload files to "/"
This commit is contained in:
parent
b59059eb6f
commit
f6f689504e
1 changed files with 80 additions and 0 deletions
80
app.py
Normal file
80
app.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import os
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Flask, request, redirect, render_template, url_for
|
||||
|
||||
# template_folder="." : index.html est à côté de ce script, à la racine.
|
||||
app = Flask(__name__, template_folder=".")
|
||||
|
||||
# Ce dossier correspond au point de montage déclaré côté Docker.
|
||||
DATA_DIR = os.environ.get("DATA_DIR", "/data")
|
||||
DB_PATH = os.path.join(DATA_DIR, "commentaires.db")
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Ouvre une connexion à la base, en créant le dossier de données au besoin."""
|
||||
os.makedirs(DATA_DIR, exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Crée la table si elle n'existe pas encore (idempotent)."""
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS commentaires (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
auteur TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
date_creation TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
with get_db() as conn:
|
||||
commentaires = conn.execute(
|
||||
"SELECT auteur, message, date_creation "
|
||||
"FROM commentaires ORDER BY id DESC"
|
||||
).fetchall()
|
||||
return render_template("index.html", commentaires=commentaires)
|
||||
|
||||
|
||||
@app.route("/poster", methods=["POST"])
|
||||
def poster():
|
||||
# Poster un commentaire.
|
||||
auteur = (request.form.get("auteur") or "").strip() or "Un chaton anonyme"
|
||||
message = (request.form.get("message") or "").strip()
|
||||
|
||||
if message:
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO commentaires (auteur, message, date_creation) "
|
||||
"VALUES (?, ?, ?)",
|
||||
(
|
||||
auteur[:60],
|
||||
message[:2000],
|
||||
datetime.now().strftime("%d/%m/%Y à %H:%M"),
|
||||
),
|
||||
)
|
||||
return redirect(url_for("index"))
|
||||
|
||||
|
||||
@app.route("/reset", methods=["POST"])
|
||||
def reset():
|
||||
# Supprime tout les commentaires.
|
||||
with get_db() as conn:
|
||||
conn.execute("DELETE FROM commentaires")
|
||||
return redirect(url_for("index"))
|
||||
|
||||
|
||||
init_db()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Serveur de test intégré, uniquement à usage démonstratif.
|
||||
app.run(host="0.0.0.0", port=5000)
|
||||
Loading…
Add table
Add a link
Reference in a new issue