Flask session not persisting


I have a web application running on a Flask backend with a JS client handling the front-end work. I'm running into problems trying to save a key-value pair to Flask's session object (flask.session) through a simple Flask API.

The session object I'm trying to modify is called account_id and the two API routes basically look like this:


@access_service.route('/current_account.json', methods=['GET'])
def show_current_account():
    return jsonify(account_id=session.get('account_id'))


@access_service.route('/current_account.json', methods=['POST'])
def update_current_account():
if request.json:
    session['account_id'] = request.json['account_id']
    return jsonify(account_id=session.get('account_id'))
return jsonify()

In the JS frontend a call to the POST route is made as follows:

  url: '/current_account.json',
  contentType: 'application/json',
  type: 'POST',
  data: JSON.stringify({ 'account_id': 10 })

Which does appear to work correctly, the ajax call returns with 200 OK and a correct return value. Logging from the Flask application also reveals that the session now contains the key account_id with value 10. However, looking up /current_account.json immediately after the POST request is made simply returns an account_id with value null.

What's stranger still is that using a simple in-browser REST client and making an identical POST request to current_account.json causes the session to work and persist as expected through full-page refresh, etc. Since that is the case, it leads me to believe that the problem has to do with the request itself rather than with Flask's session object, although I can't seem to figure out what exactly is causing it.

9/6/2013 11:27:32 AM

In my previous project, we experienced the same issue and it turns out that $.ajax does not carry cookies. We used manual session store to remedy the problem.

1/22/2014 5:59:47 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow