0
0
Flaskframework~10 mins

Creating tables (db.create_all) in Flask - Visual Walkthrough

Choose your learning style9 modes available
Concept Flow - Creating tables (db.create_all)
Define Models
Initialize Flask App
Configure Database URI
Create SQLAlchemy db Object
Call db.create_all()
Tables Created in Database
App Ready to Use Database
This flow shows how Flask app models are defined, then db.create_all() creates corresponding tables in the database.
Execution Sample
Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
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()
This code defines a User model and creates its table in the SQLite database using db.create_all().
Execution Table
StepActionEvaluationResult
1Define User modelUser inherits db.Model with id and name columnsModel ready for table creation
2Initialize Flask appapp createdApp object ready
3Set database URIURI set to sqlite:///test.dbConfig ready for DB connection
4Create SQLAlchemy db objectdb linked to appdb object ready to manage models
5Enter app contextapp.app_context() activeContext allows DB operations
6Call db.create_all()Checks models and creates tables if missingUser table created in test.db
7Exit app contextContext closedApp ready to use database tables
💡 All defined models have corresponding tables created in the database.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 6Final
appNoneNoneFlask app instanceFlask app instanceFlask app instance
dbNoneNoneSQLAlchemy instance linked to appSQLAlchemy instance linked to appSQLAlchemy instance linked to app
UserNoneModel class definedModel class definedModel class definedModel class defined
Database TablesEmptyEmptyEmptyUser table createdUser table created
Key Moments - 2 Insights
Why do we need to call db.create_all() inside app.app_context()?
Because Flask needs an active app context to know which app and database to use. Without it, db.create_all() cannot access the app configuration (see execution_table step 5 and 6).
Does db.create_all() delete existing tables before creating new ones?
No, db.create_all() only creates tables that do not exist. It does not delete or modify existing tables (see execution_table step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of the database tables after step 4?
ANo tables created yet
BUser table created
CAll tables deleted
DTables partially created
💡 Hint
Check the 'Database Tables' variable in variable_tracker after step 4.
At which step does the User table get created in the database?
AStep 3
BStep 5
CStep 6
DStep 7
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table for when db.create_all() is called.
If we forget to enter app.app_context(), what will happen when calling db.create_all()?
ATables will still be created
BAn error will occur due to missing app context
CTables will be deleted
DNothing happens, silently fails
💡 Hint
Refer to key_moments about the importance of app context for db.create_all().
Concept Snapshot
Define your models as classes inheriting db.Model.
Initialize Flask app and configure database URI.
Create SQLAlchemy db object linked to app.
Use app.app_context() to activate context.
Call db.create_all() to create tables for all models.
Existing tables are not deleted or modified.
Full Transcript
In Flask, to create database tables, you first define your models as Python classes inheriting from db.Model. Then you initialize your Flask app and set the database URI in the app configuration. Next, you create a SQLAlchemy db object linked to your app. To perform database operations like creating tables, you must enter the app context using app.app_context(). Inside this context, calling db.create_all() will create tables in the database for all models that do not already have tables. This process does not delete or modify existing tables. After this, your app is ready to use the database tables.