Bird
Raised Fist0
Flaskframework~20 mins

Secret key configuration in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Secret Key Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens if Flask app's secret key is not set?

Consider a Flask app where the secret_key is not configured. What will happen when you try to use sessions?

Flask
from flask import Flask, session
app = Flask(__name__)

@app.route('/')
def index():
    session['user'] = 'Alice'
    return 'Session set!'

if __name__ == '__main__':
    app.run()
AFlask will raise a RuntimeError complaining about missing secret key.
BThe session data will be stored securely and encrypted.
CSession data will be stored but not encrypted, causing a warning.
DThe app will crash immediately on startup.
Attempts:
2 left
💡 Hint

Think about what Flask requires to sign session cookies.

📝 Syntax
intermediate
1:30remaining
Which code correctly sets a secret key in Flask?

Choose the correct way to set a secret key for a Flask app.

Flask
from flask import Flask
app = Flask(__name__)

# Set secret key here
Aapp.config['SECRET_KEY'] = 'mysecret'
Bapp.secret_key = 'mysecret'
Capp.set_secret_key('mysecret')
Dapp.secretKey = 'mysecret'
Attempts:
2 left
💡 Hint

Flask configuration keys are usually uppercase strings.

❓ state_output
advanced
2:30remaining
What is the output when secret key changes between requests?

Given a Flask app that sets a new random secret key on every request, what happens to the session data?

Flask
from flask import Flask, session
import os

app = Flask(__name__)

@app.before_request
def set_key():
    app.config['SECRET_KEY'] = os.urandom(16)

@app.route('/')
def index():
    session['count'] = session.get('count', 0) + 1
    return f"Count: {session['count']}"

if __name__ == '__main__':
    app.run()
AThe count will increment on each refresh as expected.
BThe count will reset to 1 on every request.
CFlask will raise an error about changing secret key during request.
DThe session will persist but with corrupted data.
Attempts:
2 left
💡 Hint

Think about how Flask uses the secret key to sign session cookies.

🔧 Debug
advanced
2:30remaining
Why does this Flask app's session data not persist?

Review the code below. The session data does not persist between requests. What is the cause?

Flask
from flask import Flask, session
app = Flask(__name__)

app.config['SECRET_KEY'] = 'abc123'

@app.route('/')
def index():
    session['visits'] = session.get('visits', 0) + 1
    return f"Visits: {session['visits']}"

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)
AThe app is running with debug and use_reloader, causing the secret key to reset.
BSession data requires a database backend configured.
CThe session key must be set inside the route function.
DThe secret key is too short and Flask ignores it.
Attempts:
2 left
💡 Hint

Consider what happens when Flask reloads the app in debug mode.

🧠 Conceptual
expert
2:00remaining
Why should Flask's secret key be kept secret and unpredictable?

Choose the best explanation for why Flask's SECRET_KEY must be kept secret and hard to guess.

ABecause it encrypts all data sent to the client, preventing snooping.
BBecause it controls the Flask app's debug mode and error messages.
CBecause it is used to hash passwords stored in the database.
DBecause it signs session cookies to prevent tampering and impersonation.
Attempts:
2 left
💡 Hint

Think about what the secret key is used for in Flask sessions.

Practice

(1/5)
1. What is the main purpose of setting a SECRET_KEY in a Flask application?
easy
A. To secure sessions and cookies by signing them
B. To define the database connection string
C. To set the port number for the Flask server
D. To specify the template folder location

Solution

  1. Step 1: Understand the role of SECRET_KEY in Flask

    The SECRET_KEY is used to sign session cookies and protect data from tampering.
  2. Step 2: Identify the correct purpose

    It does not relate to database, port, or templates but to security of sessions and cookies.
  3. Final Answer:

    To secure sessions and cookies by signing them -> Option A
  4. Quick Check:

    SECRET_KEY secures sessions = A [OK]
Hint: SECRET_KEY protects sessions and cookies [OK]
Common Mistakes:
  • Confusing SECRET_KEY with database settings
  • Thinking SECRET_KEY sets server port
  • Assuming SECRET_KEY defines template paths
