Reputation: 12098
I'm using flask_login to authenticate my users logging in. I'd like to count every time they successfully log into my app.
Here's what my log in route looks like:
@app.route('/login', methods=['GET', 'POST'])
def login():
# Bypass if user is logged in
if current_user.is_authenticated:
return redirect(url_for('index'))
# continue
form = LoginForm(request.form)
# Validate login attempt
if form.validate_on_submit():
# Get data
my_data = {k:v for k,v in form.allFields.data.items()}
# If the user is in the db
user = User.query.filter_by(email=my_data["email"]).first()
if user and user.check_password(password=my_data["password"]):
# This is where the user is logged in <----------------------- !
login_user(user,remember=True)
# Otherwise
flash('Invalid username/password combination')
return redirect(url_for('/login'))
return render_template(
'login/login.html',
form=form,
title='Log in.',
template='login-page'
)
Upvotes: 0
Views: 1522
Reputation: 815
You can create a model UserLoginCount
with the field user_id
and count
. After login_user(user,remember=True)
do the following,
count
column for each successful log in.Insert this code after login_user(user,remember=True)
.
obj = UserLoginCount.query.filter_by(user_id=user.id).first()
if obj:
obj.count = obj.count + 1
else:
obj = UserLoginCount(user_id=user.id, count=1)
dbsession.add(obj)
dbsession.flush()
Note: This is basic implementation. Using foreign key will be best approach. You can look here.
Upvotes: 1
Reputation: 11360
You need a login_count
property added to your User class, or a separate model that ties each User to their login_count
. Then, increment the count each time they log in.
Show your User
model with UserMixin
if you need help setting that up
Upvotes: 0