Python Programming: Building a To-Do List App with Flask

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the Flask App
  5. Creating the Database
  6. Creating the Routes
  7. Creating the Templates
  8. Adding Functionality
  9. Testing the App
  10. Conclusion

Introduction

In this tutorial, we will guide you through the process of building a To-Do List App using the Flask web framework in Python. By the end of this tutorial, you will have a functional web application where users can create, view, update, and delete tasks in their to-do list.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming and web development concepts. Familiarity with HTML, CSS, and Flask will be helpful but not required.

Setup

To begin, make sure you have Python and Flask installed on your machine. You can install Flask using pip, the package manager for Python, by running the following command in your terminal: bash pip install flask

Creating the Flask App

First, let’s create a new directory for our project. Open your terminal and navigate to the desired location where you want to create the app. Then, run the following command to create a new directory: bash mkdir todoapp Navigate into the newly created directory: bash cd todoapp Now, let’s create a new Python file for our Flask app: bash touch app.py Open the app.py file in your favorite text editor and add the following import statements: python from flask import Flask, render_template, request, redirect Next, create an instance of the Flask class and define a route for the root URL (“/”) that will render the home page template: ```python app = Flask(name)

@app.route('/')
def home():
    return render_template('home.html')
``` Save the changes and close the file.

Creating the Database

Before we can start creating the routes and templates, let’s create a SQLite database to store the tasks for our to-do list.

In the same directory as the app.py file, create a new file called database.db. This file will serve as our SQLite database.

Creating the Routes

Now, let’s create the routes that will handle the different functionalities of our to-do list app.

Route for Creating a Task

Inside the app.py file, add the following route to handle the creation of a new task: python @app.route('/create', methods=['POST']) def create(): if request.method == 'POST': task = request.form['task'] # Add code to insert the task into the database return redirect('/') This route expects a POST request with a form parameter named task, which represents the new task to be created. Inside the route function, we retrieve the task from the request form and insert it into the database. Finally, we redirect the user back to the home page.

Route for Viewing Tasks

Add the following route to handle the rendering of the tasks on the home page: python @app.route('/') def home(): # Fetch tasks from database tasks = [] # Add code to fetch tasks from the database return render_template('home.html', tasks=tasks) Inside this route, we fetch all the tasks from the database and pass them to the render_template function along with the name of the template file (home.html). We also pass the tasks as a variable to the template so that we can display them on the home page.

Route for Updating a Task

To handle the update functionality, add the following route: python @app.route('/update/<int:task_id>', methods=['POST']) def update(task_id): if request.method == 'POST': task = request.form['task'] # Add code to update the task in the database return redirect('/') This route expects a POST request with a form parameter named task and a route parameter named task_id, which represents the ID of the task to be updated. Inside the route function, we retrieve the updated task from the request form and update the corresponding task in the database. Finally, we redirect the user back to the home page.

Route for Deleting a Task

Lastly, add the route for deleting a task: python @app.route('/delete/<int:task_id>') def delete(task_id): # Add code to delete the task from the database return redirect('/') This route expects a GET request with a route parameter named task_id, which represents the ID of the task to be deleted. Inside the route function, we delete the corresponding task from the database. Finally, we redirect the user back to the home page.

Save the changes made to the app.py file.

Creating the Templates

Now, let’s create the templates that will be used to render the different pages of our to-do list app.

Inside the templates directory, create a new file called home.html. In this file, add the following HTML code: ```html <!DOCTYPE html> <html>

<head>
    <title>To-Do List</title>
</head>

<body>
    <h1>To-Do List</h1>
    <form action="/create" method="POST">
        <input type="text" name="task" placeholder="Enter a task">
        <button type="submit">Add Task</button>
    </form>

    <ul>
        
    </ul>
</body>

</html>
``` The above HTML code includes a form to create a new task, a loop to iterate over the tasks and display them, and options to update and delete each task.

Save the changes made to the home.html file.

Adding Functionality

Let’s add the missing functionality to the routes in the app.py file.

Creating a Task

Inside the create route, add the following code to insert the task into the database: ```python import sqlite3

# ...

conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO tasks (description) VALUES (?)', (task,))
conn.commit()
conn.close()
``` ### Fetching Tasks

Inside the home route, add the following code to fetch the tasks from the database: python conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute('SELECT description FROM tasks') tasks = [task[0] for task in cursor.fetchall()] conn.close()

Updating a Task

Inside the update route, add the following code to update the task in the database: python conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute('UPDATE tasks SET description = ? WHERE ROWID = ?', (task, task_id)) conn.commit() conn.close()

Deleting a Task

Inside the delete route, add the following code to delete the task from the database: python conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute('DELETE FROM tasks WHERE ROWID = ?', (task_id,)) conn.commit() conn.close() Save the changes made to the app.py file.

Testing the App

To test the app, open your terminal and navigate to the todoapp directory. Then, run the following command to start the Flask development server: bash python app.py Open your web browser and visit http://localhost:5000 to access the To-Do List app. You should be able to create, view, update, and delete tasks on the home page.

Conclusion

Congratulations! You have successfully built a To-Do List app with Flask. In this tutorial, we covered the basics of building a web application using Flask and SQLite. You learned how to create routes, handle form submissions, interact with a database, and render templates.

Feel free to explore further and add more features to your app, such as user authentication or task prioritization. Flask offers a lot of flexibility and additional functionality that you can leverage to enhance your To-Do List app.

Remember to refer to the Flask documentation and other resources for more advanced topics and best practices in web development with Flask.

Keep coding, and happy Flask-ing!