creating-a-simple-crud-application-with-flask-and-sqlalchemy.html

Creating a Simple CRUD Application with Flask and SQLAlchemy

In today’s digital landscape, understanding how to build a web application is a crucial skill for developers. One of the most common types of applications is a CRUD (Create, Read, Update, Delete) application, which allows users to manage data effectively. In this article, we will delve into creating a simple CRUD application using Flask, a lightweight web framework for Python, and SQLAlchemy, an ORM (Object Relational Mapper) that facilitates database interactions.

What is Flask?

Flask is a micro web framework for Python that is designed to make web development easy and straightforward. It is lightweight and modular, allowing developers to build applications with ease. Flask is perfect for small to medium-sized applications and comes with a built-in development server, making it a popular choice among developers.

What is SQLAlchemy?

SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) system for Python. It allows developers to interact with databases using Python objects instead of SQL queries, making database manipulation more intuitive and manageable. SQLAlchemy supports multiple database backends, making it versatile for various applications.

Use Cases for a CRUD Application

A CRUD application can serve numerous purposes, including:

  • Content Management Systems: Manage articles, blogs, and user-generated content.
  • Inventory Management: Track products, stock levels, and orders.
  • User Management: Handle user profiles, registrations, and authentication.
  • Task Management: Create to-do lists or project management tools.

Now, let’s dive into building a simple CRUD application using Flask and SQLAlchemy.

Step-by-Step Guide to Building a CRUD Application

Prerequisites

Before we start, ensure you have the following installed:

  • Python 3.x
  • Flask
  • Flask-SQLAlchemy

You can install Flask and Flask-SQLAlchemy using pip:

pip install Flask Flask-SQLAlchemy

Setting Up the Project Structure

Create a new directory for your project and set up the following structure:

flask_crud/
│
├── app.py
├── models.py
└── templates/
    ├── home.html
    └── add.html

Step 1: Setting Up the Flask Application

In app.py, we will initialize the Flask application and set up the SQLAlchemy database connection.

from flask import Flask, render_template, redirect, url_for, request
from models import db, Item

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///items.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

with app.app_context():
    db.create_all()

@app.route('/')
def home():
    items = Item.query.all()
    return render_template('home.html', items=items)

if __name__ == '__main__':
    app.run(debug=True)

Step 2: Defining the Database Model

Next, we need to define our data model in models.py. For this example, we will create a simple Item model.

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(200), nullable=True)

    def __repr__(self):
        return f'<Item {self.name}>'

Step 3: Creating the CRUD Functionality

Now we will implement the functionality to create, read, update, and delete items.

Create Item

Add a route to handle the creation of new items.

@app.route('/add', methods=['GET', 'POST'])
def add_item():
    if request.method == 'POST':
        item_name = request.form['name']
        item_description = request.form['description']
        new_item = Item(name=item_name, description=item_description)

        db.session.add(new_item)
        db.session.commit()
        return redirect(url_for('home'))

    return render_template('add.html')

Read Items

The home route already fetches and displays all items from the database.

Update Item

To update an item, create a new route:

@app.route('/edit/<int:item_id>', methods=['GET', 'POST'])
def edit_item(item_id):
    item = Item.query.get_or_404(item_id)
    if request.method == 'POST':
        item.name = request.form['name']
        item.description = request.form['description']
        db.session.commit()
        return redirect(url_for('home'))

    return render_template('edit.html', item=item)

Delete Item

Create a route for deleting items:

@app.route('/delete/<int:item_id>')
def delete_item(item_id):
    item = Item.query.get_or_404(item_id)
    db.session.delete(item)
    db.session.commit()
    return redirect(url_for('home'))

Step 4: Creating HTML Templates

Now, let’s create the HTML templates for displaying and adding items.

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask CRUD</title>
</head>
<body>
    <h1>Items</h1>
    <a href="{{ url_for('add_item') }}">Add Item</a>
    <ul>
        {% for item in items %}
        <li>
            {{ item.name }} - {{ item.description }}
            <a href="{{ url_for('edit_item', item_id=item.id) }}">Edit</a>
            <a href="{{ url_for('delete_item', item_id=item.id) }}">Delete</a>
        </li>
        {% endfor %}
    </ul>
</body>
</html>

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Item</title>
</head>
<body>
    <h1>Add Item</h1>
    <form method="POST">
        <input type="text" name="name" placeholder="Item Name" required>
        <textarea name="description" placeholder="Item Description"></textarea>
        <button type="submit">Add</button>
    </form>
    <a href="{{ url_for('home') }}">Back</a>
</body>
</html>

Conclusion

Congratulations! You have successfully created a simple CRUD application using Flask and SQLAlchemy. This application allows you to create, read, update, and delete items stored in a SQLite database.

Troubleshooting Tips

  • Database Issues: Ensure your SQLite database file is accessible and that you have the correct permissions.
  • Flask Configuration: Verify that your Flask application is running in debug mode for easier troubleshooting during development.

By mastering CRUD operations in Flask, you can build dynamic web applications tailored to various needs. Consider expanding this basic application by adding user authentication, improving the UI, or integrating more complex data models. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.