65 lines
2.4 KiB
Python
65 lines
2.4 KiB
Python
```python
|
|
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_all_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 None
|
|
```
|
|
|
|
|
|
- `POST /comments/`: Create a new comment
|
|
- `GET /comments/`: Get all comments
|
|
- `GET /comments/{comment_id}`: Get a single comment
|
|
- `PUT /comments/{comment_id}`: Update a comment
|
|
- `DELETE /comments/{comment_id}`: Delete a comment
|
|
|
|
The endpoints use SQLAlchemy models and Pydantic schemas for data validation and serialization. The `get_db` dependency is used to get a database session.
|
|
|
|
Note: Make sure you have the appropriate models and schemas defined in your project, and that the `get_db` function is correctly configured to connect to your database. |