Question

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.

No correct solution

OTHER TIPS

Your indentation of app.secret_key = "dd" is wrong. It must be on the same level as the app.run call.

Indentation is NOT OPTIONAL in Python - it's part of the syntax. You MUST indent blocks in a consistent way or your script won't run.

Python gives you very helpful error messages by the way - so please run your code in a terminal (cmd.exe on windows, any shell on other OSes) using python yourfile.py. That way the terminal does not close when the script terminates and you actually see errors instead of having to ask here.


Also you handle SQL really wrong:

query = ("SELECT COUNT('email'), password FROM user WHERE email = '" + request.form['mail'] + "'")
cursor.execute(query)

That code has a gaping SQL injection hole. Do this instead:

query = "SELECT COUNT('email'), password FROM user WHERE email = %s"
cursor.execute(query, [request.form['mail']])

This way the database (or database api) will handle your arguments in a secure way.


Another thing: You should really use Jinja2 templates instead of creating an ugly mess of embedded HTML. It's an excellent template engine that's already a dependency of Flask anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top