In this section, we will delve into the core operations of interacting with a database using Flask-SQLAlchemy: Create, Read, Update, and Delete (CRUD). These operations are fundamental for any web application that manages data.

Key Concepts

  1. Create: Adding new records to the database.
  2. Read: Retrieving data from the database.
  3. Update: Modifying existing records in the database.
  4. Delete: Removing records from the database.

Setting Up

Before we start, ensure you have Flask-SQLAlchemy installed and configured. If not, refer to the previous section on Introduction to Flask-SQLAlchemy.

Example Model

Let's assume we have a simple User model defined as follows:

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)

    def __repr__(self):
        return f'<User {self.username}>'

Create Operation

To add a new user to the database, you need to create an instance of the User model and add it to the session.

Code Example

@app.route('/create_user', methods=['POST'])
def create_user():
    username = request.form['username']
    email = request.form['email']
    new_user = User(username=username, email=email)
    
    db.session.add(new_user)
    db.session.commit()
    
    return f"User {new_user.username} has been created successfully."

Explanation

  1. Create an Instance: new_user = User(username=username, email=email)
  2. Add to Session: db.session.add(new_user)
  3. Commit the Session: db.session.commit()

Read Operation

To retrieve data, you can use various query methods provided by SQLAlchemy.

Code Example

@app.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    return jsonify([{'username': user.username, 'email': user.email} for user in users])

Explanation

  1. Query All Users: users = User.query.all()
  2. Return Data: Convert the list of users to JSON format.

Update Operation

To update an existing record, you first need to retrieve it, modify its attributes, and then commit the changes.

Code Example

@app.route('/update_user/<int:id>', methods=['POST'])
def update_user(id):
    user = User.query.get(id)
    if user:
        user.username = request.form['username']
        user.email = request.form['email']
        db.session.commit()
        return f"User {user.username} has been updated successfully."
    else:
        return "User not found."

Explanation

  1. Retrieve User: user = User.query.get(id)
  2. Modify Attributes: user.username = request.form['username']
  3. Commit Changes: db.session.commit()

Delete Operation

To delete a record, retrieve it and then delete it from the session.

Code Example

@app.route('/delete_user/<int:id>', methods=['POST'])
def delete_user(id):
    user = User.query.get(id)
    if user:
        db.session.delete(user)
        db.session.commit()
        return f"User {user.username} has been deleted successfully."
    else:
        return "User not found."

Explanation

  1. Retrieve User: user = User.query.get(id)
  2. Delete from Session: db.session.delete(user)
  3. Commit Changes: db.session.commit()

Practical Exercise

Task

  1. Create a new route to add a user.
  2. Create a new route to list all users.
  3. Create a new route to update a user's email.
  4. Create a new route to delete a user.

Solution

Refer to the code examples provided above for each CRUD operation.

Common Mistakes and Tips

  1. Forgetting to Commit: Always remember to commit the session after adding, updating, or deleting records.
  2. Handling Non-Existent Records: Always check if the record exists before performing update or delete operations.
  3. Session Management: Be cautious with session management to avoid issues like stale data or session conflicts.

Conclusion

In this section, we covered the essential CRUD operations using Flask-SQLAlchemy. These operations form the backbone of any data-driven web application. In the next section, we will explore database migrations with Flask-Migrate to manage changes in your database schema effectively.

© Copyright 2024. All rights reserved