跳到正文
DEV Community· Hanieh Khanmohamad·· 37 分鐘前AI 評分30

使用 Python 和 SQLite 建立可靠的家居保養提醒工具

Build a Reliable Home Maintenance Reminder with Python and SQLite

AI 導讀

這篇教學以 Python 和 SQLite 建立本機家居保養追蹤工具,記錄定期任務、計算到期日期、列出逾期項目及保存實際完成日期。工具按日曆月份計算週期,並以實際完成日期推算下次到期日;它只用 Python 標準程式庫,毋須帳戶、雲端 API 或第三方套件。

正文

A reminder app can be impressive in a demo and unreliable in an actual home. Consider a water filter that was supposed to be checked every three months. You might complete the job two weeks late. Should the next reminder be calculated from the old deadline or from the day the work was actually done? Now add an air-conditioner inspection, a smoke-alarm test, and a refrigerator-coil cleaning schedule. A simple calendar alert is suddenly a data-modeling problem.

This tutorial builds a small, local-first home maintenance tracker with Python and SQLite. It stores recurring tasks, calculates dates using calendar months, reports overdue items, and records actual completion dates. It uses only the Python standard library and requires no account, cloud API, or third-party package.

The project is intentionally modest. We want a design we can inspect and test, not a system that quietly makes unreliable assumptions about household safety or personal data.
Define the behavior before writing code
A recurring task needs at least five pieces of information:

  • A name, such as “Check water filter.”
  • A location or category, such as “Kitchen.”
  • A recurrence interval, measured in calendar months.
  • The date of the most recent completed inspection or service.
  • A stable database identifier so a completed task can be updated without guessing which record was intended. For this project, the next due date is derived from the last real completion date. If a task was due on April 15 but you did it on May 1, its next three-month deadline becomes August 1. That is a deliberate product decision: it models maintenance carried out periodically after actual work. Some safety schedules or warranty agreements instead require fixed deadlines. Those must be modeled differently, according to their real requirements.

We also define the meaning of an alert. If today's date is November 26 and an inspection was due November 10, it is overdue by 16 days. A task due within the next 30 days is upcoming. Everything later remains hidden from the short list, without deleting it from storage.
Why calendar months matter
“Three months” is not interchangeable with “90 days.” Months vary in length, and calendar dates such as January 31 need a policy. If we add one calendar month to January 31, there is no February 31. We will clamp the result to the last valid day of the destination month. In a leap year, January 31 plus one month becomes February 29; otherwise, February 28.

The calculation always starts with last_done, not with the previously calculated deadline. That avoids accumulating drift from repeatedly adding intervals to dates already clamped by shorter months.

A date object is sufficient for a household task recorded by day. We do not invent an hour of service, and we avoid time-zone conversions because there is no time-of-day field to convert. A notification service with exact delivery times would require a more explicit time-zone model.
Choose a small, auditable storage model
SQLite is a useful starting point because it is transactional, requires no database server, and keeps the data in a single local file. Our schema has one tasks table. An integer primary key identifies each task; a positive interval protects against zero-month recurrence; the last completion date is stored as an ISO-formatted string such as 2026-08-10.

An important distinction: local-first does not automatically mean encrypted. Someone with access to the file may be able to read it. Store the database in an appropriate private directory, use operating-system account protections, and consider encrypted backups when the information is sensitive. This example also does not sync between devices.

Database parameters are passed through SQLite placeholders (?), not assembled into SQL strings. That prevents user-entered task names from becoming part of a SQL command.
A complete command-line implementation
Save the following code as home_maintenance.py and run it with Python 3.10 or newer. It creates its database on first use. There is no package installation step.
"""A small local-first home maintenance scheduler (Python 3.10+)."""
import argparse
import calendar
import sqlite3
from datetime import date, timedelta
from pathlib import Path

def add_months(day: date, months: int) -> date:
"""Add calendar months, clamping short months (Jan 31 -> Feb 28/29)."""
if months < 1:
raise ValueError("The interval must be at least one month")
offset = day.year * 12 + (day.month - 1) + months
year, zero_based_month = divmod(offset, 12)
month = zero_based_month + 1
return date(year, month, min(day.day, calendar.monthrange(year, month)[1]))

