Bird
Raised Fist0
Flaskframework~20 mins

Flask-SQLAlchemy setup - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask-SQLAlchemy Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask-SQLAlchemy model query?

Given this Flask app and model setup, what will User.query.count() return after adding two users and committing?

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

with app.app_context():
    db.create_all()
    user1 = User(name='Alice')
    user2 = User(name='Bob')
    db.session.add(user1)
    db.session.add(user2)
    db.session.commit()
    count = User.query.count()
A2
B0
C1
DRaises an error because of missing app context
Attempts:
2 left
💡 Hint

Remember that db.create_all() and queries require the app context.

📝 Syntax
intermediate
2:00remaining
Which option correctly initializes Flask-SQLAlchemy with an app factory?

Choose the correct way to set up Flask-SQLAlchemy when using an app factory pattern.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
    # Initialize db here
    return app
Adb.init_app(app) inside create_app before return
Bdb = SQLAlchemy(app) inside create_app
Cdb.create_all() inside create_app before return
Dapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' after return
Attempts:
2 left
💡 Hint

When using app factory, you create the db object outside and initialize it inside.

🔧 Debug
advanced
2:00remaining
Why does this Flask-SQLAlchemy code raise an error?

What error does this code raise and why?

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)

product = Product(name='Book')
db.session.add(product)
db.session.commit()
ARaises AttributeError: 'Product' object has no attribute 'name'
BRaises IntegrityError due to missing primary key
CRaises RuntimeError: Working outside of application context
DNo error, commits successfully
Attempts:
2 left
💡 Hint

Check if the code runs inside the Flask app context.

❓ state_output
advanced
2:00remaining
What is the value of user.email after this code runs?

Consider this Flask-SQLAlchemy model and code snippet. What will user.email be?

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=True)

with app.app_context():
    db.create_all()
    user = User(username='john')
    db.session.add(user)
    db.session.commit()
    user = User.query.first()
ARaises AttributeError
BNone
CEmpty string ''
D'john@example.com'
Attempts:
2 left
💡 Hint

Check the default value of email when not set.

🧠 Conceptual
expert
2:00remaining
Which statement best describes Flask-SQLAlchemy's session behavior?

Choose the most accurate description of how Flask-SQLAlchemy manages database sessions.

AIt shares a single global session object across all threads without isolation.
BIt creates a new session for each query and closes it immediately after.
CIt requires manual session creation and closing for every database operation.
DIt uses a scoped session tied to the Flask app context to handle concurrent requests safely.
Attempts:
2 left
💡 Hint

Think about how Flask handles multiple requests and how SQLAlchemy sessions should behave.

Practice

(1/5)
1. What is the main purpose of Flask-SQLAlchemy in a Flask application?
easy
A. To create HTML templates for the Flask app
B. To connect the Flask app to a database and manage data easily
C. To handle user authentication and sessions
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand Flask-SQLAlchemy role

    Flask-SQLAlchemy is a tool that helps Flask apps talk to databases easily.
  2. Step 2: Compare with other options

    Options B, C, and D relate to other Flask features, not database connection.
  3. Final Answer:

    To connect the Flask app to a database and manage data easily -> Option B
  4. Quick Check:

    Flask-SQLAlchemy = database connection [OK]
Hint: Flask-SQLAlchemy is about databases, not templates or files [OK]
Common Mistakes:
  • Confusing Flask-SQLAlchemy with template engines
  • Thinking it manages user sessions
  • Assuming it serves static files
2. Which of the following is the correct way to initialize Flask-SQLAlchemy in your Flask app?
easy
A. db = SQLAlchemy(app)
B. db = SQLAlchemy() db.init_app(appp)
C. db = SQLAlchemy(appp)
D. db = SQLAlchemy(app=Flask())

