Python Flask - how to remember anonymous users via cookie/session?

Viewed 1731

I`m building a Flask web site that is a part of a research experiment. I need to be able to remember anonymous users so every visitor to my web site will be anonymous and unique but also be remembered so they could not enter the web site again (they will get redirection to a "thank you for your participation" page).

How can I do it? I looked into flask.session (how to generate unique anonymous id and save it to user cookie?) and Flask-login (have to be with user login to get an id) but didn't find the specific solution for this problem.

please help.

1 Answers

There is no perfect solution to your problem because you will not be able to identify a user if they are anonymous.

The most practical is probably to use sessions and save that they completed the survey in a session variable. But if they clear their cookies they will be able to enter the site again.

Example implementation:

from flask import session, app

@app.before_request
def make_session_permanent():
    session.permanent = True

In your survey form view:

if not "already_participated" in session:
    ... Display form

And then in your submit view:

session["already_participated"] = True
Related