sand-and-scripture / scripts /add_post.py
pmrc-phil's picture
Add scripts module
2ee7e68 verified
Raw
History Blame Contribute Delete
3.08 kB
"""
Single post adder: CLI tool to add a single post to the database.
Usage:
python scripts/add_post.py --title "Title" --slug "slug" \
--content-file drafts/foo.md --category "Category" \
--content-format markdown
"""
import os
import sys
import argparse
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app import app, db, Post, prepare_post_content, calculate_content_hash
def add_post(title, slug, content_file, category, content_format='markdown'):
"""
Add a single post to the database.
Args:
title (str): Post title
slug (str): URL-friendly slug
content_file (str): Path to content file
category (str): Post category
content_format (str): 'markdown' or 'html'
"""
# Read content file
if not os.path.exists(content_file):
print(f"Error: Content file not found: {content_file}")
return False
with open(content_file, 'r', encoding='utf-8') as f:
raw_content = f.read()
# Check if slug already exists
existing = Post.query.filter_by(slug=slug).first()
if existing:
print(f"Error: Slug '{slug}' already exists in database")
return False
# Process content
if content_format == 'markdown':
html_content = prepare_post_content(raw_content)
else:
html_content = raw_content
# Calculate hash
content_hash = calculate_content_hash(raw_content)
# Extract summary (first 200 chars)
summary = raw_content[:200]
# Create post
post = Post(
title=title,
slug=slug,
content=html_content,
summary=summary,
pub_date=datetime.utcnow(),
category=category,
published=True,
content_hash=content_hash
)
try:
db.session.add(post)
db.session.commit()
print(f"Success: Post '{title}' added with slug '{slug}'")
return True
except Exception as e:
db.session.rollback()
print(f"Error: Failed to add post: {e}")
return False
def main():
parser = argparse.ArgumentParser(description='Add a single post to the database')
parser.add_argument('--title', required=True, help='Post title')
parser.add_argument('--slug', required=True, help='URL-friendly slug')
parser.add_argument('--content-file', required=True, help='Path to content file')
parser.add_argument('--category', default='General', help='Post category')
parser.add_argument('--content-format', default='markdown',
choices=['markdown', 'html'], help='Content format')
args = parser.parse_args()
with app.app_context():
db.create_all()
success = add_post(
title=args.title,
slug=args.slug,
content_file=args.content_file,
category=args.category,
content_format=args.content_format
)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()