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.
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 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.
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'] .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With