def open_db(path: Path) -> sqlite3.Connection:
connection = sqlite3.connect(path)
connection.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
area TEXT NOT NULL,
interval_months INTEGER NOT NULL CHECK (interval_months >= 1),
last_done TEXT NOT NULL
)
""")
connection.commit()
return connection

def add_task(conn, title: str, area: str, interval: int, last_done: str) -> None:
date.fromisoformat(last_done)
if interval < 1 or not title.strip() or not area.strip():
raise ValueError("Supply a title, area, and a positive month interval")
with conn:
conn.execute(
"INSERT INTO tasks(title, area, interval_months, last_done) VALUES (?, ?, ?, ?)",
(title.strip(), area.strip(), interval, last_done),
)

def upcoming(conn, today: date, window_days: int = 30):
if window_days < 0:
raise ValueError("The look-ahead window cannot be negative")
items = []
for task_id, title, area, interval, last_done in conn.execute(
"SELECT id, title, area, interval_months, last_done FROM tasks"
):
due = add_months(date.fromisoformat(last_done), interval)
if due <= today + timedelta(days=window_days):
days = (due - today).days
label = "overdue" if days < 0 else "due today" if days == 0 else "upcoming"
items.append((due, task_id, title, area, label, days))
return sorted(items)

def mark_done(conn, task_id: int, finished: str) -> None:
date.fromisoformat(finished)
with conn:
cursor = conn.execute(
"UPDATE tasks SET last_done = ? WHERE id = ?", (finished, task_id)
)
if cursor.rowcount == 0:
raise ValueError(f"No task with ID {task_id}")

def main() -> None:
parser = argparse.ArgumentParser(description="Private home maintenance reminders")
parser.add_argument("--db", type=Path, default=Path("home_maintenance.sqlite3"))
commands = parser.add_subparsers(dest="command", required=True)
add = commands.add_parser("add")
add.add_argument("title")
add.add_argument("area")
add.add_argument("interval_months", type=int)
add.add_argument("last_done", help="YYYY-MM-DD")
listing = commands.add_parser("list")
listing.add_argument("--within", type=int, default=30)
listing.add_argument("--today", default=date.today().isoformat())
done = commands.add_parser("done")
done.add_argument("id", type=int)
done.add_argument("--date", default=date.today().isoformat())
args = parser.parse_args()
with open_db(args.db) as conn:
try:
if args.command == "add":
add_task(conn, args.title, args.area, args.interval_months, args.last_done)
print("Saved")
elif args.command == "done":
mark_done(conn, args.id, args.date)
print("Completion recorded")
else:
for due, task_id, title, area, label, days in upcoming(
conn, date.fromisoformat(args.today), args.within
):
print(f"#{task_id} | {due} | {label:9} | {area} | {title} ({days:+} days)")
except ValueError as error:
parser.error(str(error))

if name == "main":
main()
Try it with a realistic example
Add a water-filter inspection last completed on August 10, 2026. The interval is three months:
python home_maintenance.py add "Check water filter" Kitchen 3 2026-08-10
Now ask what was due as of November 26, 2026. The optional --today switch is primarily useful for testing and reproducible examples; omit it during normal use:
python home_maintenance.py list --today 2026-11-26
You should get a record whose due date is November 10 and whose status is overdue. The tool also prints a task ID. To record a completion on November 26, use that ID (shown here as 1 in a fresh database):
python home_maintenance.py done 1 --date 2026-11-26
python home_maintenance.py list --today 2026-11-26
The task disappears from the default 30-day view because its new due date is February 26, 2027. It still exists in SQLite. If you add more tasks, the ID need not be 1, so always read the actual list output.

To inspect a longer planning horizon, use python home_maintenance.py list --within 120. The look-ahead window changes the view, not the stored due date.
Test the awkward cases first
Date calculations are a classic source of plausible-looking bugs. A short unit test can check that the algorithm does what the product specification says:
from datetime import date
from home_maintenance import add_months

assert add_months(date(2025, 1, 31), 1) == date(2025, 2, 28)
assert add_months(date(2024, 1, 31), 1) == date(2024, 2, 29)
assert add_months(date(2026, 11, 26), 3) == date(2027, 2, 26)
Then test the state transition. Put a task in a temporary in-memory SQLite database, confirm it is overdue, mark it completed, and confirm the next deadline changes. No network connection is needed for the test.
from datetime import date
from pathlib import Path
from home_maintenance import open_db, add_task, upcoming, mark_done

with open_db(Path(":memory:")) as conn:
add_task(conn, "Clean filter", "Kitchen", 3, "2026-01-15")
before = upcoming(conn, date(2026, 5, 1))
assert before[0][4] == "overdue"
task_id = before[0][1]
mark_done(conn, task_id, "2026-05-01")
assert upcoming(conn, date(2026, 5, 1)) == []
These tests do not prove the app is ready for every household. They prove specific rules: clamping, overdue detection, and recomputing the next date from completion.
Failure modes worth designing for
Duplicate tasks. Our demonstration allows duplicate names because two appliances could share a label. A production interface should make duplicate creation visible, perhaps by using an appliance identifier and allowing the user to merge entries.

Incorrect dates. The CLI uses ISO dates and rejects invalid dates such as February 30. In a graphical application, date input should also have a clear label and validation feedback. If someone enters a completion date in the future, this prototype accepts it; a production version should ask whether that is intended.

Multiple people updating one task. A single local SQLite file works well for a small, single-device tool. Concurrent updates across several devices need a synchronization strategy, conflict detection, and possibly an event log rather than only a last_done field.

Loss of history. Updating last_done overwrites the previous completion date. That is acceptable for a minimal reminder, but not for warranty evidence, maintenance analytics, or audit trails. A stronger design uses two tables: a tasks table for the recurrence rule and a completions table with one immutable row per service event. The latest completion can then be derived rather than overwritten.

Safety-critical reminders. Never treat a generic example interval as manufacturer guidance. Smoke alarms, electrical systems, ventilation, and other safety-related equipment may have legally or technically prescribed inspection schedules. The user should enter a schedule from the relevant instructions or a qualified professional.
What to add next
The highest-value upgrade is not a flashy dashboard; it is an event history. Store each completion with a timestamp, the person who performed the work, optional notes, and evidence such as an invoice reference. Keep attachments separate from the task table and avoid uploading them without a clear need. Once history exists, the application can answer more useful questions: Which tasks are repeatedly late? How often is a repair recurring? When did a component last receive attention?

Another sensible enhancement is a calendar export using the iCalendar format. That would let users view due dates in their existing calendar without giving the app ongoing access to the calendar account. Reminders can remain local, and permissions stay narrow.
Takeaway
A trustworthy household tool should make ordinary decisions explicit: what “monthly” means, how completed work changes a deadline, what data is stored, and what happens when records disagree. Starting with a small testable model makes future features safer and easier to explain.

Publication note: This tutorial accompanies home-and-living editorial work connected to Khanehmano, a Persian-language publication focused on practical decisions about homes and everyday living. The sample application is independent, educational code rather than an official service from that publication.

AI disclosure: This tutorial was drafted with AI assistance. The example code and the date-handling tests were executed during preparation; adapt and review the implementation before using it with important household records.

來源:DEV Community · dev.to