building-a-crud-application-with-flask.html

Building a CRUD Application with Flask

Flask is a lightweight web framework for Python that allows developers to create web applications quickly and efficiently. One of the most common types of applications is a CRUD (Create, Read, Update, Delete) application, which enables users to manage data easily. In this article, we will explore how to build a simple CRUD application using Flask. We will cover definitions, use cases, and provide actionable insights, along with code examples and step-by-step instructions.

What is a CRUD Application?

A CRUD application is a software application that allows users to perform four basic operations on data:

  • Create: Adding new records.
  • Read: Retrieving and displaying existing records.
  • Update: Modifying existing records.
  • Delete: Removing records.

CRUD applications are ubiquitous in web development and can be used for various purposes, such as managing databases, user profiles, or any data-driven application.

Use Cases for CRUD Applications

CRUD applications can be applied in numerous scenarios, including:

  • Content Management Systems (CMS): Manage articles, images, and other media.
  • E-commerce Platforms: Handle product listings, customer accounts, and orders.
  • Task Management Tools: Create and manage tasks or projects.
  • Social Media Platforms: Manage user profiles, posts, and comments.

Setting Up Your Flask Environment

Before we start coding, we need to set up our development environment. Follow these steps:

  1. Install Python: Ensure you have Python installed. You can download it from python.org.

  2. Create a Virtual Environment: It’s a good practice to create a virtual environment for your project.

bash python -m venv venv

  1. Activate the Virtual Environment:

  2. On Windows: bash venv\Scripts\activate

  3. On macOS/Linux: bash source venv/bin/activate

  4. Install Flask:

bash pip install Flask

Creating Your First Flask Application

Now that we have our environment set up, let’s create a basic Flask application.

Step 1: Setting Up the Application Structure

Create a directory for your project and navigate into it. Inside the directory, create the following files:

  • app.py
  • templates/
  • static/

Step 2: Writing the Flask Application Code

Open app.py and write the following code:

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

app = Flask(__name__)

# Sample data to simulate a database
tasks = []

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

@app.route('/add', methods=['POST'])
def add_task():
    task = request.form['task']
    tasks.append(task)
    return redirect(url_for('index'))

@app.route('/delete/<int:task_id>')
def delete_task(task_id):
    tasks.pop(task_id)
    return redirect(url_for('index'))

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

Step 3: Creating HTML Templates

Under the templates/ directory, create a file named index.html and add the following 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 Application</title>
</head>
<body>
    <h1>Task List</h1>
    <form action="/add" method="POST">
        <input type="text" name="task" placeholder="Enter a new task" required>
        <button type="submit">Add Task</button>
    </form>
    <ul>
        {% for task in tasks %}
            <li>
                {{ task }} 
                <a href="/delete/{{ loop.index0 }}">Delete</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

Step 4: Running the Application

Run the application by executing the following command in your terminal:

python app.py

You should see output indicating that the server is running. Open your browser and navigate to http://127.0.0.1:5000/ to view your CRUD application.

Enhancing the CRUD Functionality

While the above example is functional, you might want to enhance your application by adding features such as:

  • Persistent Data Storage: Use a database like SQLite or PostgreSQL to store tasks permanently.
  • User Authentication: Implement login and registration features to secure the application.
  • Form Validation: Add form validation to ensure data integrity.

Example of Adding SQLite for Persistent Storage

To use SQLite, follow these steps:

  1. Install Flask-SQLAlchemy:

bash pip install Flask-SQLAlchemy

  1. Update your app.py to include database functionality:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

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

class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200), nullable=False)

@app.before_first_request
def create_tables():
    db.create_all()

# ... (rest of your code remains mostly the same)
  1. Update the /add and /delete routes to interact with the database instead of the list.

Troubleshooting Common Issues

  • Flask Not Starting: Ensure that your virtual environment is activated and Flask is installed.
  • Database Issues: Check your database URI and ensure you have permissions to create or write to the database.
  • HTML Rendering Issues: Make sure your HTML files are placed in the correct directory (templates/).

Conclusion

Building a CRUD application with Flask is a great way to get started with web development using Python. By following the steps outlined in this article, you can create a functional application that allows users to manage data efficiently. With enhancements like persistent storage and user authentication, you can take your application to the next level. 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.