I'm trying to understand how Flask-Login
works.
I see in their documentation that they use a pre-populated list of users. I want to play with a database-stored users list.
However, I don't understand some things in this Flask-Login
module.
@login_manager.user_loader
def load_user(userid):
#print 'this is executed',userid
return user(userid, 'asdf')
This code will be called at every request? This is used to load all the details of my user object?
For now, I have this code:
@app.route('/make-login')
def make_login():
username = 'asdf'
password = 'asdf'
user_data = authenticate(username, password)
user_obj = user(user_data[0], user_data[1])
login_user(user_obj)
return render_template('make-login.html')
When I access /make-login, I want to log in.
My user class:
class user(object):
def __init__(self, id, username, active=True):
self.username = username
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 5
Also, I wrote another two functions for authenticate/register
def authenticate(username, password):
cursor = db.cursor()
password = md5.md5(password).hexdigest()
try:
query = "SELECT * FROM `users` WHERE `username` = %s AND `password` = %s"
cursor.execute(query, (username, password))
results = cursor.fetchall()
#print results[0][0]
#print "here i am"
if not results:
return False
else:
user_data = [results[0][0], results[0][1]]
return user_data
#self.authenticated = True
#self.user_id = results[0][0]
#session['username'] = results['username']
#print type(results)
except db.Error, e:
return 'There was a mysql error'
def register(username, password, email, *args):
cursor = db.cursor()
password = md5.md5(password).hexdigest()
try:
#query = "INSERT INTO `users` (`username`, `password`, `email`) VALUES ('%s', '%s', '%s')" % (username, password, email)
query = "INSERT INTO `users` (`username`, `password`, `email`) VALUES (%s, %s, %s)"
cursor.execute(query, (username, password, email))
db.commit()
return True
except db.Error, e:
print 'An error has been passed. %s' %e
db.rollback()
return False
I don't know how to make this Flask-Login
work with MySQL. Also, I don't know if the user are logged-in. How can I get the user ID or the username?
Anyone can explain me in some rows how this Flask-Login
works?
See Question&Answers more detail:
os