oddurad
oddurad

Reputation: 417

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:

GET

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

POST

@access_service.route('/current_account.json', methods=['POST'])
@login_required
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:

$.ajax({
  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.

Upvotes: 2

Views: 4830

Answers (1)

Seunghoon
Seunghoon

Reputation: 5642

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.

Upvotes: 3

Related Questions