Simple server-side Flask session variable

2019-07-29 16:44发布

问题:

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?

回答1:

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