Building a Basic CRUD Application with Flask
Flask is a micro web framework for Python that allows developers to build web applications quickly and efficiently. Its lightweight nature and simplicity make it an excellent choice for beginners and experienced developers alike. In this article, we will guide you through building a basic CRUD (Create, Read, Update, Delete) application using Flask. This application will serve as a foundation for understanding how to manage data in web applications.
What is CRUD?
CRUD stands for Create, Read, Update, and Delete. These four operations are the basic functions of persistent storage and are essential for any application that interacts with a database. Here's a quick overview of each operation:
- Create: Adding new records to the database.
- Read: Retrieving existing records from the database.
- Update: Modifying existing records in the database.
- Delete: Removing records from the database.
Use Cases for CRUD Applications
CRUD applications are prevalent in various domains, including:
- Content Management Systems (CMS): Manage articles, blogs, or media.
- Inventory Management: Track products and stock levels.
- User Management: Handle user profiles and permissions.
- Task Management: Organize tasks or projects.
Tools You'll Need
Before we dive into coding, ensure you have the following tools installed:
- Python: Version 3.6 or higher.
- Flask: Install via pip using the command
pip install Flask
. - SQLite: This comes pre-installed with Python.
Step-by-Step Guide to Building a CRUD Application with Flask
Step 1: Setting Up Your Project
Create a new directory for your project and navigate into it:
mkdir flask_crud_app
cd flask_crud_app
Next, create a virtual environment and activate it:
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
Now, install Flask:
pip install Flask
Step 2: Project Structure
Organize your project files as follows:
flask_crud_app/
│
├── app.py
├── templates/
│ ├── create.html
│ ├── read.html
│ ├── update.html
│ └── index.html
└── static/
└── style.css
Step 3: Creating the Flask Application
Open app.py
and start by importing the necessary libraries:
from flask import Flask, render_template, request, redirect, url_for
import sqlite3
Next, create your Flask application and configure the SQLite database:
app = Flask(__name__)
def get_db_connection():
conn = sqlite3.connect('database.db')
conn.row_factory = sqlite3.Row
return conn
Step 4: Setting Up the Database
Create a database and a table for our CRUD application:
def init_db():
conn = get_db_connection()
conn.execute('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)')
conn.commit()
conn.close()
init_db()
Step 5: Create Functionality
Now, let’s implement the Create functionality. Add the following route to app.py
:
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
name = request.form['name']
conn = get_db_connection()
conn.execute('INSERT INTO items (name) VALUES (?)', (name,))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('create.html')
Step 6: Read Functionality
Next, implement the Read operation by adding the following route:
@app.route('/')
def index():
conn = get_db_connection()
items = conn.execute('SELECT * FROM items').fetchall()
conn.close()
return render_template('index.html', items=items)
Step 7: Update Functionality
Add an update route to modify existing records:
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
conn = get_db_connection()
item = conn.execute('SELECT * FROM items WHERE id = ?', (id,)).fetchone()
if request.method == 'POST':
name = request.form['name']
conn.execute('UPDATE items SET name = ? WHERE id = ?', (name, id))
conn.commit()
conn.close()
return redirect(url_for('index'))
conn.close()
return render_template('update.html', item=item)
Step 8: Delete Functionality
Finally, implement the Delete operation:
@app.route('/delete/<int:id>')
def delete(id):
conn = get_db_connection()
conn.execute('DELETE FROM items WHERE id = ?', (id,))
conn.commit()
conn.close()
return redirect(url_for('index'))
Step 9: Creating Templates
Create the necessary HTML templates in the templates
folder. Here’s a simple example for index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CRUD Application</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<h1>Items</h1>
<a href="{{ url_for('create') }}">Create New Item</a>
<ul>
{% for item in items %}
<li>{{ item['name'] }} <a href="{{ url_for('update', id=item['id']) }}">Edit</a> <a href="{{ url_for('delete', id=item['id']) }}">Delete</a></li>
{% endfor %}
</ul>
</body>
</html>
Step 10: Run Your Application
Finally, add the run command at the bottom of app.py
:
if __name__ == '__main__':
app.run(debug=True)
Run your application with:
python app.py
Conclusion
Congratulations! You’ve built a basic CRUD application using Flask. This foundational project can be expanded with more features, such as user authentication, input validation, and API integration. As you continue to explore Flask, remember to optimize your code for performance and troubleshoot any issues that arise along the way.
Creating a CRUD application is an excellent way to understand how web applications interact with databases, and Flask provides a powerful yet simple framework to help you get started. Happy coding!