45 lines
1.0 KiB
Python
45 lines
1.0 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
from pydantic import BaseModel
|
|
from config.database import SessionLocal
|
|
from models.consumption import Consumption
|
|
|
|
router = APIRouter(prefix="/api/consumption", tags=["Consumption"])
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
# Pydantic schemas
|
|
class ConsumptionCreate(BaseModel):
|
|
scenario_id: int
|
|
amount: float
|
|
description: Optional[str] = None
|
|
|
|
|
|
class ConsumptionRead(ConsumptionCreate):
|
|
id: int
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
|
|
|
|
@router.post("/", response_model=ConsumptionRead)
|
|
async def create_consumption(item: ConsumptionCreate, db: Session = Depends(get_db)):
|
|
db_item = Consumption(**item.dict())
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
|
|
@router.get("/", response_model=List[ConsumptionRead])
|
|
async def list_consumption(db: Session = Depends(get_db)):
|
|
return db.query(Consumption).all()
|