Consider a Flask app using SQLAlchemy. What does db.create_all() do when executed?
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()
Think about what create_all() means literally and how it behaves with existing tables.
db.create_all() creates tables for all models that do not yet exist in the database. It does not drop or delete existing tables.
Which of the following code snippets correctly calls db.create_all() in a Flask app context?
from flask_sqlalchemy import SQLAlchemy from flask import Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80))
Remember that db.create_all() needs to run inside the Flask app context.
Calling db.create_all() requires the Flask app context to be active. Using with app.app_context(): ensures this.
You added a new model to your Flask app but db.create_all() does not create its table. What is the most likely cause?
class Order(db.Model): id = db.Column(db.Integer, primary_key=True) item = db.Column(db.String(100)) # After adding this, you run: with app.app_context(): db.create_all()
Think about how SQLAlchemy knows about models when creating tables.
SQLAlchemy only creates tables for models it knows about. If the new model is not imported or registered before db.create_all(), its table won't be created.
Given a Flask app with a model User, what happens if you call db.create_all() two times in a row inside the app context?
with app.app_context():
db.create_all()
db.create_all()Consider how create_all() behaves with existing tables.
db.create_all() creates tables only if they do not exist. Calling it multiple times does not recreate or drop tables.
Explain why db.create_all() must be called inside with app.app_context(): in a Flask application.
Think about what the app context provides to Flask extensions like SQLAlchemy.
The app context provides access to the app's configuration and database connection. Without it, db.create_all() cannot access the database properly.