Flask Library SQLAlchemy

SQLAlchemy is a popular SQL toolkit and Object-Relational Mapping (ORM) library for Python. It provides a set of high-level API for connecting to relational databases and performing database operations. In this example, we’ll look at how to use the Flask-SQLAlchemy library, a Flask extension that adds support for SQLAlchemy to your Flask application.

First, let’s start by installing the Flask-SQLAlchemy library using pip:

pip install flask-sqlalchemy

Next, we’ll create a new Flask application and initialize the Flask-SQLAlchemy extension in our application. Here’s an example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

In the code above, we first imported the Flask and Flask-SQLAlchemy libraries. Then we created a new Flask application and defined the database URI for our SQLite database. The database URI is a string that defines the database type and location. In this example, we’re using a SQLite database located in a file named test.db.

Once we have initialized the Flask-SQLAlchemy extension, we can start defining our database models. A database model is a Python class that represents a database table. Here’s an example of a simple database model:

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 the code above, we defined a User model that has three columns: id, username, and email. The id column is defined as an integer and is set as the primary key. The username and email columns are defined as strings with a maximum length of 80 and 120 characters, respectively.

Once we have defined our database models, we can start using them to perform database operations. For example, we can use the following code to add a new user to the database:

new_user = User(username='john', email='john@example.com')
db.session.add(new_user)
db.session.commit()

In the code above, we created a new User object, added it to the database using the db.session.add method, and then committed the changes to the database using the db.session.commit method.

We can also use the Flask-SQLAlchemy library to query the database. For example, we can use the following code to retrieve all users from the database:

users = User.query.all()
for user in users:
    print(user.username, user.email)

In the code above, we used the User.query.all method to retrieve all users from the database. Then, we looped through the list of users and printed their username and email.

In conclusion, the Flask-SQLAlchemy library makes it easy to work