dagarre
dagarre

Reputation: 724

Flask: Set session variable from URL Param

I have a website that needs to be rebranded depending on the URL that a visitor comes in on. For the most part, the content is the same but the CSS is different. I'm brand new to flask and relatively new to session cookies, but I think the best way to do this is to create a session cookie containing a "client" session variable. Then, depending on the client (brand), I can append a specific css wrapper to a template.

How can I access URL params and set one of the param values to a session variable? For example, if a visitor comes in on www.example.com/index?client=brand1, then I'd like to set session['client'] = brand1.

My app.py file:

import os
import json
from flask import Flask, session, request, render_template


app = Flask(__name__)

# Generate a secret random key for the session
app.secret_key = os.urandom(24)

@app.route('/')
def index():
    session['client'] = 
    return render_template('index.html')

@app.route('/edc')
def edc():
    return render_template('pages/edc.html')

@app.route('/success')
def success():
    return render_template('success.html')

@app.route('/contact')
def contact():
    return render_template('pages/contact.html')

@app.route('/privacy')
def privacy():
    return render_template('pages/privacy.html')

@app.route('/license')
def license():
    return render_template('pages/license.html')

@app.route('/install')
def install():
    return render_template('pages/install.html')

@app.route('/uninstall')
def uninstall():
    return render_template('pages/uninstall.html')

if __name__ == '__main__':
    app.run(debug=True)

Upvotes: 1

Views: 2597

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

You could do so in a @flask.before_request decorated function:

@app.before_request
def set_client_session():
    if 'client' in request.args:
        session['client'] = request.args['client']

set_client_session will be called on each incoming request.

Upvotes: 4

Related Questions