0

When I make multiple requests, data doesn't get persisted.

I tried just to set session value in regular way (like in flask docs) but it doesn't work neither, session['array'] gets declared every time I make a new request.

secret_key is in the place.

Here is my route:

from flask import session
...
@app.route('/add', methods=['POST'])
@ath.login_required
def add():
    """
    adds an integer(s) to Array used for calculation.

    Parameters:
        integer(s): Integer or list of integers
    """
    param = request.json.get('integer')
    if not param:
        abort(make_response(jsonify("Param is not valid"), 400))

    if 'array' not in session:
        # each time I make a request, program enters this block
        session['array'] = []

    # I want to append more stuff into a session object
    # these 3 next lines are supposed to enable that
    # found it here: https://stackoverflow.com/questions/34630709
    array = session['array']
    array.append(param)
    session['array'] = param

    return jsonify({'success': session['array']}), 200

Making a request with curl: curl -u token -i -X POST -H "Content-Type: application/json" -d '{"integer": 2}' http://127.0.0.1:6767/add

What I am doing wrong?

11223342124
  • 175
  • 11
  • 1
    Typically, sessions are identified by a browser cookie. Your `curl` request does not have that, so each request is treated as a brand-new session. – John Gordon May 21 '20 at 14:51
  • It will not work in this way. Sessions are browser specific. – ngShravil.py May 21 '20 at 14:53
  • Moreover, I have seen that, it will work with flask templates. – ngShravil.py May 21 '20 at 14:55
  • Uhh that hurts. Is there a way to somehow work with curl and session simultaneously? I need to persist data across requests, and I don't want to use caching service/db? – 11223342124 May 21 '20 at 15:00
  • Browser cookies are just fancy header values. You're already sending one header, so it should just be a matter of sending another header to set the session cookie. – John Gordon May 21 '20 at 15:10
  • @JohnGordon Can you tell me what should be in that second header? Something browser specific? – 11223342124 May 21 '20 at 15:17
  • The curl argument to set cookies is `-b name=value`. I don't know what specific name Flask uses for its session id cookie, but that's easy to find out. – John Gordon May 21 '20 at 16:06
  • Curl supposedly supports cookies but I've played with it for longer that I'd like to admit and couldn't get it to continue adding values to the cookie. More importantly, it's important to understand that Flask-Session isn't storing anything server side, it's just a mechanism to update client stored data (a cookie). – RyanH May 21 '20 at 18:51

0 Answers0