0
0
Flaskframework~5 mins

Secret key configuration in Flask

Choose your learning style9 modes available
Introduction

The secret key helps keep your Flask app safe by protecting important data like sessions and cookies.

When you want to keep user login sessions secure.
When you use Flask features that need encryption, like CSRF protection.
When you want to prevent others from tampering with your app's cookies.
When deploying your app to a server and need to keep data safe.
When using Flask extensions that require a secret key.
Syntax
Flask
app = Flask(__name__)
app.secret_key = 'your-secret-key'
The secret key should be a long, random string to be secure.
Never share your secret key publicly or commit it to public code repositories.
Examples
A simple secret key set directly as a string.
Flask
app.secret_key = 'mysecret123'
Generates a random secret key each time the app starts.
Flask
import os
app.secret_key = os.urandom(24)
Reads the secret key from an environment variable, with a fallback.
Flask
import os
app.secret_key = os.getenv('SECRET_KEY', 'default-secret')
Sample Program

This Flask app sets a secret key using a random value. It stores a username in the session and shows it on the homepage.

Flask
from flask import Flask, session
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)

@app.route('/')
def index():
    session['user'] = 'Alice'
    return f"User stored in session: {session['user']}"

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Changing the secret key will invalidate all existing sessions.

Use environment variables or config files to keep your secret key safe in real projects.

Summary

The secret key protects your app's sessions and cookies.

Set it to a strong, random value and keep it private.

Use environment variables to manage secret keys securely.