Académique Documents
Professionnel Documents
Culture Documents
I / Introduction
Pour que le framework Flask communique
avcec MySQL, il faut un pilote flask-
mysql nommé flask-mysqldb
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'nom_base_donnes'
mysql = MySQL(app)
# différentes routes et leurs fonctions associées
if __name__ == "__main__":
app.run()
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Nom</th>
<th>Prénom</th>
<th>Salaire</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{% for employe in employes %}
<tr>
<td>{{employe[0]}}</td>
<td>{{employe[1]}}</td>
<td>{{employe[2]}}</td>
<td>{{employe[3]}}</td>
<td><a class="btn btn-primary btn-xs"
href="modif/{{employe[0]}}">Modifier</a></td>
<td><a class="btn btn-danger btn-xs"
href="sup/{{employe[0]}}">Supprimer</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
<div class="form-group">
<input type="submit" class="btn btn-success"
name="creer" value="Enregistrer">
</div>
</form>
</body>
</html>
3-3 la vue modif.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Liste des employés</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/c
ss/bootstrap.min.css" rel="stylesheet" integrity="sha384-
rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DG
LwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<h1>Modifier un employé</h1>
<div class="form-group">
<input type="submit" class="btn btn-success"
name="modifier" value="Modifier">
</div>
</form>
</body>
</html>
3 – 4 le contrôleur de l’application Flask : app.py
from flask import Flask, render_template, request, redirect,
url_for, flash
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'ong_db'
mysql = MySQL(app)
@app.route('/')
def index():
cur=mysql.connection.cursor()
cur.execute("SELECT * FROM employes")
employes = cur.fetchall()
cur.close()
return render_template('index.html', employes =
employes )
@app.route('/modif/<int:id>',methods = ['GET'])
def vsualiser(id):
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM employes where id =
%s",(id,))
employe = cur.fetchone()
return render_template('modif.html', employe=employe)
@app.route('/sup/<int:id>',methods = ['GET'])
def supprimer(id):
cur = mysql.connection.cursor()
cur.execute("DELETE FROM employes WHERE id=%s",
(id,))
mysql.connection.commit()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run()