Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 868
Reshef Avatar asked Dec 22 '18 21:12

Reshef


People also ask

How do I find user session in Flask?

The following code is a simple demonstration of session works in Flask. URL '/' simply prompts user to log in, as session variable 'username' is not set. As user browses to '/login' the login() view function, because it is called through GET method, opens up a login form.

How do you save data in a session in Flask?

How are sessions implemented in Flask? In order to store data across multiple requests, Flask utilizes cryptographically-signed cookies (stored on the web browser) to store the data for a session. This cookie is sent with each request to the Flask app on the server-side where it's decoded.

How do I know if someone logged into my Flask?

At the same time, you can use Flask-login API to do some configurations in case that you want to use its functionality. When you want to check whether the user has logged in manually rather than use the Flask-login API, then check the value of session['logged_in'] .

How do you get Session cookies in Flask?

Create cookie In Flask, set the cookie on the response object. Use the make_response() function to get the response object from the return value of the view function. After that, the cookie is stored using the set_cookie() function of the response object. It is easy to read back cookies.


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
like image 162
DaLynX Avatar answered Oct 22 '22 02:10

DaLynX