Setting Up a Database in Flask
Key Concepts
- Database Management Systems (DBMS)
- Object-Relational Mapping (ORM)
- Flask-SQLAlchemy
- Database Models
- Database Operations
1. Database Management Systems (DBMS)
A Database Management System (DBMS) is software that allows users to define, create, maintain, and control access to the database. Common DBMS include MySQL, PostgreSQL, SQLite, and MongoDB.
2. Object-Relational Mapping (ORM)
Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. ORM libraries, like SQLAlchemy, map database tables to Python classes and their instances.
3. Flask-SQLAlchemy
Flask-SQLAlchemy is an extension for Flask that simplifies the use of SQLAlchemy within Flask applications. It provides a simple interface to configure and interact with databases.
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db' db = SQLAlchemy(app)
4. Database Models
Database models are Python classes that represent database tables. Each attribute of the class corresponds to a column in the table. Models define the structure and relationships of the data.
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 f'User({self.username}, {self.email})'
5. Database Operations
Database operations include creating, reading, updating, and deleting (CRUD) records. Flask-SQLAlchemy provides methods to perform these operations seamlessly.
# Create a new user new_user = User(username='john_doe', email='john@example.com') db.session.add(new_user) db.session.commit() # Read users users = User.query.all() # Update a user user = User.query.filter_by(username='john_doe').first() user.email = 'john.doe@example.com' db.session.commit() # Delete a user user = User.query.filter_by(username='john_doe').first() db.session.delete(user) db.session.commit()