Welcome, future web developers and productivity enthusiasts! Ever wanted to keep track of your tasks and projects in a simple, custom way? Today, we’re going to embark on an exciting journey to build a very basic project management tool using Flask. Flask is a wonderful tool that makes building web applications easy and fun, especially for beginners.
What is Flask?
First things first, what exactly is Flask?
Flask is what we call a “micro web framework” for Python.
* Web Framework: Think of a web framework as a toolkit that provides a structure and common utilities to build web applications. Instead of starting from scratch every time you want to create a website, a framework gives you many components already built.
* Micro: This “micro” part means Flask aims to keep the core simple but allows you to add more features as your project grows. It doesn’t force you into specific ways of doing things, giving you a lot of flexibility.
Flask is written in Python, which is a very popular and beginner-friendly programming language. Its simplicity makes it perfect for quickly getting a web application up and running.
Why Build a Project Management Tool?
Building a project management tool, even a simple one, is a fantastic way to learn how web applications work. You’ll grasp fundamental concepts like:
* Handling requests from your web browser.
* Displaying information (like your tasks).
* Taking input from users (like adding a new task).
* Structuring a basic web project.
Plus, you’ll end up with a functional tool that you can expand and customize to fit your own needs!
Getting Started: Setting Up Your Environment
Before we write any code, we need to set up our development environment. Think of this as preparing your workspace.
1. Install Python
If you don’t have Python installed, please download it from the official website (python.org). Make sure to check the box that says “Add Python to PATH” during installation. This makes it easier to run Python commands from your terminal.
2. Create a Project Folder
Let’s create a new folder for our project. You can name it my_project_manager.
mkdir my_project_manager
cd my_project_manager
3. Set Up a Virtual Environment
A virtual environment is a really important concept.
* Virtual Environment: Imagine you’re working on multiple Python projects, and each project needs slightly different versions of the same library. A virtual environment creates an isolated space for each project. This means the libraries you install for one project won’t interfere with another. It keeps your projects neat and tidy!
Let’s create and activate one:
python -m venv venv
.\venv\Scripts\activate
source venv/bin/activate
You’ll notice (venv) appears at the beginning of your terminal prompt, indicating that your virtual environment is active.
4. Install Flask
Now that our environment is ready, let’s install Flask using pip.
* pip: This is Python’s package installer. It’s how you download and install Python libraries (like Flask) that other people have created.
pip install Flask
Great! You’re all set to start coding.
Building the Core Application (app.py)
In your my_project_manager folder, create a new file named app.py. This will be the heart of our application.
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
tasks = []
task_id_counter = 1 # To give each task a unique ID
@app.route('/', methods=['GET', 'POST'])
def index():
global task_id_counter # We need to modify the global counter
if request.method == 'POST':
# If the user submitted the form (POST request)
task_content = request.form['content'] # Get the task description from the form
if task_content: # Make sure the task isn't empty
tasks.append({'id': task_id_counter, 'content': task_content, 'completed': False})
task_id_counter += 1
return redirect(url_for('index')) # Redirect back to the homepage to see the updated list
# If the user just visited the page (GET request)
# render_template looks for an HTML file in a 'templates' folder.
return render_template('index.html', tasks=tasks)
@app.route('/complete/<int:task_id>')
def complete_task(task_id):
for task in tasks:
if task['id'] == task_id:
task['completed'] = not task['completed'] # Toggle completion status
break
return redirect(url_for('index'))
@app.route('/delete/<int:task_id>')
def delete_task(task_id):
global tasks
tasks = [task for task in tasks if task['id'] != task_id] # Create a new list excluding the deleted task
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
Let’s break down some concepts in app.py:
* from flask import Flask, render_template, request, redirect, url_for: We’re importing specific parts of Flask that we need.
* Flask: The main class to create our web application.
* render_template: A function to display HTML files.
* request: An object that holds information about the incoming request (like data submitted from a form).
* redirect: A function to send the user to a different URL.
* url_for: A function that helps build URLs for our routes.
* app = Flask(__name__): This line creates our Flask application instance. The __name__ part helps Flask locate resources like templates.
* @app.route('/'): This is a “decorator.”
* Decorator: A decorator is a special kind of function that modifies another function. Here, @app.route('/') tells Flask that when a user goes to the root URL (/), it should run the index() function right below it.
* methods=['GET', 'POST']: This tells Flask that our / route can handle two types of HTTP requests:
* GET: When you simply visit a page to view content.
* POST: When you submit data, like filling out a form.
* tasks = []: For simplicity, we’re storing our tasks in a Python list. In a real-world application, you’d use a database to store this information permanently. But for now, this works perfectly for learning.
* render_template('index.html', tasks=tasks): This is how we display our web pages. Flask will look for a file named index.html inside a special templates folder and pass our tasks list to it so the HTML can display them.
Creating Your HTML Templates
Flask expects your HTML files to be in a folder named templates right inside your project directory.
Create a folder named templates in your my_project_manager folder:
mkdir templates
Now, inside the templates folder, create a file named index.html.
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Simple Project Manager</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
h1 { color: #0056b3; }
form { margin-bottom: 20px; background-color: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
input[type="text"] { width: calc(100% - 100px); padding: 10px; margin-right: 10px; border: 1px solid #ddd; border-radius: 4px; }
button { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background-color: #0056b3; }
ul { list-style: none; padding: 0; }
li { background-color: #fff; margin-bottom: 10px; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); display: flex; justify-content: space-between; align-items: center; }
li.completed { text-decoration: line-through; color: #888; }
.actions a { text-decoration: none; margin-left: 10px; padding: 5px 10px; border-radius: 4px; }
.actions .complete { background-color: #28a745; color: white; }
.actions .delete { background-color: #dc3545; color: white; }
.actions a:hover { opacity: 0.9; }
</style>
</head>
<body>
<h1>My Project Tasks</h1>
<form method="POST">
<input type="text" name="content" placeholder="Add a new task..." required>
<button type="submit">Add Task</button>
</form>
<h2>Current Tasks</h2>
<ul>
{# This is a Jinja2 loop to iterate over the 'tasks' list we passed from Flask #}
{% for task in tasks %}
<li class="{% if task.completed %}completed{% endif %}">
<span>{{ task.content }}</span>
<div class="actions">
<a href="{{ url_for('complete_task', task_id=task.id) }}" class="complete">
{% if task.completed %}Uncomplete{% else %}Complete{% endif %}
</a>
<a href="{{ url_for('delete_task', task_id=task.id) }}" class="delete">Delete</a>
</div>
</li>
{% else %}
<li>No tasks yet! Add one above.</li>
{% endfor %}
</ul>
</body>
</html>
In index.html:
* We’re using a templating engine called Jinja2 (which Flask uses by default).
* Lines like {% for task in tasks %} are special Jinja2 syntax to loop through the tasks list that we passed from app.py.
* {{ task.content }} displays the actual content of each task.
* url_for('complete_task', task_id=task.id) generates the correct URL for our Flask routes, making it easy to link actions to specific tasks.
Running Your Application
You’ve written the code! Now let’s see it in action.
- Make sure your virtual environment is still active (
(venv)should be in your terminal prompt). -
In your
my_project_managerdirectory, run:bash
flask runYou should see output similar to this:
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit -
Open your web browser and go to
http://127.0.0.1:5000.
Congratulations! You should now see your very own simple project management tool. You can add tasks, mark them as complete, and delete them. Remember, since we’re not using a database yet, your tasks will disappear if you stop and restart the server.
Next Steps and Further Improvements
This is just the beginning! Here are some ideas to take your tool further:
- Database Integration: Instead of a simple list, integrate a database like SQLite (which is very easy to use with Flask and SQLAlchemy) to store your tasks permanently.
- User Authentication: Add the ability for different users to log in and manage their own tasks.
- More Features: Add due dates, priorities, project categories, or even a simple calendar view.
- Better Styling: Enhance the look and feel with a CSS framework like Bootstrap.
- Deployment: Learn how to deploy your application to a real server so others can use it.
Conclusion
You’ve successfully built a foundational web application using Flask! You’ve learned how to set up your environment, define routes, handle user input, and display dynamic content. Flask’s simplicity and Python’s power make it an excellent choice for developing all sorts of web projects. Keep experimenting, keep building, and enjoy your journey in web development!
Leave a Reply
You must be logged in to post a comment.