51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from typing import Annotated
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.future import select
|
|
from uuid import UUID
|
|
|
|
from ...dependencies import get_db
|
|
from ...db import models
|
|
|
|
from ..auth import services as auth_services
|
|
from ..auth import schemas as auth_schemas
|
|
|
|
from . import schemas
|
|
|
|
|
|
async def get_news(
|
|
db: Annotated[AsyncSession, Depends(get_db)],
|
|
) -> list[schemas.NewsInDb]:
|
|
news = await db.execute(select(models.News).order_by(models.News.created.desc()))
|
|
return [schemas.NewsInDb.model_validate(n) for n in news.scalars().all()]
|
|
|
|
|
|
async def create_news(
|
|
news: schemas.CreateNews,
|
|
current_user: auth_schemas.UserInDB,
|
|
db: AsyncSession,
|
|
) -> schemas.NewsInDb:
|
|
if current_user.username == "admin":
|
|
n = models.News(title=news.title, content=news.content)
|
|
db.add(n)
|
|
await db.commit()
|
|
print(f"\n\n{n.title}\n\n", flush=True)
|
|
return schemas.NewsInDb.model_validate(n)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
|
|
async def tap_news(news_id: UUID, db: AsyncSession):
|
|
n = db.query(models.News).filter(models.News.id == news_id).first()
|
|
if n:
|
|
setattr(n, "taps", n.taps + 1)
|
|
db.commit()
|
|
return
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Not found",
|
|
)
|