Jenna Kwon Jenna Kwon - 19 days ago 5
Python Question

Assigning same session ID for returning users with Python Flask app

I have a simple Flask webapp without login functionality. I would like to identify returning users, however, instead of assigning different session IDs every time. Would there be a way to achieve this?

Answer

You can put information in the session and recover it in server-side using flask session:

from flask import Flask, session, redirect, url_for, request

app = Flask(__name__)   

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        session['cookie-parameter'] = request.form['data-from-form']
        return redirect(url_for('other_endpoint'))
    return redirect(url_for('other_endpoint'))

@app.route('/other-url')
def other_endpoint():
    session.pop('cookie-parameter', None)
    return redirect(url_for('index'))

# Don't forget to add the secret key
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

Hope it helps!