Simple server-side Flask session variable
Asked Answered
P

2

9

What is the easiest way to have a server-side session variable in Flask?

Variable value:

  1. A simple string
  2. Not visible to the client (browser)
  3. Not persisted to a DB -- simply vanishes when the session is gone

There is a built-in Flask session, but it sends the session data to the client:

session["secret"] = "I can see you"

The data is Base64 encoded and sent in a cryptographically signed cookie, but it is still trivial to read on the client.

In many frameworks, creating a server-side session variable is a one-liner, such as:

session.secret = "You can't see this"

The Flask solutions I have found so far are pretty cumbersome and geared towards handling large chunks of data. Is there a simple lightweight solution?

Phene answered 9/4, 2017 at 7:54 Comment(3)
flask.pocoo.org/snippets/132 except skip the saving to disk.Kinlaw
Please clarify your issue with sending data to the client. Just about every framework uses cookies to have a session identifier/token. The session identifier can then be used to lookup other session data that is stored in your local database. Is this what you want to do?Lew
@Lew Google "server-side session variable" and there are thousands of pertinent results. Session variables have been around as long as appservers have been in existence. Based on the answer below, Flask has a plugin to support session variables. Not all transient data needs to be stored in the local database.Phene
C
11

I think the Flask-Session extension is what you are looking for.

Flask-Session is an extension for Flask that adds support for Server-side Session to your application.

From the linked website:

from flask import Flask, session
from flask_session import Session  # new style
# from flask.ext.session import Session  # old style

app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)

@app.route('/set/')
def set():
    session['key'] = 'value'
    return 'ok'

@app.route('/get/')
def get():
    return session.get('key', 'not set')
Coinstantaneous answered 23/11, 2017 at 16:8 Comment(3)
The example code here does not work. It seems Flask-Session has changed not to mention there have been 2 years since a code checkin for Flask-Session. At least change the import to from flask_session import Session. But this alone is not enough. I'm still trying to figure out how to get this package to work.Liberati
does is working for anybody ? I have tried to implement same but didn't work. can anybody share working example. ThanksBaronet
yes, execute "pip install Flask-Session" to install flask_session packageAspasia
P
9

This answer is from June 2020 for flask-session 0.3.2. The documentation is here.

There are several available SESSION_TYPESs. filesystem is the most straightforward while you're testing. The expectation is you already have a Redis, database, etc. setup if you are going to use the other SESSION_TYPEs. Section on SESSION_TYPE and requirements

  • null: NullSessionInterface (default)
  • Redis: RedisSessionInterface
  • Memcached: MemcachedSessionInterface
  • filesystem: FileSystemSessionInterface
  • MongoDB: MongoDBSessionInterface
  • SQLAlchemy: SqlAlchemySessionInterface

Code example from the documentation. If you go to /set/ then the session['key'] is populated with the word 'value'. But if you go to /get/ first, then `session['key'] will not exist and it will return 'not set'.

from flask import Flask, session
from flask_session import Session

app = Flask(__name__)

app.config['SESSION_TYPE'] = 'filesystem'
#personal style preference compared to the first answer

Session(app)

@app.route('/set/')
def set():
    session['key'] = 'value'
    return 'ok'

@app.route('/get/')
def get():
    return session.get('key', 'not set')
Propraetor answered 24/6, 2020 at 21:17 Comment(1)
Pretty sure the setting of SESSION_TYPE var the way you set it is the only correct way as Martijn Pieters points out: "it doesn't make much sense with Flask 0.10 or newer; NullSession may have made sense with Flask 0.8 or 0.9, but in current version the flask.session.NullSession class is used as an error signal. In your case it gives you the wrong error message now."Pluviometer

© 2022 - 2024 — McMap. All rights reserved.