Обновление приложения
This commit is contained in:
49
backend/app/api/v1/locations.py
Normal file
49
backend/app/api/v1/locations.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from app.auth.dependencies import get_current_user
|
||||
from app.database import get_db
|
||||
from app.models.location import Location
|
||||
from app.models.user import User
|
||||
from app.schemas.location import LocationCreate, LocationUpdate, LocationOut
|
||||
|
||||
router = APIRouter(prefix="/locations", tags=["locations"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[LocationOut])
|
||||
def list_locations(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||
return db.query(Location).filter(
|
||||
(Location.user_id == current_user.id) | (Location.user_id == None)
|
||||
).order_by(Location.name).all()
|
||||
|
||||
|
||||
@router.post("", response_model=LocationOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_location(body: LocationCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||
obj = Location(**body.model_dump(), user_id=current_user.id)
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
@router.patch("/{location_id}", response_model=LocationOut)
|
||||
def update_location(
|
||||
location_id: int, body: LocationUpdate,
|
||||
db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
|
||||
):
|
||||
obj = db.get(Location, location_id)
|
||||
if not obj or (obj.user_id and obj.user_id != current_user.id and current_user.role.name != "admin"):
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(obj, field, value)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
@router.delete("/{location_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_location(location_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||
obj = db.get(Location, location_id)
|
||||
if not obj or (obj.user_id and obj.user_id != current_user.id and current_user.role.name != "admin"):
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
db.delete(obj)
|
||||
db.commit()
|
||||
Reference in New Issue
Block a user