Binta26 commited on
Commit
3155d59
Β·
verified Β·
1 Parent(s): 5b85ad6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -8
app.py CHANGED
@@ -12,15 +12,27 @@ import joblib
12
  import numpy as np
13
  from flask import (Flask, render_template, request, redirect,
14
  url_for, session, flash, g)
 
15
 
16
  # ── App setup ─────────────────────────────────────────────────────────────────
17
  app = Flask(__name__)
18
- app.secret_key = os.environ.get("SECRET_KEY", "iris-ml-secret-2024")
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
21
 
22
- # ── Chemin DB persistant sur HuggingFace ──────────────────────────────────────
23
- # Sur HF Spaces, /data/ est persistant si activΓ©, sinon fallback local
24
  _data_dir = "/data" if os.path.isdir("/data") else BASE_DIR
25
  DB_PATH = os.path.join(_data_dir, "users.db")
26
 
@@ -54,7 +66,6 @@ def close_db(_):
54
  def init_db():
55
  with app.app_context():
56
  db = get_db()
57
-
58
  db.execute("""
59
  CREATE TABLE IF NOT EXISTS users (
60
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -64,7 +75,6 @@ def init_db():
64
  created TEXT NOT NULL
65
  )
66
  """)
67
-
68
  db.execute("""
69
  CREATE TABLE IF NOT EXISTS sessions (
70
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -74,7 +84,6 @@ def init_db():
74
  FOREIGN KEY (user_id) REFERENCES users(id)
75
  )
76
  """)
77
-
78
  db.execute("""
79
  CREATE TABLE IF NOT EXISTS predictions (
80
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -88,7 +97,6 @@ def init_db():
88
  timestamp TEXT NOT NULL
89
  )
90
  """)
91
-
92
  try:
93
  db.execute("ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''")
94
  except sqlite3.OperationalError:
@@ -137,8 +145,11 @@ def login():
137
  (username, hash_pw(password))
138
  ).fetchone()
139
  if user:
 
140
  session["username"] = username
141
  session["user_id"] = user["id"]
 
 
142
  db.execute(
143
  "INSERT INTO sessions (user_id, login_at) VALUES (?, ?)",
144
  (user["id"], datetime.now().isoformat())
@@ -146,6 +157,7 @@ def login():
146
  cursor = db.execute("SELECT last_insert_rowid()")
147
  session["session_db_id"] = cursor.fetchone()[0]
148
  db.commit()
 
149
  flash(f"Bienvenue, {username} ! πŸ‘‹", "success")
150
  return redirect(url_for("predict"))
151
  flash("Nom d'utilisateur ou mot de passe incorrect.", "danger")
@@ -294,7 +306,7 @@ def admin():
294
  return render_template("admin.html", users=users, sessions_log=sessions_log, stats=stats)
295
 
296
 
297
- # ── Init DB au dΓ©marrage (fonctionne avec Gunicorn ET python app.py) ──────────
298
  init_db()
299
 
300
  if __name__ == "__main__":
 
12
  import numpy as np
13
  from flask import (Flask, render_template, request, redirect,
14
  url_for, session, flash, g)
15
+ from werkzeug.middleware.proxy_fix import ProxyFix
16
 
17
  # ── App setup ─────────────────────────────────────────────────────────────────
18
  app = Flask(__name__)
19
+
20
+ # CRITIQUE pour HuggingFace : l'app est derrière un reverse proxy
21
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
22
+
23
+ app.secret_key = os.environ.get("SECRET_KEY", "iris-ml-secret-2024-xK9pL")
24
+
25
+ # CRITIQUE : config cookies pour fonctionner derrière proxy HF
26
+ app.config.update(
27
+ SESSION_COOKIE_SAMESITE="None",
28
+ SESSION_COOKIE_SECURE=True,
29
+ SESSION_COOKIE_HTTPONLY=True,
30
+ SESSION_COOKIE_NAME="irisai_session",
31
+ )
32
 
33
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
34
 
35
+ # Chemin DB persistant sur HuggingFace
 
36
  _data_dir = "/data" if os.path.isdir("/data") else BASE_DIR
37
  DB_PATH = os.path.join(_data_dir, "users.db")
38
 
 
66
  def init_db():
67
  with app.app_context():
68
  db = get_db()
 
69
  db.execute("""
70
  CREATE TABLE IF NOT EXISTS users (
71
  id INTEGER PRIMARY KEY AUTOINCREMENT,
 
75
  created TEXT NOT NULL
76
  )
77
  """)
 
78
  db.execute("""
79
  CREATE TABLE IF NOT EXISTS sessions (
80
  id INTEGER PRIMARY KEY AUTOINCREMENT,
 
84
  FOREIGN KEY (user_id) REFERENCES users(id)
85
  )
86
  """)
 
87
  db.execute("""
88
  CREATE TABLE IF NOT EXISTS predictions (
89
  id INTEGER PRIMARY KEY AUTOINCREMENT,
 
97
  timestamp TEXT NOT NULL
98
  )
99
  """)
 
100
  try:
101
  db.execute("ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''")
102
  except sqlite3.OperationalError:
 
145
  (username, hash_pw(password))
146
  ).fetchone()
147
  if user:
148
+ session.clear()
149
  session["username"] = username
150
  session["user_id"] = user["id"]
151
+ session.permanent = True
152
+
153
  db.execute(
154
  "INSERT INTO sessions (user_id, login_at) VALUES (?, ?)",
155
  (user["id"], datetime.now().isoformat())
 
157
  cursor = db.execute("SELECT last_insert_rowid()")
158
  session["session_db_id"] = cursor.fetchone()[0]
159
  db.commit()
160
+
161
  flash(f"Bienvenue, {username} ! πŸ‘‹", "success")
162
  return redirect(url_for("predict"))
163
  flash("Nom d'utilisateur ou mot de passe incorrect.", "danger")
 
306
  return render_template("admin.html", users=users, sessions_log=sessions_log, stats=stats)
307
 
308
 
309
+ # ── Init DB au dΓ©marrage ───────────────────────────────────────────────────────
310
  init_db()
311
 
312
  if __name__ == "__main__":