Build a simple web application with a database backend using a framework of your choice…
- User
Build a simple web application with a database backend using a framework of your choice (e.g., Flask, Django)
Assistant
Build a simple web application with a database backend using a framework of your choice (e.g., Flask, Django)
The user wants me to build a simple web application with a database backend. They gave me the freedom to choose the framework (e.g., Flask, Django).
Choice of Framework:
Flask-SQLAlchemy for the DB).Jinja2 support makes it easy).Decision: I will choose Flask with SQLite (via Flask-SQLAlchemy).
settings.py, urls.py, models.py, views.py, etc.).Application Idea: A "To-Do List" is the classic "Hello World" for database-backed apps. It covers CRUD (Create, Read, Update, Delete).
Plan:
app.py: Main application logic.templates/: Folder for HTML.
index.html: The frontend.app.py:
flask, flask_sqlalchemy).Todo class: id, content, completed).GET /: Show list.POST /add: Add item.GET /delete/<id>: Delete item.GET /update/<id>: Update status.app.run).index.html:
Drafting the Content:
pip install flask flask-sqlalchemyapp.py.
db.create_all() needs to be run in an application context. I should explain how to do that in the Python shell or add a specific command. For simplicity in a tutorial, I'll include a with app.app_context(): db.create_all() block or instructions to run it manually. Actually, putting it inside if __name__ == "__main__": before app.run() is the easiest "copy-paste-run" approach for beginners, though not production-standard.templates/index.html. Use Jinja2 syntax.Refining the Flask Code:
Flask-SQLAlchemy version 3.x syntax (which is stricter about contexts).Alternative Consideration: Should I use SQLite directly? No, an ORM (SQLAlchemy) is much better practice and easier to read.
Final Output Structure:
app.py (Backend + DB Model).templates/index.html (Frontend).Let's write the code mentally first to check for errors.
db = SQLAlchemy(app)
class Todo(db.Model): ...
@app.route('/') -> query all.
@app.route('/add', methods=['POST']) -> form handling.
Looks solid. I will implement the "To-Do List".
Self-Correction during drafting:
If I use db.create_all() inside the main block, it might run every time. It's fast enough for SQLite to not matter for a demo.
I should probably stick to the standard practice: tell the user to open a python shell to create the DB, OR provide a function/command. To make it "simple" as requested, I will use a trick: check if the db file exists, if not create it. Or just instruct the user to run python and from app import db etc.
Better approach for a tutorial: Instruct the user to run a specific command in the terminal or create the tables in the script before app.run.
Let's go with the Flask solution.
Steps:
pip install Flask Flask-SQLAlchemyapp.pytemplates/index.htmlLet's write the response. Here is a complete, step-by-step guide to building a simple To-Do List web application.
I have chosen Flask (a Python micro-framework) because it is lightweight, easy for beginners to understand, and perfect for small projects. We will use SQLite for the database because it requires no installation (it runs as a simple file on your computer).
You need Python installed on your computer. You will also need to install Flask and SQLAlchemy (an library to manage the database).
Open your terminal or command prompt and run:
pip install Flask Flask-SQLAlchemy
Create a folder for your project (e.g., todo_app). Inside, create the following files structure:
todo_app/
│
├── app.py # The main backend logic
└── templates/ # Folder for HTML files
└── index.html # The frontend design
app.py)This file handles the server, connects to the database, and processes user input (adding/deleting tasks).
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Configuration for the SQLite database
# The database file will be created automatically in the instance folder
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize the database
db = SQLAlchemy(app)
# -- Database Model --
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed = db.Column(db.Boolean, default=False)
def __repr__(self):
return f'<Task {self.id}>'
# -- Routes --
@app.route('/')
def index():
# Fetch all tasks from the database
tasks = Todo.query.all()
return render_template('index.html', tasks=tasks)
@app.route('/add', methods=['POST'])
def add():
task_content = request.form['content']
if not task_content:
return redirect(url_for('index'))
# Create a new Todo object
new_task = Todo(content=task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect(url_for('index'))
except:
return 'There was an issue adding your task'
@app.route('/delete/<int:id>')
def delete(id):
task_to_delete = Todo.query.get_or_404(id)
try:
db.session.delete(task_to_delete)
db.session.commit()
return redirect(url_for('index'))
except:
return 'There was a problem deleting that task'
@app.route('/update/<int:id>')
def update(id):
task = Todo.query.get_or_404(id)
try:
# Toggle the completion status
task.completed = not task.completed
db.session.commit()
return redirect(url_for('index'))
except:
return 'There was an issue updating your task'
if __name__ == "__main__":
# Create the database tables within the application context
with app.app_context():
db.create_all()
app.run(debug=True)
templates/index.html)Flask looks for HTML files in the templates folder. Create index.html inside that folder.
This uses Jinja2 syntax (the curly braces {{ }} and {% %}) to inject data from Python into the HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Todo App</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
h1 { color: #333; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { padding: 10px; border-bottom: 1px solid #ddd; text-align: left; }
.completed { text-decoration: line-through; color: #888; }
form { display: flex; gap: 10px; }
input[type="text"] { flex-grow: 1; padding: 8px; }
input[type="submit"] { padding: 8px 16px; background-color: #28a745; color: white; border: none; cursor: pointer; }
.btn-del { color: red; text-decoration: none; margin-left: 10px; }
.btn-done { color: blue; text-decoration: none; }
</style>
</head>
<body>
<h1>My Todo List</h1>
<form action="/add" method="POST">
<input type="text" name="content" placeholder="Enter a task..." required>
<input type="submit" value="Add Task">
</form>
<table>
<thead>
<tr>
<th>Task</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for task in tasks %}
<tr>
<!-- If task is completed, add the 'completed' class -->
<td class="{{ 'completed' if task.completed else '' }}">
{{ task.content }}
</td>
<td>
<a href="/update/{{ task.id }}" class="btn-done">
{{ "Undo" if task.completed else "Done" }}
</a>
<a href="/delete/{{ task.id }}" class="btn-del">Delete</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="2">No tasks yet. Add one above!</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
cd todo_app).python app.py
http://127.0.0.1:5000).python app.py, the db.create_all() command checks if todo.db exists. If not, it creates it based on your Todo class structure./), the index function queries the database for all tasks and sends them to the HTML template./add. Python captures the text, creates a new database row, saves it, and refreshes the page./delete/1) trigger the specific Python functions associated with that ID to modify the database.