📜  Flask – SQLAlchemy(1)

📅  最后修改于: 2023-12-03 14:41:13.498000             🧑  作者: Mango

Flask - SQLAlchemy

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. SQLAlchemy is a SQL toolkit and ORM (Object Relational Mapper) that provides a set of high-level API that greatly simplifies database manipulation in Python.

Installation

To install Flask-SQLAlchemy, run the following command:

pip install Flask-SQLAlchemy
Configuration

Before using the extension in your project, you need to create an instance of the SQLAlchemy class and define the database connection settings. For example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/mydatabase'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

In the code above, we are setting the SQLALCHEMY_DATABASE_URI configuration variable to the connection string of the PostgreSQL database named mydatabase.

We also set the SQLALCHEMY_TRACK_MODIFICATIONS configuration variable to False to disable the modification tracker, which can be a performance penalty if not required.

Defining Models

In SQLAlchemy, database tables are represented by Python classes called models. Each model class is a subclass of the db.Model class provided by Flask-SQLAlchemy.

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

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)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<User %r>' % self.username

In the code above, we defined a User model class that represents a database table with id, username, email, and created_at columns.

Querying Data

To query data from the database, we can use the db.session object provided by Flask-SQLAlchemy.

from myapp.models import User

# Get all user objects
users = User.query.all()

# Get the first user object
user = User.query.first()

# Filter users by username
users = User.query.filter_by(username='john').all()

# Get the number of users
users_count = User.query.count()

In the code above, we show examples of querying data using Flask-SQLAlchemy's API.

Conclusion

Flask-SQLAlchemy is a powerful SQLAlchemy extension that simplifies database manipulation in Flask. With this extension, you can easily define models, query data, and perform database migrations.