[Python] Two apparently same methods returning different results flask_sqlalchemy

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to work with message flashing with flask and also trying to gain a better understanding of Flask_SQLAlchemy and SQL as a whole. I'm trying to get a message to appear if the user enters an incorrect email address I have managed to find a solution that works but I am confused why a similar solution doesn't.

    @app.route('/login', methods=["GET", "POST"])
    def login():
    email = request.form.get("email")
    password = request.form.get("password")
    if request.method == "POST":
    user = User.query.filter_by(email=email).first()
    if not user:
    flash("sorry that email doesn't exist")
    return redirect(url_for('login'))
    elif not check_password_hash(user.password, password):
    flash("Password incorrect, please try again")
    return redirect(url_for('login'))
    else:
    login_user(user)
    return redirect(url_for('secrets', id=user.id))
    return render_template("login.html")


    This code works perfectly fine and I am getting the error message pop up as expected however when I adjust the

    user = User.query.filter_by(email=email).first()


    to

    user = db.session.execute(db.select(User).filter_by(email=email)).scalar_one()


    so the block of code looks like this..

    @app.route('/login', methods=["GET", "POST"])
    def login():
    email = request.form.get("email")
    password = request.form.get("password")
    if request.method == "POST":
    user = db.session.execute(db.select(User).filter_by(email=email)).scalar_one()
    if not user:
    flash("sorry that email doesn't exist")
    return redirect(url_for('login'))
    elif not check_password_hash(user.password, password):
    flash("Password incorrect please try again")
    return redirect(url_for('login'))
    else:
    login_user(user)
    return redirect(url_for('secrets', id=user.id))
    return render_template("login.html")



    Then the code throws the following error


    raise exc.NoResultFound( sqlalchemy.exc.NoResultFound: No row was found when one was required
    ​

    I'm aware that this error is being raised because the database entry isn't being found, but from reading the documentation I've been led to believe that there is no distinction between using the two methods and that the db.session.execute(db.select()) is just an updated version of User.query and so far I've been able to use both interchangeably throughout my code without any issues.

    Does anybody know exactly how these two methods differ if there is a difference at all and why I'm getting different results with what I believe to be two lines of code that are basically doing the same thing, or is the problem with my code and are these two methods interchangeable?

    Continue reading...

Compartilhe esta Página