Building a Simple CRUD Application with Flask
Flask is a lightweight web framework for Python that is perfect for building web applications quickly and efficiently. With its straightforward syntax and minimalist design, Flask allows developers to create simple yet powerful applications. In this article, we’ll walk through the process of building a simple CRUD (Create, Read, Update, Delete) application using Flask. This application will manage a list of items, showcasing the essential features of a CRUD app.
What is a CRUD Application?
CRUD stands for Create, Read, Update, and Delete, which are the four basic operations you can perform on data in a web application. A CRUD application is a software application that allows users to perform these operations on a data model. Common use cases include:
- Task Management Systems: Manage tasks with options to create, view, update, and delete tasks.
- Inventory Systems: Track products, allowing the addition, review, modification, and removal of inventory items.
- User Management: Handle user data with the ability to add, view, edit, and remove user accounts.
Setting Up the Environment
Before diving into the coding, you need to set up your development environment.
Prerequisites
- Python: Ensure you have Python installed (version 3.6 or above is recommended).
- Flask: Install Flask using pip:
bash pip install Flask
- Flask-SQLAlchemy: For database interactions:
bash pip install Flask-SQLAlchemy
Project Structure
Create a new directory for your project and navigate into it:
mkdir flask_crud_app
cd flask_crud_app
Inside this directory, create the following files and directories:
flask_crud_app/
│
├── app.py
└── templates/
├── base.html
├── create.html
├── update.html
└── index.html
Creating the Flask Application
Let’s start by writing the core application logic in app.py
.
Initialize Flask and SQLAlchemy
In app.py
, import Flask and SQLAlchemy, and set up your application:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///items.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
def __repr__(self):
return f'<Item {self.name}>'
db.create_all()
# Home route
@app.route('/')
def index():
items = Item.query.all()
return render_template('index.html', items=items)
if __name__ == '__main__':
app.run(debug=True)
Explanation of Code
- Flask and SQLAlchemy Setup: Import necessary modules and initialize Flask and SQLAlchemy.
- Database Configuration: Use SQLite as the database for simplicity.
- Model Definition: Create an
Item
model representing our data structure. - Create the Database:
db.create_all()
initializes the database and creates the table defined in the model.
Creating the CRUD Operations
Create Item
Add a route to handle item creation. Update app.py
with the following:
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
item_name = request.form['name']
new_item = Item(name=item_name)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('index'))
return render_template('create.html')
Read Items
The home route (index
) already displays all items, as shown in the earlier code.
Update Item
Next, add the ability to update an existing item:
@app.route('/update/<int:item_id>', methods=['GET', 'POST'])
def update(item_id):
item = Item.query.get_or_404(item_id)
if request.method == 'POST':
item.name = request.form['name']
db.session.commit()
return redirect(url_for('index'))
return render_template('update.html', item=item)
Delete Item
Finally, implement the delete operation:
@app.route('/delete/<int:item_id>')
def delete(item_id):
item = Item.query.get_or_404(item_id)
db.session.delete(item)
db.session.commit()
return redirect(url_for('index'))
Creating the HTML Templates
Now, let’s create the HTML templates for our app inside the templates
folder.
Base Template (base.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>
<div class="container">
<h1>Flask CRUD Application</h1>
{% block content %}{% endblock %}
</div>
</body>
</html>
Index Template (index.html
)
{% extends 'base.html' %}
{% block content %}
<a href="{{ url_for('create') }}">Create New Item</a>
<ul>
{% for item in items %}
<li>
{{ item.name }}
<a href="{{ url_for('update', item_id=item.id) }}">Edit</a>
<a href="{{ url_for('delete', item_id=item.id) }}">Delete</a>
</li>
{% endfor %}
</ul>
{% endblock %}
Create and Update Templates
Follow a similar structure for create.html
and update.html
, where you have a form for entering item names.
Create Template (create.html
)
{% extends 'base.html' %}
{% block content %}
<form method="POST">
<input type="text" name="name" placeholder="Item Name" required>
<button type="submit">Add Item</button>
</form>
<a href="{{ url_for('index') }}">Back to Home</a>
{% endblock %}
Update Template (update.html
)
{% extends 'base.html' %}
{% block content %}
<form method="POST">
<input type="text" name="name" value="{{ item.name }}" required>
<button type="submit">Update Item</button>
</form>
<a href="{{ url_for('index') }}">Back to Home</a>
{% endblock %}
Running the Application
To run your application, use the following command in your terminal:
python app.py
Visit http://127.0.0.1:5000/
in your web browser, and you should see your CRUD application in action!
Conclusion
Building a simple CRUD application with Flask provides a solid foundation for understanding web development. This project not only showcases how to manage data but also teaches valuable lessons in structuring applications, handling user inputs, and working with databases. As you advance, consider enhancing this application with user authentication, API integration, or even deploying it to a cloud platform.
With Flask’s flexibility and simplicity, you're well-equipped to expand your skills and create more complex applications in the future. Happy coding!