58 lines
2.2 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.session import get_db
from app.models.comment import Comment
from app.schemas.comment import CommentCreate, CommentResponse
router = APIRouter()
@router.post("/comments/", 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("/comments/", response_model=List[CommentResponse])
def read_comments(db: Session = Depends(get_db)):
comments = db.query(Comment).all()
return comments
@router.get("/comments/{comment_id}", response_model=CommentResponse)
def read_comment(comment_id: int, 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")
return db_comment
@router.put("/comments/{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("/comments/{comment_id}", response_model=CommentResponse)
def delete_comment(comment_id: int, 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")
db.delete(db_comment)
db.commit()
return db_comment
This file defines the following endpoints:
Note: Make sure you have the appropriate models and schemas defined in `app/models/comment.py` and `app/schemas/comment.py`, respectively.