Files

30 lines
840 B
Python

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List
from pydantic import BaseModel
from app.db.database import get_db
from app.db.models import NewsCache
router = APIRouter()
class NewsItemSchema(BaseModel):
news_id: str
title: str
description: str
pubDate: str
sentiment: str | None
class Config:
from_attributes = True
@router.get("/", response_model=List[NewsItemSchema])
async def get_news(query: str = None, limit: int = 50, db: AsyncSession = Depends(get_db)):
stmt = select(NewsCache).order_by(NewsCache.pubDate.desc()).limit(limit)
if query:
stmt = stmt.where(NewsCache.title.like(f"%{query}%"))
result = await db.execute(stmt)
news = result.scalars().all()
return news