Skip to main content

53. Implementing Safe File Storage

Task data should be stored in a controlled directory with proper permissions and validation.

Original

with open("tasks.json", "w") as f:
json.dump(tasks, f)

Secure Refactor

import os, json

DATA_DIR = os.path.expanduser("~/.pydo_secure")
os.makedirs(DATA_DIR, exist_ok=True)

def safe_save(tasks):
path = os.path.join(DATA_DIR, "tasks.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(tasks, f, indent=2)

Lesson: Restrict storage to a safe directory and ensure files are encoded and validated.