How to create a simple CRUD application in Flask

How to Create a Simple CRUD Application in Flask

Flask is a lightweight web framework for Python that is often chosen for its simplicity and flexibility. It's an excellent option for developers looking to create web applications quickly and efficiently. In this article, we will walk you through the process of creating a simple CRUD (Create, Read, Update, Delete) application using Flask. CRUD applications are fundamental in web development as they allow users to manage data effectively. By the end of this tutorial, you will have a basic Flask application up and running that can perform all four CRUD operations.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that you can perform on data in a database. Here’s a quick overview:

  • Create: Add new data to the database.
  • Read: Retrieve and display data from the database.
  • Update: Modify existing data in the database.
  • Delete: Remove data from the database.

Use Cases for a CRUD Application

CRUD applications are ubiquitous in web development and can be used for various purposes, including:

  • Content Management Systems (CMS): For managing articles, blogs, or product listings.
  • User Management Platforms: For handling user registrations, profiles, and permissions.
  • Inventory Management: To track stock levels, product details, and pricing.

With that in mind, let’s dive into building a simple CRUD application using Flask!

Setting Up Your Flask Environment

Before we start coding, ensure you have Python and Flask installed on your machine. You can follow these steps to set up your environment:

  1. Install Python (if you haven't already):
  2. Download and install Python from python.org.

  3. Create a Virtual Environment: bash python -m venv venv

  4. Activate the Virtual Environment:

  5. On Windows: bash venv\Scripts\activate
  6. On macOS/Linux: bash source venv/bin/activate

  7. Install Flask: bash pip install Flask

Creating the Flask Application

Step 1: Setting Up the Application Structure

Create a directory structure like this:

/flask_crud_app
    ├── app.py
    ├── templates
    │   ├── index.html
    │   ├── create.html
    │   └── edit.html
    └── static

Step 2: Create the Flask Application

In the app.py file, start by importing Flask and setting up a basic application:

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# Sample data to simulate a database
posts = []

@app.route('/')
def index():
    return render_template('index.html', posts=posts)

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

Step 3: Creating the HTML Templates

index.html

Create a file in the templates folder named index.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 App</title>
</head>
<body>
    <h1>My Posts</h1>
    <a href="{{ url_for('create') }}">Create New Post</a>
    <ul>
    {% for post in posts %}
        <li>{{ post['title'] }} - <a href="{{ url_for('edit', post_id=loop.index0) }}">Edit</a> | <a href="{{ url_for('delete', post_id=loop.index0) }}">Delete</a></li>
    {% endfor %}
    </ul>
</body>
</html>

create.html

Create another file named create.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Post</title>
</head>
<body>
    <h1>Create a New Post</h1>
    <form action="{{ url_for('create') }}" method="post">
        <input type="text" name="title" placeholder="Post Title" required>
        <textarea name="content" placeholder="Post Content" required></textarea>
        <button type="submit">Create</button>
    </form>
</body>
</html>

edit.html

Create the final template as edit.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Post</title>
</head>
<body>
    <h1>Edit Post</h1>
    <form action="{{ url_for('edit', post_id=post_id) }}" method="post">
        <input type="text" name="title" value="{{ post['title'] }}" required>
        <textarea name="content" required>{{ post['content'] }}</textarea>
        <button type="submit">Update</button>
    </form>
</body>
</html>

Step 4: Implementing CRUD Operations

Now, let's add the functionality to handle the CRUD operations in app.py.

@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        posts.append({'title': title, 'content': content})
        return redirect(url_for('index'))
    return render_template('create.html')

@app.route('/edit/<int:post_id>', methods=['GET', 'POST'])
def edit(post_id):
    if request.method == 'POST':
        posts[post_id]['title'] = request.form['title']
        posts[post_id]['content'] = request.form['content']
        return redirect(url_for('index'))
    return render_template('edit.html', post=posts[post_id], post_id=post_id)

@app.route('/delete/<int:post_id>')
def delete(post_id):
    posts.pop(post_id)
    return redirect(url_for('index'))

Step 5: Run the Application

Finally, run your application using the command:

python app.py

You can now access your CRUD application by navigating to http://127.0.0.1:5000 in your web browser.

Conclusion

Congratulations! You’ve successfully created a simple CRUD application using Flask. This basic structure can be expanded with additional features like user authentication, database integration, and more. Flask is a powerful framework that provides the flexibility to build complex applications with ease.

Final Tips for Optimization and Troubleshooting

  • Use a Database: For a production application, consider integrating a database like SQLite or PostgreSQL to store your data persistently.
  • Error Handling: Implement error handling to manage exceptions and provide user-friendly feedback.
  • Code Organization: As your application grows, consider organizing your code into Blueprints for better maintainability.

By following these steps, you now have a solid foundation to build upon and enhance your Flask skills. 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.