Jenna Kwon Jenna Kwon - 4 months ago 61
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?


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'))

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!