Solution

  1. Step 1: Recall initialization pattern

    The simplest and most common way is to pass the app directly to SQLAlchemy constructor: db = SQLAlchemy(app).
  2. Step 2: Check other options

    db = SQLAlchemy() db.init_app(appp) uses undefined 'appp'. db = SQLAlchemy(appp) uses undefined 'appp'. db = SQLAlchemy(app=Flask()) creates a new Flask app, not the existing one.
  3. Final Answer:

    db = SQLAlchemy(app) -> Option A
  4. Quick Check:

    Direct app in constructor = db = SQLAlchemy(app) [OK]
Hint: Pass your Flask app directly to SQLAlchemy() for quick setup [OK]
Common Mistakes:
  • Trying to pass app as a keyword argument incorrectly
  • Creating a new Flask app inside SQLAlchemy
  • Forgetting to link SQLAlchemy to the app
3. Given this Flask-SQLAlchemy model and code, what will print(user.name) output?
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

with app.app_context():
    db.create_all()
    user = User(name='Alice')
    db.session.add(user)
    db.session.commit()

print(user.name)
medium
A. Empty string
B. None
C. Alice
D. Error: No such attribute

Solution

  1. Step 1: Understand model and data insertion

    The User model has a name field. We create a user with name 'Alice' and add it to the database.
  2. Step 2: Check what user.name holds after commit

    After committing, the user object still has the name 'Alice' stored in its attribute.
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    User.name after commit = 'Alice' [OK]
Hint: Committed model instances keep their attribute values accessible [OK]
Common Mistakes:
  • Assuming user.name becomes None after commit
  • Thinking print causes a database query error
  • Confusing model attribute with database column name
4. What is wrong with this Flask-SQLAlchemy setup code?
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy()
db.init_app(app)

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

product = Product(name='Book')
db.session.add(product)
db.session.commit()
medium
A. Missing app.app_context() when adding and committing
B. SQLALCHEMY_DATABASE_URI is incorrect
C. Product model lacks a __tablename__ attribute
D. db = SQLAlchemy() should be db = SQLAlchemy(app)

Solution

  1. Step 1: Check app context usage

    When using db.init_app(app), database operations must be inside app.app_context() to access app config.
  2. Step 2: Verify other parts

    The URI is valid, __tablename__ is optional, and db = SQLAlchemy() with init_app is valid. The missing app context causes runtime error.
  3. Final Answer:

    Missing app.app_context() when adding and committing -> Option A
  4. Quick Check:

    Database ops need app context [OK]
Hint: Wrap DB actions in app.app_context() if using init_app() [OK]
Common Mistakes:
  • Ignoring app context requirement with init_app()
  • Thinking __tablename__ is always required
  • Confusing init_app() with passing app in constructor
5. You want to create a Flask app with Flask-SQLAlchemy that uses PostgreSQL. Which steps correctly set up the database URI and initialize the app and database? Choose the correct sequence.
hard
A. Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(appp)
B. Set app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'; then db = SQLAlchemy(app)
C. Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(); no init_app call
D. Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(); db.init_app(app)

Solution

  1. Step 1: Set correct PostgreSQL URI

    The URI must start with 'postgresql://' and include user, password, host, and database name.
  2. Step 2: Initialize SQLAlchemy properly

    Using db = SQLAlchemy() then db.init_app(app) is a flexible pattern, especially for larger apps.
  3. Step 3: Check other options

    Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(appp) uses undefined 'appp'; Set app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'; then db = SQLAlchemy(app) uses SQLite, not PostgreSQL; Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(); no init_app call misses init_app call, so db won't link to app.
  4. Final Answer:

    Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(); db.init_app(app) -> Option D
  5. Quick Check:

    PostgreSQL URI + init_app() = Set app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/dbname'; then db = SQLAlchemy(); db.init_app(app) [OK]
Hint: Use init_app() with PostgreSQL URI for flexible setup [OK]
Common Mistakes:
  • Using SQLite URI when PostgreSQL is needed
  • Forgetting to call init_app() after creating db without app
  • Passing app to SQLAlchemy but using wrong URI format
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