spotnotes.app/seed_notes.py

81 lines
2.9 KiB
Python
Raw Permalink Normal View History

2026-05-12 23:58:18 +00:00
import csv
import sys
import os
from app import app
from extensions import db
from models.notepad import Notepad
from models.note import Note
from models.user import User
def seed_from_csv(csv_file, notepad_name, is_public=True, owner_email=None):
"""
Reads a CSV file and populates a notepad with notes.
CSV Format: title, content, lat, lng
"""
if not os.path.exists(csv_file):
print(f"Error: File '{csv_file}' not found.")
return
with app.app_context():
# 1. Resolve Owner (Optional)
user_id = None
if owner_email:
user = User.query.filter_by(email=owner_email).first()
if user:
user_id = user.id
else:
print(f"Warning: User with email '{owner_email}' not found. Notepad will be unowned.")
# 2. Find or Create Notepad
notepad = Notepad.query.filter_by(name=notepad_name).first()
if not notepad:
print(f"Creating new notepad: '{notepad_name}'")
notepad = Notepad(name=notepad_name, is_public=is_public, user_id=user_id)
db.session.add(notepad)
db.session.commit()
else:
print(f"Using existing notepad: '{notepad.name}' (ID: {notepad.id})")
# 3. Read CSV and Create Notes
try:
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
count = 0
for row in reader:
# Basic validation
if not all(k in row for k in ('title', 'content', 'lat', 'lng')):
print(f"Skipping invalid row: {row}")
continue
try:
note = Note(
title=row['title'],
content=row['content'],
lat=float(row['lat']),
lng=float(row['lng']),
is_encrypted=False,
2026-05-12 23:58:18 +00:00
notepad_id=notepad.id
)
db.session.add(note)
count += 1
except ValueError:
print(f"Invalid coordinates in row: {row['title']}")
continue
db.session.commit()
print(f"Success! Added {count} notes to '{notepad_name}'.")
except Exception as e:
print(f"An error occurred: {e}")
db.session.rollback()
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python seed_notes.py <csv_file> <notepad_name> [owner_email]")
sys.exit(1)
csv_path = sys.argv[1]
pad_name = sys.argv[2]
owner = sys.argv[3] if len(sys.argv) > 3 else None
seed_from_csv(csv_path, pad_name, is_public=True, owner_email=owner)