Jenna Kwon Jenna Kwon - 1 year ago 113
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 Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download