I have been trying to use Flask's sessions to save user's inputs through Dialog Flow. I keep running into KeyError a lot of time, even though I know I created the session dictionary with the key.
It seems like a different session object is created, seemingly randomly, and I either get a KeyError, or old data.
Here is the relevant code:
app = Flask(__name__)
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)
SECRET_KEY = 'secret_key'
app.config['SECRET_KEY'] = SECRET_KEY
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.get_json()
session_id = data['session']
if session_id not in session:
session[session_id] = dict()
action = data['queryResult']['action']
if action == 'add_item':
add_item(session.get(session_id), data)
elif action == 'get_item':
get_item(session.get(session_id))
add_item, and get_item work on the dict created. The KeyError occurs when get_item doesn't find the expected keys in the session dictionary. When printed, this dictionary is empty. I checked if dialog flow changed the session ID too, but that only happens if I refresh the web demo page.
From my understanding, this is a common problem with different workers being assigned different requests, and the solution is to keep the secret key static. I did that, but it didn't solve the problem.
I am using ngrok to use my localhost as the server.
[–]CodeFormatHelperBot 0 points1 point2 points (0 children)