Flask, flask-login - I don't get it


Question

I have a mysql table with users and roles and I have a login page. It works. But, I don't get how to look up a user from a database.

1) Here is my User class and login form

class User(UserMixin):
    def __init__(self, email, password, org_role, user_role, id, active=True):
        self.email = email
        self.password = password
        self.org_role = org_role
        self.user_role = user_role
        self.id = id
        self.active = active
    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return unicode(self.id)
    def __repr__(self):
        return '<User %r>' % (self.email)


@login_manager.user_loader
def load_user(id):
    return USERS.get(int(id))


@app.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm()
    if request.method == "POST" and form.validate():
        if form.email.data + form.password.data in USER_NAMES:
            remember = request.form.get("remember", "no") == "yes"
            if login_user(USER_NAMES[form.email.data + form.password.data], remember=remember):
                flash("Logged in!")
                return redirect(request.args.get("next") or url_for("index"))
            else:
                flash(u"Sorry, but you could not log in.")
        else:
            flash(u"Invalid email/password.")
    return render_template("login.html", title = 'Sign In', form = form)

2) Here is what I don't understand.

I have this code:

USERS={}
for i,nn in enumerate(userlist):
    USERS[i+1]=User(nn['email'],nn['password'],nn['org_role'],nn['user_role'],int(nn['user_id']))
USER_NAMES = dict((u.email + u.password, u) for u in USERS.itervalues())

When I start the application, I have a mysql query that populates all of the allowed USERS.

I tried to follow the docs from flask-login but they dont show an example to do a lookup for users from a database. Only from a prepopulated list of users. If I update a user in a table, it's not picked up unless I restart the server.

This really makes no sense. Any guidance on how to lookup a user from a mysql database and add then to the User class will be great.

Below is my code for getting all users:

def getUsers():
    conn = MySQLdb.connect(host=db_host,user=db_username,passwd=db_password,db=db_database)
    cursor = conn.cursor()
    #query = """SELECT * from rtb_users WHERE email='%s' and password='%s'""" % (email,user_password)
    query = """SELECT * from rtb_users"""
    cursor.execute(query)

    userlist = []
    rows = cursor.fetchall()
    for row in rows:
        user_id = row[0]
        email = row[1]
        password = row[2]
        first_name = row[3]
        last_name = row[4]
        org_role = row[5]
        user_role = row[6]

        temp = {'user_id':user_id,'email':email,'password':password,'first_name':first_name,'last_name':last_name,'org_role':org_role,'user_role':user_role}
        userlist.append(temp)
    cursor.close()
    conn.close()
    return userlist
userlist = getUsers()
1
2
3/5/2014 9:12:20 AM

Accepted Answer

Simply access the database each time you need to load a user:

@login_manager.user_loader
def load_user(id):
    return get_user(id)

def get_user(user_id):

    # TODO: Return None on ValueError
    user_id = int(user_id)

    conn = MySQLdb.connect(...etc...)
    cursor = conn.cursor()
    user = cursor.fetchone("SELECT * FROM rtb_users WHERE ID = %s", (user_id, ))

    conn.close()

    try:
        # A simpler way to map row names to row values in a dictionary
        user = dict(zip(cursor.description, user))
        user = User(user['email'],
                        user['password'],
                        user['org_role'],
                        user['user_role'],
                        int(user['user_id']))
    except MySQLdb.Error:
        user = None

    return user

Eventually, you will most likely want caching on the get_user function (to avoid adding a database call for every single connection made to your server), but for testing, this should work.

2
5/24/2015 2:11:37 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon