How to Build a Simple CRUD Application with Flask
Flask is a lightweight web framework for Python that has gained immense popularity due to its simplicity and flexibility. Whether you are a beginner or an experienced developer, building a CRUD (Create, Read, Update, Delete) application with Flask is an excellent way to understand the basics of web development. In this article, we will guide you through the process of creating a simple CRUD application step by step, complete with code examples and actionable insights.
What is a CRUD Application?
A CRUD application allows users to create, read, update, and delete data. It’s a fundamental concept in web development that serves as the backbone for many applications, including content management systems, databases, and more.
Use Cases for CRUD Applications
- Content Management Systems: Manage articles, blogs, and multimedia content.
- Inventory Management: Track products in a warehouse or store.
- User Management: Handle user profiles and authentication.
- Task Management: Organize tasks, projects, or to-do lists.
Setting Up Your Flask Environment
Before diving into the code, you need to set up your development environment. You’ll need Python and Flask installed on your machine.
Step 1: Install Python and Flask
- Install Python: Ensure you have Python 3.x installed. You can download it from the official website.
- Install Flask: Use pip to install Flask by running the following command in your terminal:
bash pip install Flask
Step 2: Create Your Project Structure
Create a directory for your project and navigate into it. Inside, create the following files:
/flask_crud_app
├── app.py
├── templates/
│ ├── index.html
│ ├── add.html
│ ├── edit.html
└── static/
└── style.css
Building the CRUD Application
Step 3: Create the Flask Application
Open app.py
and start by importing the necessary modules:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Step 4: Define the Database Model
Next, define a model for the data you will be managing. For this example, we will create a simple model for a Task
.
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
def __repr__(self):
return f'<Task {self.title}>'
Step 5: Create the Database
Before you can use the database, you need to create it. Add the following to your app.py
file:
@app.before_first_request
def create_tables():
db.create_all()
Step 6: Implement CRUD Functions
Now, let’s implement the CRUD operations.
Create a Task
Add a route to render a form for adding a new task:
@app.route('/add', methods=['GET', 'POST'])
def add_task():
if request.method == 'POST':
task_title = request.form['title']
new_task = Task(title=task_title)
db.session.add(new_task)
db.session.commit()
return redirect(url_for('index'))
return render_template('add.html')
Read Tasks
Next, create a route to display all tasks:
@app.route('/')
def index():
tasks = Task.query.all()
return render_template('index.html', tasks=tasks)
Update a Task
To update a task, create a route that fetches the task by ID and renders a form for editing:
@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit_task(id):
task = Task.query.get_or_404(id)
if request.method == 'POST':
task.title = request.form['title']
db.session.commit()
return redirect(url_for('index'))
return render_template('edit.html', task=task)
Delete a Task
Finally, add a route to delete a task:
@app.route('/delete/<int:id>')
def delete_task(id):
task = Task.query.get_or_404(id)
db.session.delete(task)
db.session.commit()
return redirect(url_for('index'))
Step 7: Create Templates
Now that your routes are set up, let’s create the HTML templates.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task List</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Task List</h1>
<a href="{{ url_for('add_task') }}">Add Task</a>
<ul>
{% for task in tasks %}
<li>
{{ task.title }}
<a href="{{ url_for('edit_task', id=task.id) }}">Edit</a>
<a href="{{ url_for('delete_task', id=task.id) }}">Delete</a>
</li>
{% endfor %}
</ul>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Task</title>
</head>
<body>
<h1>Add Task</h1>
<form method="POST">
<input type="text" name="title" placeholder="Task Title" required>
<button type="submit">Add</button>
</form>
<a href="{{ url_for('index') }}">Back to Task List</a>
</body>
</html>
edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Task</title>
</head>
<body>
<h1>Edit Task</h1>
<form method="POST">
<input type="text" name="title" value="{{ task.title }}" required>
<button type="submit">Update</button>
</form>
<a href="{{ url_for('index') }}">Back to Task List</a>
</body>
</html>
Step 8: Run Your Application
To run your application, add the following at the bottom of your app.py
file:
if __name__ == '__main__':
app.run(debug=True)
Now run the application using the following command in your terminal:
python app.py
Visit http://127.0.0.1:5000/
in your web browser to see your CRUD application in action!
Conclusion
Congratulations! You have successfully built a simple CRUD application using Flask. This application allows users to create, read, update, and delete tasks, demonstrating the essential operations of a web application.
Key Takeaways:
- Flask Framework: Great for building lightweight web applications.
- CRUD Operations: Fundamental for managing data.
- SQLAlchemy: A powerful ORM for database interactions.
By understanding these concepts, you can expand your skills and create more complex applications with Flask. Happy coding!