Python Flask: Message Flashing Session Issue

I have to say it: the Flask documents are pretty bad. The code is chunked up, abbreviated, poorly explained and no comments to really go through every little detail, which often leads to bizarre errors for the inexperienced programmer. Even for an experienced programmer, there’s some things that just are really mysterious or need far more depth. But I want to show something simple.

I wanted to try Message Flashing in my application. Once you add a flash() call, you may encounter the following error message (if you tail your supervisor logs)

RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.

Now, this is a little obvious and not really. Essentially, you’re supposed to add a ‘secret_key’ property to the app object that you instantiate from Flask. It can be whatever but you still have to dig it up. Now, this makes sense because Flash messaging essentially uses the session storage mechanism (at least it appears to me) for containing your messages in between request. That way, it goes away the next time you arrive at the page automagically.

To handle this error, you just need to add something like:

from flask import Flask, render_template

app = Flask(__name__)
app.secret_key = 'my unobvious secret key'

import myapp.views

For me, I placed this code in the file where my Flask application resides. I do this here because I will eventually turn this into the recommended application splitting where each application resides in a separate directory.

The problem here was that the documentation doesn’t directly tell you that you’re required to add a secret_key in order to use flash messaging because of its ties to sessions. That’s pretty awful. Even though I was able to guess what needed to be done, the real problem is that the documentation should point to this somewhere, at least in the tutorial or that horribly brief Large Applications section. There’s just a lot of missing steps in between key points or areas where a whole file needs to be shown to be obvious.

At any rate, I wrote this out of frustration, hoping that other people who have a similar problem can avoid this issue. Also, maybe they feel the same way.

(Visited 3,405 times, 1 visits today)