deliveryman-api/app/api/endpoints/community.py
2025-01-02 16:33:39 +08:00

72 lines
2.2 KiB
Python

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import List
from app.models.community import CommunityDB, CommunityCreate, CommunityUpdate, CommunityInfo
from app.models.database import get_db
router = APIRouter()
@router.post("/", response_model=CommunityInfo)
async def create_community(
community: CommunityCreate,
db: Session = Depends(get_db)
):
"""创建社区"""
db_community = CommunityDB(**community.model_dump())
db.add(db_community)
db.commit()
db.refresh(db_community)
return db_community
@router.get("/", response_model=List[CommunityInfo])
async def get_communities(
skip: int = 0,
limit: int = 10,
db: Session = Depends(get_db)
):
"""获取社区列表"""
communities = db.query(CommunityDB).offset(skip).limit(limit).all()
return communities
@router.get("/{community_id}", response_model=CommunityInfo)
async def get_community(
community_id: int,
db: Session = Depends(get_db)
):
"""获取社区详情"""
community = db.query(CommunityDB).filter(CommunityDB.id == community_id).first()
if not community:
raise HTTPException(status_code=404, detail="社区不存在")
return community
@router.put("/{community_id}", response_model=CommunityInfo)
async def update_community(
community_id: int,
community: CommunityUpdate,
db: Session = Depends(get_db)
):
"""更新社区信息"""
db_community = db.query(CommunityDB).filter(CommunityDB.id == community_id).first()
if not db_community:
raise HTTPException(status_code=404, detail="社区不存在")
update_data = community.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_community, key, value)
db.commit()
db.refresh(db_community)
return db_community
@router.delete("/{community_id}")
async def delete_community(
community_id: int,
db: Session = Depends(get_db)
):
"""删除社区"""
result = db.query(CommunityDB).filter(CommunityDB.id == community_id).delete()
if not result:
raise HTTPException(status_code=404, detail="社区不存在")
db.commit()
return {"message": "社区已删除"}