اولین نسخه بکاند آرامش پلازا
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.auth import get_current_admin
|
||||
from app.database import get_db
|
||||
from app import models, schemas
|
||||
|
||||
router = APIRouter(prefix="/api/articles", tags=["Articles"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[schemas.ArticleOut])
|
||||
def list_articles(category: str | None = None, db: Session = Depends(get_db)):
|
||||
query = db.query(models.Article)
|
||||
if category:
|
||||
query = query.filter(models.Article.category == category)
|
||||
return query.order_by(models.Article.order).all()
|
||||
|
||||
|
||||
@router.get("/{slug}", response_model=schemas.ArticleOut)
|
||||
def get_article(slug: str, db: Session = Depends(get_db)):
|
||||
article = db.query(models.Article).filter(models.Article.slug == slug).first()
|
||||
if not article:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "مقاله پیدا نشد")
|
||||
return article
|
||||
|
||||
|
||||
@router.post("", response_model=schemas.ArticleOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_article(
|
||||
payload: schemas.ArticleCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_admin=Depends(get_current_admin),
|
||||
):
|
||||
if db.query(models.Article).filter(models.Article.slug == payload.slug).first():
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "این slug قبلاً استفاده شده است")
|
||||
article = models.Article(**payload.model_dump())
|
||||
db.add(article)
|
||||
db.commit()
|
||||
db.refresh(article)
|
||||
return article
|
||||
|
||||
|
||||
@router.put("/{article_id}", response_model=schemas.ArticleOut)
|
||||
def update_article(
|
||||
article_id: int,
|
||||
payload: schemas.ArticleUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_admin=Depends(get_current_admin),
|
||||
):
|
||||
article = db.get(models.Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "مقاله پیدا نشد")
|
||||
for field, value in payload.model_dump(exclude_unset=True).items():
|
||||
setattr(article, field, value)
|
||||
db.commit()
|
||||
db.refresh(article)
|
||||
return article
|
||||
|
||||
|
||||
@router.delete("/{article_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_article(
|
||||
article_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_admin=Depends(get_current_admin),
|
||||
):
|
||||
article = db.get(models.Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "مقاله پیدا نشد")
|
||||
db.delete(article)
|
||||
db.commit()
|
||||
return None
|
||||
Reference in New Issue
Block a user