Automated Action 355d2a84d5 Implement notes management platform with FastAPI and SQLite
- Set up project structure with FastAPI
- Create database models for notes
- Implement Alembic migrations
- Create API endpoints for note CRUD operations
- Implement note export functionality (markdown, txt, pdf)
- Add health endpoint
- Set up linting with Ruff
2025-06-04 08:13:43 +00:00

86 lines
2.5 KiB
Python

import os
import tempfile
import uuid
from datetime import datetime
from pathlib import Path
from typing import Literal
import markdown
from weasyprint import HTML
from app.core.config import settings
from app.models.note import Note
def export_note(note: Note, format_type: Literal["markdown", "txt", "pdf"]) -> Path:
"""
Export a note to the specified format.
Args:
note: The note to export
format_type: The format to export to (markdown, txt, pdf)
Returns:
Path to the exported file
"""
# Create a unique filename
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
unique_id = str(uuid.uuid4())[:8]
if format_type == "markdown":
return _export_markdown(note, timestamp, unique_id)
elif format_type == "txt":
return _export_txt(note, timestamp, unique_id)
elif format_type == "pdf":
return _export_pdf(note, timestamp, unique_id)
else:
raise ValueError(f"Unsupported format: {format_type}")
def _export_markdown(note: Note, timestamp: str, unique_id: str) -> Path:
"""Export note to Markdown format."""
filename = f"{note.title.replace(' ', '_')}_{timestamp}_{unique_id}.md"
export_path = settings.EXPORT_DIR / filename
with open(export_path, "w") as f:
f.write(f"# {note.title}\n\n")
f.write(note.content)
return export_path
def _export_txt(note: Note, timestamp: str, unique_id: str) -> Path:
"""Export note to plain text format."""
filename = f"{note.title.replace(' ', '_')}_{timestamp}_{unique_id}.txt"
export_path = settings.EXPORT_DIR / filename
with open(export_path, "w") as f:
f.write(f"Title: {note.title}\n\n")
f.write(note.content)
return export_path
def _export_pdf(note: Note, timestamp: str, unique_id: str) -> Path:
"""Export note to PDF format."""
filename = f"{note.title.replace(' ', '_')}_{timestamp}_{unique_id}.pdf"
export_path = settings.EXPORT_DIR / filename
# Convert markdown to HTML
html_content = f"<h1>{note.title}</h1>\n{markdown.markdown(note.content)}"
# Create a temporary HTML file
with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as temp_html:
temp_html.write(html_content.encode('utf-8'))
temp_html_path = temp_html.name
try:
# Convert HTML to PDF
HTML(string=html_content).write_pdf(export_path)
finally:
# Clean up temporary file
if os.path.exists(temp_html_path):
os.unlink(temp_html_path)
return export_path