55 lines
2.0 KiB
Python

Here's the `comments.py` file with CRUD endpoints for comments:
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models import Comment
from app.schemas import CommentCreate, CommentResponse
router = APIRouter(
prefix="/comments",
tags=["Comments"],
@router.post("/", response_model=CommentResponse)
def create_comment(comment: CommentCreate, db: Session = Depends(get_db)):
db_comment = Comment(**comment.dict())
db.add(db_comment)
db.commit()
db.refresh(db_comment)
return db_comment
@router.get("/", response_model=List[CommentResponse])
def get_comments(db: Session = Depends(get_db)):
comments = db.query(Comment).all()
return comments
@router.get("/{comment_id}", response_model=CommentResponse)
def get_comment(comment_id: int, db: Session = Depends(get_db)):
comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not comment:
raise HTTPException(status_code=404, detail="Comment not found")
return comment
@router.put("/{comment_id}", response_model=CommentResponse)
def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depends(get_db)):
db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not db_comment:
raise HTTPException(status_code=404, detail="Comment not found")
update_data = comment.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_comment, key, value)
db.commit()
db.refresh(db_comment)
return db_comment
@router.delete("/{comment_id}", response_model=CommentResponse)
def delete_comment(comment_id: int, db: Session = Depends(get_db)):
comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not comment:
raise HTTPException(status_code=404, detail="Comment not found")
db.delete(comment)
db.commit()
return comment
This file defines the following endpoints: