Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 974
Dem Pilafian Avatar asked Apr 09 '17 07:04

Dem Pilafian


People also ask

Is Flask session server-side?

Flask-Session is an extension for Flask that supports Server-side Session to your application. The Session is the time between the client logs in to the server and logs out of the server. The data that is required to be saved in the Session is stored in a temporary directory on the server.

How do you access session variables in Flask?

To release a session variable use pop() method. The following code is a simple demonstration of session works in Flask. URL '/' simply prompts user to log in, as session variable 'username' is not set. As user browses to '/login' the login() view function, because it is called through GET method, opens up a login form.

Does Flask support client-side sessions?

Flask uses the client-side approach. Pros: Validating and creating sessions is fast (no data storage) Easy to scale (no need to replicate session data across web servers)


1 Answers

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')
like image 152
langlauf.io Avatar answered Oct 29 '22 22:10

langlauf.io