To use an ORM in Flask, install the required packages:
pip3 install sqlalchemy flask-sqlalchemy
Create a MySQL database for your application:
CREATE DATABASE flask DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
Configure the database URI in your Flask app:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost:3306/flask'
Initialize the SQLAlchemy extension:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
Define models by subclassing db.Model. Each class represents a table:
class User(db.Model):
__tablename__ = 'users' # Optional; defaults to lowercase class name
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), index=True, default='')
Common column types include:
Integer→intString(size)→strText→strBoolean→boolDateTime→datetime.datetimeFloat→float
Column options:
primary_key=True: marks as primary keyautoincrement=True: enables auto-incrementunique=True: enforces uniquenessnullable=False: disallows NULL valuesindex=True: adds a database indexdefault=value: sets a default value
For managing schema changes, use Flask-Migrate instead of db.create_all() or db.drop_all().
Set up migration support:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
Run these commands once to initialize migrations:
python3 app.py db init
Generate a migration script after modifying models:
python3 app.py db migrate -m "Add user table"
Apply the migration to the daatbase:
python3 app.py db upgrade