Skip to content Skip to sidebar Skip to footer

Python/flask: How To Tell How Long A User Spends On A Page? (data Entry/time Log App)

I have seen answers to see how long a user spends on a page using Javascript, but my knowledge of JS is lacking (much less integrating JS into my Python/Flask framework). My objec

Solution 1:

You can use a Flask session to track the start time. It's implemented on top of browser cookies.

http://flask.pocoo.org/docs/0.12/quickstart/#sessions

You need to implement a secret key for the app (as shown in the quickstart example), and then you can use the session object as a key value store for user-specific information.

For your particular use case, it might be something like:

@app.route('/logpage', methods=['GET', 'POST'])
@login_required
def logpage():
    form = LogForm()

    if form.validate_on_submit():
        entry = LogData(sessionid=form.sessionid.data, user_id=current_user.get_id(), 
                        starttime=session.pop('start_time', None), endtime=datetime.utcnow())
        db.session.add(entry)
        db.session.commit()

        return redirect(url_for('home'))

    session['start_time'] = datetime.utcnow()

    return render_template('logpage.html', form=form)

pageload = datetime.utcnow() before the form validation didn't work because:

  • this variable would be local to the scope of the function and wouldn't persist after the function completes
  • even if the variable weren't local to the scope of the function call, the same function is being called for both GET and POST, so it would be overridden when the user posts the form

One more thing to be aware of is that you can't trust the user to be using cookies or to allow JavaScript, so you should consider how your program would handle null start times in the database.

Post a Comment for "Python/flask: How To Tell How Long A User Spends On A Page? (data Entry/time Log App)"