Libra
Libra

Reputation: 369

Change session variable value fails

EDIT: actually, I can see the value of the session variable changed, but in the next call to the function the value is set back to 0

I am a Flask beginner and I have problems in changing the value of a session variable. Here is an excerpt of my code: EDIT after first round of comments

0) I set the SECRET_KEY variable in my config.py.

1) when a user logs in I set a session variable:

@app.route('/login', methods=['GET', 'POST'])
def login():
    session['info_released'] = 0
    app.logger.debug('info_released session value: {}'.format(session['info_released'])
    ...

Checking the log, the value of the session variable is correctly set to 0.

2) I have a counter variable passed via request.json that is incremented from time to time. Between one counter increment and the following one I check the following condition several times (via an ajax call):

@app.route('/get_actual_demand', methods=['GET', 'POST'])
def get_actual_demand():

    app.logger.info('> SESSION: {}'.format(session['info_released']))
    if request.json['counter'] == 10 and session['info_released'] == 0:
        #code
        session['info_released'] = 1
        app.logger.info('> SESSION VAR. AFTER CHANGE: {}'.format(session['info_released']))
        return jsonify(released=1)
    else:
        return jsonify(released=0)

That is, when counter == 10 I check the condition many times but I want to run the #code only once (the first time the counter == 10 and the session variable is 0).

EDIT: Checking the log, the session['info_released'] is changed to 1 when counter == 10, but in the next call the value is set back to 0: indeed, the #code is run many times until the counter gets incremented.

I can't understand what I am doing wrong. I may also have the program flow better organized, but I don't think it matters with the problem I am having.

EDIT: it seems that everything I do on the session variables inside the get_actual_demand() view function are only "local". I changed the code as follows, removing the session['info_released'] = 0 from the login() function:

@app.route('/get_actual_demand', methods=['GET', 'POST'])
def get_actual_demand():
    # the variable session['info_released'] is no more
    # defined in the login() function

    if request.json['counter'] == 10:
        try:
            # The first time I get here, raise a KeyError exception
            if session['info_released'] == 1:
                return jsonify(released=0)
        except KeyError:
            # Use `session['info_released']` as a flag,
            # defined here
            session['info_released'] = 1
            return jsonify(released=1)
    else:
        return jsonify(released=0)

Checking the log (removed from the code) I can see the session variable defined when it first hits the exception, but then hits again the exception as if the session variable is still not present.

I think there is something missing in my configuration, but I can't find hints in the documentation. My config.py is as follows:

import os
basedir = os.path.abspath(os.path.dirname(__file__))


class Config(object):
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True
    WTF_CSRF_ENABLED = True
    SECRET_KEY = 'oqEr[]*woi+145@#11!&$fsa%(Mn21eq'
    SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')

class DevelopmentConfig(Config):
    DEVELOPMENT = True
    DEBUG = True
    SQLALCHEMY_DATABASE_URI ='postgresql+psycopg2://libra:password@localhost/mydb'

Upvotes: 1

Views: 1614

Answers (1)

rbd33
rbd33

Reputation: 21

I had the same problem and I solved it using Flask-Session extension which adds support for Server-side Session to your application. Here is the URL:

http://pythonhosted.org/Flask-Session/

I added the next lines to my app:

from flask import Flask, session
from flask.ext.session import Session

app = Flask(__name__)
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)

and that's all. No need secret keys.

Hope this helps.

Upvotes: 1

Related Questions