Sun Minh
Sun Minh

Reputation: 1

Flask Session does not retain value between POST requests

So I'm using flask to create endpoints as receivers and data processors. I have two threads of http POST requests, the first one is sent to the first route, similarly for the second one. The thing is I want the 2nd processor to be triggered only when the 1st one is, so I created a session key, to validate for the execution of the 2nd processor.

But no matter what I did, session key is always wiped when I sent POST to the second processor. Here's my code, which has been simplified. Pardon my amateur ablity to express the problem, I'm extremely new to coding.

from flask import Flask, request, redirect, url_for, session

app = Flask(__name__)
app.secret_key = "abc"

@app.route('/first_processor', methods=['POST'])
def first_processor():
    data = {
        'message': 'json received',
        'json': request.json
    }
    cond = data['json']

    if cond['event'] == "message:received":
        session["key"] = cond['key']
        return redirect(url_for("second_processor"))
    else:
        return data

@app.route('/second_processor', methods=['POST'])
def second_processor():
    if "key" in session:
        print('OK')
    else:
        print("FAIL")
    return data

if __name__ == "__main__":
    app.run(debug=True)

Upvotes: 0

Views: 954

Answers (1)

Bruck1701
Bruck1701

Reputation: 329

Apparently I saw two minor problems. The first one is that

@app.route('/second_processor', methods=['POST']) `

only allows POST method, and

redirect(url_for("second_processor"))

is a GET request. And you cannot force a POST request. Even though, according to the documentation, there is a _method parameter in the url_for function.
Related question: Issue a POST request with url_for in Flask

The second problem is that you created the data variable inside the first_processor function, but you don't pass it to the second_processor.

 if 'key' in session:
        print('OK')
    else:
        print("FAIL")
-->    return data

you could either:

  • pass the data inside the session,
  • make data global ( not sure if it is a good practice though)
  • store data in a file or db and read it inside second_processor.

Upvotes: 2

Related Questions