Table of Contents
- Introduction
- Prerequisites
- Overview
- Setting up the Project
- Creating the Database
- Creating the Task Class
- Adding New Tasks
- Listing Tasks
- Updating Task Status
- Deleting Tasks
- Conclusion
Introduction
In this tutorial, we will learn how to build a task management app using Python and SQLite. The app will allow users to add, list, update, and delete tasks. By the end of this tutorial, you will have a working task management app that you can use or customize according to your needs.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming language and object-oriented programming concepts. You should also have Python installed on your machine.
Overview
We will use SQLite, a lightweight database engine, to store our task data. Python provides a built-in SQLite module that allows us to interact with the SQLite database. We will create a Task class to represent a single task and use various SQLite queries to perform CRUD (Create, Read, Update, Delete) operations on the tasks.
Here are the main steps we will cover in this tutorial:
- Setting up the project.
- Creating the database.
- Creating the Task class.
- Adding new tasks.
- Listing tasks.
- Updating task status.
- Deleting tasks.
Let’s get started!
Setting up the Project
Before we start coding, let’s set up our project directory. Create a new directory named “task_manager” and navigate into it using the command line.
bash
mkdir task_manager
cd task_manager
Next, create a new Python virtual environment inside the “task_manager” directory:
bash
python3 -m venv env
Activate the virtual environment:
bash
source env/bin/activate
Creating the Database
To create the database, we will use the SQLite module provided by Python. Create a new Python file named “database.py” inside the “task_manager” directory. ```python # database.py
import sqlite3
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
# Create the tasks table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL
)
""")
conn.close()
``` In the above code, we import the `sqlite3` module and connect to the database "tasks.db". We also create a cursor object that allows us to execute SQL queries on the database. We use the cursor to execute a SQL query that creates a "tasks" table if it doesn't already exist. The "tasks" table has four columns: id (auto-incremented primary key), title (task title), description (task description), and status (task status).
To create the database and table, run the following command in your terminal:
bash
python3 database.py
Creating the Task Class
Next, let’s create a Task class that represents a single task. Create a new Python file named “task.py” inside the “task_manager” directory. ```python # task.py
class Task:
def __init__(self, title, description):
self.title = title
self.description = description
self.status = "Pending"
``` The Task class has an `__init__` method that takes two parameters: title and description. It initializes the instance variables `self.title`, `self.description`, and `self.status` with the provided values. The default status is set to "Pending".
Adding New Tasks
To add a new task, we need to insert a new row into the “tasks” table in the database. Let’s update the Task class to include a method for adding tasks. ```python # task.py
class Task:
def __init__(self, title, description):
self.title = title
self.description = description
self.status = "Pending"
def save(self):
import sqlite3
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO tasks (title, description, status)
VALUES (?, ?, ?)
""", (self.title, self.description, self.status))
conn.commit()
conn.close()
``` In the updated `Task` class, we have added a `save` method that inserts a new task into the "tasks" table. We use parameterized queries to ensure safe and secure database operations. After executing the insert query, we commit the changes and close the database connection.
Listing Tasks
Let’s add a method to the Task class that retrieves all the tasks from the database and returns them as a list of Task objects. ```python # task.py
class Task:
# ...
@staticmethod
def get_all_tasks():
import sqlite3
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM tasks")
rows = cursor.fetchall()
tasks = []
for row in rows:
task = Task(row[1], row[2])
task.status = row[3]
tasks.append(task)
conn.close()
return tasks
``` In the updated `Task` class, we have added a `get_all_tasks` static method that retrieves all the tasks from the "tasks" table using a SELECT query. We iterate over the returned rows, create Task objects from the data, and append them to a list. Finally, we close the database connection and return the list of tasks.
Updating Task Status
To update the status of a task, we need to execute an UPDATE query on the “tasks” table. Let’s add a method to the Task class for updating the status. ```python # task.py
class Task:
# ...
def update_status(self, new_status):
import sqlite3
self.status = new_status
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("UPDATE tasks SET status = ? WHERE title = ?", (self.status, self.title))
conn.commit()
conn.close()
``` In the updated `Task` class, we have added an `update_status` method that takes a `new_status` parameter. It updates the `self.status` variable with the new status and executes an UPDATE query on the "tasks" table to update the status of the task with a matching title. We commit the changes and close the database connection.
Deleting Tasks
To delete a task, we need to execute a DELETE query on the “tasks” table. Let’s add a method to the Task class for deleting tasks. ```python # task.py
class Task:
# ...
def delete(self):
import sqlite3
conn = sqlite3.connect("tasks.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM tasks WHERE title = ?", (self.title,))
conn.commit()
conn.close()
``` In the updated `Task` class, we have added a `delete` method that executes a DELETE query on the "tasks" table to delete the task with a matching title. We commit the changes and close the database connection.
Conclusion
In this tutorial, we have learned how to build a task management app using Python and SQLite. We created a Task class to represent a single task and used SQLite queries to perform CRUD operations on the tasks. By following this tutorial, you should now have a basic understanding of how to work with databases in Python and build simple data-driven applications.
You can further enhance the app by adding more features such as task due dates, priority levels, or user authentication. Feel free to explore the SQLite documentation and Python’s built-in SQLite module for more advanced database operations. ```python # main.py
from task import Task
# Create a new task
task1 = Task("Buy groceries", "Don't forget milk and eggs!")
task1.save()
# Create another task
task2 = Task("Finish coding assignment", "Finish the assignment before the deadline")
task2.save()
# Get all tasks
tasks = Task.get_all_tasks()
for task in tasks:
print(task.title)
# Update task status
task1.update_status("Completed")
# Delete a task
task2.delete()
``` That's it! You have successfully built a task management app in Python using SQLite. Feel free to experiment with different functionalities and customize the app according to your requirements.
Happy coding!