0

Tl;dr: How to generate Flask sessions without having to authenticate a user (e.g. login)?

The long story

I am developing a simple web app in which users can vote on whether a programming language is hot or not. So far I have an index HTML file that shows the user a programming language randomly and gets his/her vote, but this means that (quite frequently) a user gets prompted the same language twice or more.

E.g: python3 -> C# -> C -> Pascal -> python3

I want to remember a user "for some time" (session). If he/she closes his/her browser and then comes back to vote again, that's fine. I just want to avoid asking the users the same question twice.

All the tutorials and examples of Flask's sessions I found implement a login form of some kind, like the following from Flask's quickstart guide:

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))

Is there a way to generate sessions without specifying a username?

davidism
  • 121,510
  • 29
  • 395
  • 339
gmelodie
  • 411
  • 4
  • 18

1 Answers1

1

You must approach the problem differently!

Sessions are the correct construct to use.

However, instead of storing usernames you could store a JSON like object containing programming languages and an integer representing whether the user has voted for it yet.

For example, you can store in session an object similar to this:

{
    'java' : 0,
    'python3' : 0
    'pascal' : 0
}

After a user votes for a particular language, just update that particular language's value to 1.

Now you just need to ensure that the randomly asked language is a 0.

This works for each session without the need for user logging in.