Creating models
Flask is a popular Python web framework known for its simplicity, flexibility, and fine-grained control. One of the most important aspects of developing a Flask application is creating models for your data. Models define the structure of your database tables and the relationships between them.
Before we begin, make sure Flask-SQLAlchemy and Flask-Migrate are installed in your environment. They are essential for working with databases in Flask.
pip install flask-sqlalchemy flask-migrate
Initializing Flask-SQLAlchemy
Flask-SQLAlchemy is an extension that simplifies the use of SQLAlchemy, an Object Relational Mapper (ORM), with Flask. To initialize it in your Flask application, add the following code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
In the above code, SQLALCHEMY_DATABASE_URI
is the configuration key for setting the database URI. In this case, we're using SQLite, which is a simple file-based database.
Creating Models
Models in Flask are Python classes that inherit from db.Model
. Each attribute of the class represents a field in the table. Here's an example of a model for a User:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
In this model, id
is an integer that serves as the primary key, username
and email
are strings that must be unique and cannot be null.
The __repr__
method is a special method that returns a string representation of the object, which can be useful for debugging.
Creating Tables
After defining your models, you need to create the corresponding tables in the database. Flask-Migrate makes this easy with the db.create_all()
command:
db.create_all()
Interacting with the Database
You can interact with the database using the methods provided by SQLAlchemy. Here are some basic operations:
- Creating a new user:
user = User(username='admin', email='[email protected]')
db.session.add(user)
db.session.commit()
- Querying for users:
users = User.query.all()
- Getting a user by their username:
user = User.query.filter_by(username='admin').first()
- Updating a user:
user.email = '[email protected]'
db.session.commit()
- Deleting a user:
db.session.delete(user)
db.session.commit()
Remember to always commit your changes if you want them to persist.
Congratulations, you've just created your first Flask model! With this knowledge, you can start building more complex applications with databases.