news & things

This commit is contained in:
2024-04-13 14:37:30 +03:00
parent 8904d3c2b6
commit 89f59dabb1
17 changed files with 334 additions and 5 deletions

View File

View File

@ -0,0 +1,41 @@
from datetime import datetime, timedelta, timezone
from typing import Annotated, Union
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel
from ...config import jwt_config
from ...dependencies import get_db
from . import schemas
from . import services
from ..auth import services as auth_services
from ..auth import schemas as auth_schemas
router = APIRouter(
prefix="/news",
tags=["news"],
dependencies=[Depends(get_db)],
responses={404: {"description": "Not found"}},
)
@router.get("/")
async def get_news(
news: Annotated[schemas.NewsInDb, Depends(services.get_news)],
) -> list[schemas.NewsInDb]:
return news
@router.post("/")
async def create_news(
news: schemas.CreateNews,
current_user: Annotated[auth_schemas.User, Depends(auth_services.get_current_user)],
db: Annotated[Session, Depends(get_db)],
) -> schemas.NewsInDb:
return services.create_news(news=news, current_user=current_user, db=db)

View File

@ -0,0 +1,22 @@
from typing import Union
from pydantic import BaseModel
from uuid import UUID
from datetime import datetime
class CreateNews(BaseModel):
title: str
content: str
class News(BaseModel):
title: str
content: str
created: datetime
class NewsInDb(News):
id: UUID
class Config:
from_attributes = True

View File

@ -0,0 +1,37 @@
from fastapi import Depends, HTTPException
from typing import Annotated
from sqlalchemy.orm import Session
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
def get_news(
db: Annotated[Session, Depends(get_db)],
) -> list[schemas.NewsInDb]:
return [
schemas.NewsInDb.model_validate(n)
for n in db.query(models.News).order_by(models.News.created.desc()).all()
]
def create_news(
news: schemas.CreateNews,
current_user: auth_schemas.UserInDB,
db: Session,
) -> schemas.NewsInDb:
if current_user.username == "admin":
n = models.News(title=news.title, content=news.content)
db.add(n)
db.commit()
return schemas.NewsInDb.model_validate(n)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)