0

Shouldn't the length of the row be equal to the length of the id, username, hash, and cash combined? Why is it written to give a message of invalid if the length does not equal 1?

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)
2

db.execute for a SELECT returns a list of dicts, a dict being some kind of key:value store. Each list entry corresponds to a database record.

So len(rows) represents the matching number of records (which is 0 or 1 for this query).

2
  • I have a question that is similar, that this sort of helps with so hijacking this thread if I may @Blauelf? I don't understand why we have 'rows[0]["hash"]' or 'rows[0]["id"]'. If rows is a list of dicts then it seems like the [0] is indexing to the first element/dict. I understand that the second [] gets the value for the key (in this case value for 'hash' or 'id'), but the [0] is confusing me. If rows = a list of dicts for a particular username surely it would return [{'id' : 'value'}, {'username' : 'value'}, {'hash : 'value}, {'cash' : 'value'}].
    – James
    Oct 30 '19 at 8:28
  • @James Did you mean [{'id' : 'value', 'username' : 'value', 'hash' : 'value', 'cash' : 'value'}], a list containing a single dict with multiple key/value pairs? And better make it a separate question, comments are not meant for this kind of thing.
    – Blauelf
    Nov 4 '19 at 10:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .