Python/FastAPI backend with PostgreSQL for collecting Reddit data via public .json endpoints. React/Vite dashboard for analytics. Docker Compose setup with API and worker services connecting to shared PostgreSQL. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
from datetime import datetime
|
|
from sqlalchemy import select, func
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from backend.models.comment import Comment
|
|
from backend.models.post import Post
|
|
from backend.models.author import Author
|
|
|
|
|
|
async def list_comments(
|
|
db: AsyncSession,
|
|
post_id: int | None = None,
|
|
subreddit_id: int | None = None,
|
|
author: str | None = None,
|
|
sort_by: str = "created_utc",
|
|
sort_order: str = "desc",
|
|
since: datetime | None = None,
|
|
until: datetime | None = None,
|
|
page: int = 1,
|
|
per_page: int = 25,
|
|
) -> tuple[list[dict], int]:
|
|
base = select(Comment, Author.username).outerjoin(Author).join(Post)
|
|
|
|
filters = []
|
|
if post_id:
|
|
filters.append(Comment.post_id == post_id)
|
|
if subreddit_id:
|
|
filters.append(Post.subreddit_id == subreddit_id)
|
|
if author:
|
|
filters.append(Author.username == author)
|
|
if since:
|
|
filters.append(Comment.created_utc >= since)
|
|
if until:
|
|
filters.append(Comment.created_utc <= until)
|
|
|
|
if filters:
|
|
base = base.where(*filters)
|
|
|
|
count_stmt = select(func.count()).select_from(base.subquery())
|
|
total = (await db.execute(count_stmt)).scalar() or 0
|
|
|
|
sort_col = getattr(Comment, sort_by, Comment.created_utc)
|
|
if sort_order == "asc":
|
|
base = base.order_by(sort_col.asc())
|
|
else:
|
|
base = base.order_by(sort_col.desc())
|
|
|
|
base = base.offset((page - 1) * per_page).limit(per_page)
|
|
|
|
result = await db.execute(base)
|
|
comments = []
|
|
for comment, author_name in result.all():
|
|
data = {c.name: getattr(comment, c.name) for c in comment.__table__.columns}
|
|
data["author_name"] = author_name
|
|
comments.append(data)
|
|
|
|
return comments, total
|