60 lines
2.0 KiB
Python
60 lines
2.0 KiB
Python
Here's an example of the `comments.py` file with CRUD endpoints for comments using FastAPI and SQLAlchemy:
|
|
|
|
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db 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, status_code=201)
|
|
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")
|
|
for field, value in comment.dict().items():
|
|
setattr(db_comment, field, value)
|
|
db.commit()
|
|
db.refresh(db_comment)
|
|
return db_comment
|
|
|
|
|
|
@router.delete("/{comment_id}", status_code=204)
|
|
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 {"message": "Comment deleted successfully"}
|
|
|
|
This file defines the following endpoints: |