ns python flask 2
TRANSCRIPT
Session 2/2
Olivier Rovellotti
Python
Lancer Flask
Set FLASK_APP=mypython.py
flask run
Le site des étudiants de la classe
Etudiant 1
Etudiant 2
Etudiant 3
Etudiant 4
Les étudiants de la classe Etudiant 1
Détail de l’étudiant
Les routes
from flask import Flask
app = Flask(__name__)
@app.route('/')
def classe():
return 'classe'
@app.route('/etudiant')
def etudiant():
return 'un etudiants'
SET FLASK_DEBUG=1
Les routes avec parametres
from flask import Flask,render_templateapp = Flask(__name__)
@app.route('/')def classe(): return 'classe'
@app.route('/etudiant/<name>')def hello(name=None): return ('bonjour ' + name)
Les templates
<!DOCTYPE html><html> <head> <title>un etudiant de la classe</title> </head> <body> <div class="container"> <p>Etudiant : {{name}}</p> </div> </body></html>
@app.route('/etudiant/<name>')def hello(name=None): return render_template('TemplateEtudiant.html', name=name)
Les templates
<!DOCTYPE html><html> <head> <title>un etudiant de la classe</title> </head> <body> <div class="container"> <p>Etudiant : {{name}}</p> </div> </body></html>
@app.route('/etudiant/<name>')def hello(name=None): return render_template('TemplateEtudiant.html', name=name)
Les templates
<!DOCTYPE html><html> <head> <title>un etudiant de la classe</title> </head> <body> <h1>Voila la liste des etudiants</h1> <div class="container">
{% for key, value in dictionaire.items() %} <li> <a href="./etudiant/{{ key }}">{{ key }}</a></li> {% endfor %} </div> </body></html>
dictionaire = {"Olivier": '0609566656', "Kevin": '065567785',"Shana": '065767785'}
@app.route('/')def classe(): return render_template('TemplateClasse.html', dictionaire=dictionaire)
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">body { font-family: sans-serif; background: #eee; }
a, h1, h2 { color: black; }
h1, h2 { font-family: 'Georgia', serif; margin: 0; }
h1 { border-bottom: 2px solid ; background-color:lightgrey }
h2 { font-size: 1.2em; }
Les styles
<form method="POST" action="{{ url_for('add_post') }}"><dl>
<dt>Nom:<dd><input type="text" size="30" name="name"><dt>Telephone:<dd><input type="text" size="30" name="telephone"><dd><input type="submit" value="Ajouter">
</dl></form>
Les Ajouts
@app.route('/add_etudiant', methods=['POST'])def add_post(): name= request.form['name'] telephone= request.form['telephone'] dictionaire[name] = telephone return redirect(url_for('classe'))
Et voila