🎓 A1Learner
🔍
0 of 50 lessons completed

The Flask Secret Key

The secret key signs the session cookie. Flask uses it to prove the cookie came from this app.

Make the app

This line makes the Flask app. The next line sets its secret key.

from flask import Flask

app = Flask(__name__)
app.secret_key = "dev-key"

Show the key length

The print shows how long the key is. The key itself never prints, because it is a secret.

print("Key length: " + str(len(app.secret_key)))

Example

from flask import Flask

app = Flask(__name__)
app.secret_key = "dev-key"

print("Key length: " + str(len(app.secret_key)))

Key points

  • app.secret_key holds a secret text.
  • The key signs cookies so readers cannot forge them.
  • Set the key before using sessions or flash.
  • A changed key logs every reader out.

In this example, the app is made and its secret key is set to "dev-key". The print shows the key length, 7. Sessions and flash need this key, so the next lessons set it the same way.

Note

Keep the real key private, never in shared code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the Flask secret key for?