Creating the Database (db.create_all)
When you have models, you need to create tables.
For quick demos, you can use db.create_all()db.create_all().
Example
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
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(80), unique=True, nullable=False)
with app.app_context():
db.create_all()from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
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(80), unique=True, nullable=False)
with app.app_context():
db.create_all()Why app.app_context()?
Database operations often need the Flask application context.
Important warning
db.create_all()db.create_all():
- creates missing tables
- does not handle schema changes safely over time
Thatβs why real apps use migrations (Flask-Migrate).
Use create_all()create_all() for:
- learning
- small prototypes
Use migrations for:
- anything you deploy
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
