I'm on a project with Flask and I would like to create a session when the user is logging in. I follow the documentation but my script doesn't work and close directly after the opening. So, no way to launch my project in my browser.
My code is the following one:
#! /usr/bin/python
# -*- coding:utf-8 -*-
from flask import Flask, url_for, request, session
import mysql.connector
app = Flask(__name__)
@app.route('/connexion/', methods=['GET', 'POST'])
def connexion():
if request.method == 'POST':
if request.form['mail'] == "":
return affichage_form_mail(erreur = "001")
else:
cnx = mysql.connector.connect(user='admin', password='mysql', host='localhost', database='colocation')
cursor = cnx.cursor()
query = ("SELECT COUNT('email'), password FROM user WHERE email = '" + request.form['mail'] + "'")
cursor.execute(query)
i = cursor.fetchone()
if str(i[0]) != "1":
# on regarde le nombre d'enregistrements. Si diff de 0, on réaffiche le formulaire avec un code d'erreur 001
return affichage_form_mail(erreur = "001")
else:
# on vérifie le mdp
if request.form['password'] != str(i[1]):
# mot de passe faux, on reaffiche form_login avec en argument l'erreur et le mail
return affichage_form_mail(request.form['mail'], "002")
else:
# l'user est connecté. On le redirige vers son compte et on met une variable dans la session
session['connect'] = True
cursor.close()
cnx.close()
else:
return affichage_form_mail()
def affichage_form_mail(mail='Adresse email', erreur='none'):
aff_erreur = ""
if erreur == "001" :
aff_erreur = "Email inexistant"
if erreur == "002" :
aff_erreur = "Mot de passe inccorect"
if erreur == "003" :
aff_erreur = "Il faut indiquer email"
return aff_erreur + '<form action="" method="post"><input type="text" name="mail" value= "' + mail + '" /><input type="text" name="password" /><input type="submit" value="Envoyer" /></form>'
if __name__ == '__main__':
app.secret_key = "dd"
app.run(debug=True)
I know that my secret key is not so secure but it is not the point. Note that I tried without the secret key (don't ask why...) and I can open my project in Chrome but I have, of course, a error message telling that I have to put a secret key.
I hope you will be able to help me... I checked in the official documentation and I copy-paste to be sure to avoid any mistake but it still not working.