2. Which of the following is the correct way to set a secret key in a Flask app?
easy
A. app.secretkey = 'mysecret'
B. app.SECRET_KEY = 'mysecret'
C. app.config['secret_key'] = 'mysecret'
D. app.config['SECRET_KEY'] = 'mysecret'

Solution

  1. Step 1: Recall Flask config key names

    Flask expects the secret key to be set in uppercase as SECRET_KEY in the config dictionary.
  2. Step 2: Check syntax correctness

    Only app.config['SECRET_KEY'] = 'mysecret' uses correct case and syntax.
  3. Final Answer:

    app.config['SECRET_KEY'] = 'mysecret' -> Option D
  4. Quick Check:

    Config keys are uppercase = D [OK]
Hint: Use uppercase 'SECRET_KEY' in app.config [OK]
Common Mistakes:
  • Using lowercase 'secret_key' instead of uppercase
  • Assigning secret_key directly to app object
  • Using wrong attribute names like SECRET_KEY property
3. Given this Flask code snippet, what will print(app.secret_key) output?
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'abc123'
print(app.secret_key)
medium
A. None
B. KeyError
C. 'abc123'
D. AttributeError

Solution

  1. Step 1: Understand Flask secret key access

    app.secret_key is a property that returns the value from app.config['SECRET_KEY'] if set.
  2. Step 2: Check the code execution

    Since app.config['SECRET_KEY'] is set to 'abc123', app.secret_key returns 'abc123' and print outputs abc123 (denoted as "'abc123'" in options).
  3. Final Answer:

    'abc123' -> Option C
  4. Quick Check:

    app.secret_key reads from config['SECRET_KEY'] = A [OK]
Hint: app.secret_key property returns app.config['SECRET_KEY'] [OK]
Common Mistakes:
  • Thinking app.secret_key defaults to None despite config set
  • Expecting KeyError when accessing app.secret_key
  • Expecting AttributeError for app.secret_key
4. Identify the error in this Flask secret key setup:
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ['SECRET']
Assuming os is not imported.
medium
A. SECRET_KEY should be lowercase
B. os module is not imported causing NameError
C. SECRET environment variable is not a valid key name
D. SECRET_KEY must be set after app.run()

Solution

  1. Step 1: Check for missing imports

    The code uses os.environ but does not import the os module, causing a NameError.
  2. Step 2: Validate other options

    SECRET_KEY is case-sensitive and correct as uppercase; environment variable name is valid; setting SECRET_KEY after app.run() is incorrect practice.
  3. Final Answer:

    os module is not imported causing NameError -> Option B
  4. Quick Check:

    Missing import os causes error = A [OK]
Hint: Always import os before using os.environ [OK]
Common Mistakes:
  • Using lowercase 'secret_key' instead of uppercase
  • Assuming environment variable name must be SECRET_KEY
  • Setting SECRET_KEY after app.run()
5. You want to securely set the Flask SECRET_KEY using an environment variable but provide a fallback for development. Which code snippet correctly achieves this?
hard
A. app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev_secret')
B. app.config['SECRET_KEY'] = os.environ['SECRET_KEY'] or 'dev_secret'
C. app.config['SECRET_KEY'] = 'dev_secret' if os.getenv('SECRET_KEY') else os.getenv('SECRET_KEY')
D. app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') and 'dev_secret'

Solution

  1. Step 1: Understand environment variable retrieval methods

    os.getenv('SECRET_KEY', 'dev_secret') returns the environment variable if set, else returns the fallback 'dev_secret'.
  2. Step 2: Analyze other options

    A raises KeyError if missing; C reverses fallback logic ('dev_secret' if set, None if missing); D misuses 'and', returning 'dev_secret' if set, None if missing.
  3. Final Answer:

    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev_secret') -> Option A
  4. Quick Check:

    Use os.getenv with fallback = B [OK]
Hint: Use os.getenv with default fallback for safe secret key [OK]
Common Mistakes:
  • Using os.environ without fallback causing errors
  • Reversing fallback logic in conditional expressions
  • Misusing logical operators for fallback values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard