Dem Pilafian
Dem Pilafian

Reputation: 6006

Simple server-side Flask session variable

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?

Upvotes: 9

Views: 18843

Answers (2)

fcsr
fcsr

Reputation: 939

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

Upvotes: 9

langlauf.io
langlauf.io

Reputation: 3201

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

Upvotes: 11

Related Questions