параметризованный круд; добавление роутера для experiment_category; дописаны некоторые роуты для других сущностей

This commit is contained in:
HellsSenju 2024-10-27 23:29:52 +04:00
parent e52066f65d
commit ab32a0f7f5
16 changed files with 435 additions and 195 deletions

51
db/crud.py Normal file
View File

@ -0,0 +1,51 @@
from typing import Type, TypeVar, Sequence, Optional, Dict, Any
from sqlalchemy import update as update_, delete as delete_
from sqlalchemy.future import select
from db.models import ExperimentCategory, ExperimentData, ExperimentParameters, LoadParameters, RecyclingParameters
from db.postgres_db_connection import async_session_postgres
T = TypeVar("T", ExperimentCategory, ExperimentData, ExperimentParameters, LoadParameters, RecyclingParameters)
async def get_all(model_class: Type[T]) -> Sequence[T]:
async with async_session_postgres() as session:
result = await session.execute(select(model_class))
return result.scalars().all()
async def get_by_id(model_class: Type[T], id: int) -> Optional[T]:
async with async_session_postgres() as session:
result = await session.execute(select(model_class).where(model_class.id == id))
return result.scalar_one_or_none()
async def create(model_class: Type[T], **kwargs) -> T:
async with async_session_postgres() as session:
new_instance = model_class(**kwargs)
session.add(new_instance)
await session.commit()
await session.refresh(new_instance)
return new_instance
async def update(model_class: Type[T], id: int, updated_data: Dict[str, Any]) -> Optional[T]:
async with async_session_postgres() as session:
stmt = (
update_(model_class)
.where(model_class.id == id)
.values(**updated_data)
.execution_options(synchronize_session="fetch")
)
await session.execute(stmt)
await session.commit()
return await get_by_id(model_class, id)
async def delete(model_class: Type[T], id: int) -> bool:
async with async_session_postgres() as session:
stmt = delete_(model_class).where(model_class.id == id)
result = await session.execute(stmt)
await session.commit()
return result.rowcount > 0

View File

@ -51,10 +51,10 @@ async def csv_to_db():
await load_data_to_postgres('./db/files/load_parameters.csv', LoadParameters) await load_data_to_postgres('./db/files/load_parameters.csv', LoadParameters)
await load_data_to_postgres('./db/files/recycling_parameters.csv', RecyclingParameters) await load_data_to_postgres('./db/files/recycling_parameters.csv', RecyclingParameters)
await load_data_to_postgres('./db/files/experiment_parameters.csv', ExperimentParameters) await load_data_to_postgres('./db/files/experiment_parameters.csv', ExperimentParameters)
await load_data_to_postgres('./db/files/experiment_data.csv', ExperimentData) await load_data_to_postgres('./db/files/experiment_data.csv', ExperimentData)
load_data_to_clickhouse('./db/files/ch_experimentdb_experiment_data.csv', ChExperimentDBExperimentData) load_data_to_clickhouse('./db/files/ch_experimentdb_experiment_data.csv', ChExperimentDBExperimentData)
print('csv_to_db выполнено')

View File

@ -3,3 +3,9 @@ from settings import settings
engine_postgres = create_async_engine(url=settings.db_url_asyncpg_docker, echo=True) engine_postgres = create_async_engine(url=settings.db_url_asyncpg_docker, echo=True)
async_session_postgres = async_sessionmaker(engine_postgres, expire_on_commit=False) async_session_postgres = async_sessionmaker(engine_postgres, expire_on_commit=False)
# Функция для получения новой сессии
async def get_async_session():
async with async_session_postgres() as session:
yield session

View File

@ -1,7 +1,8 @@
from typing import Sequence
from sqlalchemy import update, delete
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select from sqlalchemy.future import select
from sqlalchemy import update, delete
from typing import List
from db.models import ExperimentCategory from db.models import ExperimentCategory
@ -10,7 +11,7 @@ class ExperimentCategoryRepository:
def __init__(self, session: AsyncSession): def __init__(self, session: AsyncSession):
self.session = session self.session = session
async def get_all(self) -> List[ExperimentCategory]: async def get_all(self) -> Sequence[ExperimentCategory]:
result = await self.session.execute(select(ExperimentCategory)) result = await self.session.execute(select(ExperimentCategory))
return result.scalars().all() return result.scalars().all()
@ -18,13 +19,11 @@ class ExperimentCategoryRepository:
result = await self.session.execute(select(ExperimentCategory).where(ExperimentCategory.id == id)) result = await self.session.execute(select(ExperimentCategory).where(ExperimentCategory.id == id))
return result.scalar_one_or_none() return result.scalar_one_or_none()
async def create(self, experiment_category: ExperimentCategory) -> ExperimentCategory: async def create(self, new_data: ExperimentCategory):
self.session.add(experiment_category) self.session.add(new_data)
await self.session.commit() await self.session.commit()
await self.session.refresh(experiment_category)
return experiment_category
async def update(self, id: int, updated_data: dict) -> ExperimentCategory: async def update(self, id: int, updated_data: dict):
stmt = ( stmt = (
update(ExperimentCategory). update(ExperimentCategory).
where(ExperimentCategory.id == id). where(ExperimentCategory.id == id).
@ -32,24 +31,8 @@ class ExperimentCategoryRepository:
) )
await self.session.execute(stmt) await self.session.execute(stmt)
await self.session.commit() await self.session.commit()
return await self.get_by_id(id)
async def delete(self, id: int) -> bool: async def delete(self, id: int):
stmt = delete(ExperimentCategory).where(ExperimentCategory.id == id) stmt = delete(ExperimentCategory).where(ExperimentCategory.id == id)
result = await self.session.execute(stmt) await self.session.execute(stmt)
await self.session.commit() await self.session.commit()
return result.rowcount > 0
# @staticmethod
# async def create_from_pydantic(body: ExperimentDataBody):
# new_data = ExperimentData(
# direction=body.direction,
# temperature=body.temperature,
# nox=body.nox,
# co2=body.co2,
# co=body.co,
# file_id=body.file_id
# )
# async with async_session() as session:
# session.add(new_data)
# await session.commit()

View File

@ -1,16 +1,20 @@
from typing import Sequence, Optional
from sqlalchemy import update, delete
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select from sqlalchemy.future import select
from sqlalchemy import update, delete
from typing import List
from db.models.experiment_data_model import ExperimentData from db.models.experiment_data_model import ExperimentData
from network.schemas import ExperimentDataBody
class ExperimentDataRepository: class ExperimentDataRepository:
def __init__(self, session: AsyncSession): def __init__(self, session: AsyncSession):
self.session = session self.session = session
async def get_all(self) -> List[ExperimentData]: async def get_all(self) -> Sequence[ExperimentData]:
result = await self.session.execute(select(ExperimentData)) result = await self.session.execute(select(ExperimentData))
return result.scalars().all() return result.scalars().all()
@ -18,13 +22,11 @@ class ExperimentDataRepository:
result = await self.session.execute(select(ExperimentData).where(ExperimentData.id == id)) result = await self.session.execute(select(ExperimentData).where(ExperimentData.id == id))
return result.scalar_one_or_none() return result.scalar_one_or_none()
async def create(self, experiment_data: ExperimentData) -> ExperimentData: async def create(self, new_data: ExperimentData):
self.session.add(experiment_data) self.session.add(new_data)
await self.session.commit() await self.session.commit()
await self.session.refresh(experiment_data)
return experiment_data
async def update(self, id: int, updated_data: dict) -> ExperimentData: async def update(self, id: int, updated_data: dict):
stmt = ( stmt = (
update(ExperimentData). update(ExperimentData).
where(ExperimentData.id == id). where(ExperimentData.id == id).
@ -32,24 +34,9 @@ class ExperimentDataRepository:
) )
await self.session.execute(stmt) await self.session.execute(stmt)
await self.session.commit() await self.session.commit()
return await self.get_by_id(id)
async def delete(self, id: int) -> bool: async def delete(self, id: int):
stmt = delete(ExperimentData).where(ExperimentData.id == id) stmt = delete(ExperimentData).where(ExperimentData.id == id)
result = await self.session.execute(stmt) await self.session.execute(stmt)
await self.session.commit() await self.session.commit()
return result.rowcount > 0
# @staticmethod
# async def create_from_pydantic(body: ExperimentDataBody):
# new_data = ExperimentData(
# direction=body.direction,
# temperature=body.temperature,
# nox=body.nox,
# co2=body.co2,
# co=body.co,
# file_id=body.file_id
# )
# async with async_session() as session:
# session.add(new_data)
# await session.commit()

View File

@ -1,16 +1,17 @@
from typing import Optional, List, Sequence from typing import Sequence
from sqlalchemy import select
from sqlalchemy import update, delete
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select from sqlalchemy.future import select
from sqlalchemy import update, delete
from typing import List
from db.models.experiment_parameters_model import ExperimentParameters from db.models.experiment_parameters_model import ExperimentParameters
class ExperimentParametersRepository: class ExperimentParametersRepository:
def __init__(self, session: AsyncSession): def __init__(self, session: AsyncSession):
self.session = session self.session = session
async def get_all(self) -> List[ExperimentParameters]: async def get_all(self) -> Sequence[ExperimentParameters]:
result = await self.session.execute(select(ExperimentParameters)) result = await self.session.execute(select(ExperimentParameters))
return result.scalars().all() return result.scalars().all()
@ -18,13 +19,17 @@ class ExperimentParametersRepository:
result = await self.session.execute(select(ExperimentParameters).where(ExperimentParameters.id == id)) result = await self.session.execute(select(ExperimentParameters).where(ExperimentParameters.id == id))
return result.scalar_one_or_none() return result.scalar_one_or_none()
async def create(self, experiment_parameters: ExperimentParameters) -> ExperimentParameters: async def get_experiment_parameters_by_category(self, session: AsyncSession, category_id: int) -> Sequence[ExperimentParameters]:
self.session.add(experiment_parameters) result = await self.session.execute(
await self.session.commit() select(ExperimentParameters).where(ExperimentParameters.experiment_category_id == category_id)
await self.session.refresh(experiment_parameters) )
return experiment_parameters return result.scalars().all()
async def update(self, id: int, updated_data: dict) -> ExperimentParameters: async def create(self, new_data: ExperimentParameters):
self.session.add(new_data)
await self.session.commit()
async def update(self, id: int, updated_data: dict):
stmt = ( stmt = (
update(ExperimentParameters). update(ExperimentParameters).
where(ExperimentParameters.id == id). where(ExperimentParameters.id == id).
@ -32,25 +37,8 @@ class ExperimentParametersRepository:
) )
await self.session.execute(stmt) await self.session.execute(stmt)
await self.session.commit() await self.session.commit()
return await self.get_by_id(id)
async def delete(self, id: int) -> bool: async def delete(self, id: int):
stmt = delete(ExperimentParameters).where(ExperimentParameters.id == id) stmt = delete(ExperimentParameters).where(ExperimentParameters.id == id)
result = await self.session.execute(stmt) await self.session.execute(stmt)
await self.session.commit() await self.session.commit()
return result.rowcount > 0
# @staticmethod
# async def create_from_pydantic(body: ExperimentParametersBody):
# new_data = ExperimentParameters(
# outer_blades_count=body.outer_blades_count,
# outer_blades_length=body.outer_blades_length,
# outer_blades_angle=body.outer_blades_angle,
# middle_blades_count=body.middle_blades_count,
# load_id=body.load_id,
# recycling_id=body.recycling_id,
# experiment_hash=body.experiment_hash
# )
# async with async_session() as session:
# session.add(new_data)
# await session.commit()

View File

@ -1,49 +1,76 @@
from typing import Optional from typing import Optional, Sequence
from sqlalchemy import delete as delete_
from sqlalchemy import update as update_
from sqlalchemy.future import select from sqlalchemy.future import select
from db.postgres_db_connection import async_session_postgres
from db.models.load_parameters_model import LoadParameters from db.models.load_parameters_model import LoadParameters
from network.schemas import LoadParametersBody from db.postgres_db_connection import async_session_postgres
class LoadParametersRepository: async def get_all() -> Sequence[LoadParameters]:
@staticmethod
async def get_all() -> Optional[list[LoadParameters]]:
async with async_session_postgres() as session: async with async_session_postgres() as session:
result = await session.execute(select(LoadParameters)) result = await session.execute(select(LoadParameters))
return result.scalars().all() return result.scalars().all()
@staticmethod
async def get_by_id(id_: int) -> Optional[LoadParameters]:
async with async_session_postgres() as session:
result = session.get(LoadParameters, id_)
return result
@staticmethod async def get_by_id(id: int) -> LoadParameters:
async def create(load: int,
primary_air_consumption: float,
secondary_air_consumption: float,
gas_inlet_consumption: float) -> None:
new_data = LoadParameters(
load=load,
primary_air_consumption=primary_air_consumption,
secondary_air_consumption=secondary_air_consumption,
gas_inlet_consumption=gas_inlet_consumption
)
async with async_session_postgres() as session: async with async_session_postgres() as session:
session.add(new_data) result = await session.execute(select(LoadParameters).where(LoadParameters.id == id))
await session.commit() return result.scalar_one_or_none()
@staticmethod
async def create_from_pydantic(body: LoadParametersBody): async def create(new_data: LoadParameters):
new_data = LoadParameters(
load=body.load,
primary_air_consumption=body.primary_air_consumption,
secondary_air_consumption=body.secondary_air_consumption,
gas_inlet_consumption=body.gas_inlet_consumption
)
async with async_session_postgres() as session: async with async_session_postgres() as session:
session.add(new_data) session.add(new_data)
await session.commit() await session.commit()
async def update(id: int, updated_data: dict):
async with async_session_postgres() as session:
stmt = (
update_(LoadParameters).
where(LoadParameters.id == id).
values(**updated_data)
)
await session.execute(stmt)
await session.commit()
async def delete(id: int) -> bool:
async with async_session_postgres() as session:
stmt = delete_(LoadParameters).where(LoadParameters.id == id)
result = await session.execute(stmt)
await session.commit()
return result.rowcount > 0
# class LoadParametersRepository:
# def __init__(self, session: AsyncSession):
# self.session = session
#
# async def get_all(self) -> Sequence[LoadParameters]:
# result = await self.session.execute(select(LoadParameters))
# return result.scalars().all()
#
# async def get_by_id(self, id: int) -> LoadParameters:
# result = await self.session.execute(select(LoadParameters).where(LoadParameters.id == id))
# return result.scalar_one_or_none()
#
# async def create(self, new_data: LoadParameters):
# self.session.add(new_data)
# await self.session.commit()
#
# async def update(self, id: int, updated_data: dict):
# stmt = (
# update_(LoadParameters).
# where(LoadParameters.id == id).
# values(**updated_data)
# )
# await self.session.execute(stmt)
# await self.session.commit()
#
# async def delete(self, id: int):
# stmt = delete_(LoadParameters).where(LoadParameters.id == id)
# await self.session.execute(stmt)
# await self.session.commit()

View File

@ -1,52 +1,38 @@
from typing import Optional from typing import Sequence
from sqlalchemy import select from sqlalchemy import select
from db.postgres_db_connection import async_session_postgres from sqlalchemy import update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from db.models.recycling_parameters_model import RecyclingParameters from db.models.recycling_parameters_model import RecyclingParameters
from network.schemas import RecyclingParametersBody
class RecyclingParametersRepository: class RecyclingParametersRepository:
@staticmethod def __init__(self, session: AsyncSession):
async def get_all() -> Optional[list[RecyclingParameters]]: self.session = session
async with async_session_postgres() as session:
result = await session.execute(select(RecyclingParameters))
return result.scalars.all()
@staticmethod async def get_all(self) -> Sequence[RecyclingParameters]:
async def get_by_id(id_: int) -> Optional[RecyclingParameters]: result = await self.session.execute(select(RecyclingParameters))
async with async_session_postgres() as session: return result.scalars().all()
result = await session.execute(select(RecyclingParameters).where(RecyclingParameters.id == id_))
return result.scalars().first()
@staticmethod async def get_by_id(self, id: int) -> RecyclingParameters:
async def create(load_id: int, result = await self.session.execute(select(RecyclingParameters).where(RecyclingParameters.id == id))
recycling_level: int, return result.scalar_one_or_none()
co2: float,
n2: float, async def create(self, new_data: RecyclingParameters):
h2o: float, self.session.add(new_data)
o2: float): await self.session.commit()
new_data = RecyclingParameters(
load_id=load_id, async def update(self, id: int, updated_data: dict):
recycling_level=recycling_level, stmt = (
co2=co2, update(RecyclingParameters).
n2=n2, where(RecyclingParameters.id == id).
h2o=h2o, values(**updated_data)
o2=o2
) )
async with async_session_postgres() as session: await self.session.execute(stmt)
session.add(new_data) await self.session.commit()
await session.commit()
@staticmethod async def delete(self, id: int):
async def create_from_pydantic(body: RecyclingParametersBody): stmt = delete(RecyclingParameters).where(RecyclingParameters.id == id)
new_data = RecyclingParameters( await self.session.execute(stmt)
load_id=body.load_id, await self.session.commit()
recycling_level=body.recycling_level,
co2=body.co2,
n2=body.n2,
h2o=body.h2o,
o2=body.o2
)
async with async_session_postgres() as session:
session.add(new_data)
await session.commit()

View File

@ -1,7 +1,8 @@
import asyncio import asyncio
from fastapi import FastAPI, HTTPException, BackgroundTasks from fastapi import FastAPI, HTTPException, BackgroundTasks
from db.csv_to_db import csv_to_db from db.csv_to_db import csv_to_db
from network.routes import ch_experimentdb_experiment_data_router, experiment_data_router, experiment_parameters_router from network.routes import (ch_experimentdb_experiment_data_router, experiment_data_router,
experiment_parameters_router, experiment_category_router)
from network.routes import load_parameters_router, recycling_parameters_router from network.routes import load_parameters_router, recycling_parameters_router
from network.schemas import * from network.schemas import *
from new_experiment_planner import run_experiment from new_experiment_planner import run_experiment
@ -11,6 +12,9 @@ app = FastAPI()
app.include_router(ch_experimentdb_experiment_data_router.router, app.include_router(ch_experimentdb_experiment_data_router.router,
prefix="/ch_experimentdb_experiment_data", prefix="/ch_experimentdb_experiment_data",
tags=["ch_experimentdb_experiment_data"]) tags=["ch_experimentdb_experiment_data"])
app.include_router(experiment_category_router.router,
prefix="/experiment_category",
tags=["experiment_category"])
app.include_router(experiment_data_router.router, app.include_router(experiment_data_router.router,
prefix="/experiment_data", prefix="/experiment_data",
tags=["experiment_data"]) tags=["experiment_data"])

View File

@ -0,0 +1,59 @@
from fastapi import APIRouter, HTTPException
from db.crud import *
from db.models import ExperimentCategory
from network.schemas import ExperimentCategoryBody
router = APIRouter()
@router.post('/create')
async def create_experiment_category(body: ExperimentCategoryBody):
try:
await create(ExperimentCategory,
name=body.name
)
return {"message": "Новая запись <ExperimentCategory> успешно добавлена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/all')
async def get_all_experiment_category():
try:
result = await get_all(ExperimentCategory)
if result is not None:
return result
else:
return {"message": "Нет записей в <ExperimentCategory>"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/{id}')
async def get_by_id_experiment_category(id: int):
try:
result = await get_by_id(ExperimentCategory, id)
if result is not None:
return result
else:
return {"message": "Запись <ExperimentCategory> не найдена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.delete('/{id}/delete')
async def delete_experiment_category(id: int):
try:
is_deleted = await delete(ExperimentCategory, id)
if is_deleted:
return {"message": "Запись <ExperimentCategory> успешно удалена"}
else:
return {"message": "Запись <ExperimentCategory> не найдена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

View File

@ -1,14 +1,23 @@
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from db.repositories.experiment_data_repos import ExperimentDataRepository
from db.crud import *
from db.models import ExperimentData
from network.schemas import ExperimentDataBody from network.schemas import ExperimentDataBody
router = APIRouter() router = APIRouter()
@router.post('/create') @router.post('/create')
async def create_experiment_data(data: ExperimentDataBody): async def create_experiment_data(body: ExperimentDataBody):
try: try:
await ExperimentDataRepository.create_from_pydantic(data) await create(ExperimentData,
direction=body.direction,
temperature=body.temperature,
nox=body.nox,
co2=body.co2,
co=body.co,
file_id=body.file_id
)
return {"message": "Новая запись <ExperimentData> успешно добавлена"} return {"message": "Новая запись <ExperimentData> успешно добавлена"}
except Exception as e: except Exception as e:
@ -18,12 +27,36 @@ async def create_experiment_data(data: ExperimentDataBody):
@router.get('/all') @router.get('/all')
async def get_all_experiment_data(): async def get_all_experiment_data():
try: try:
result = await ExperimentDataRepository.get_all() result = await get_all(ExperimentData)
if result is not None: if result is not None:
# return {"status": "success", "data": [LoadParametersBody.model_validate(param) for param in result]}
return result return result
else: else:
return {"message": "Нет записей в <ExperimentData>, либо произошла непредвиденная ошибка"} return {"message": "Нет записей в <ExperimentData>"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/{id}')
async def get_by_id_experiment_data(id: int):
try:
result = await get_by_id(ExperimentData, id)
if result is not None:
return result
else:
return {"message": "Запись <ExperimentData> не найдена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.delete('/{id}/delete')
async def delete_experiment_data(id: int):
try:
is_deleted = await delete(ExperimentData, id)
if is_deleted:
return {"message": "Запись <ExperimentData> успешно удалена"}
else:
return {"message": "Запись <ExperimentData> не найдена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

View File

@ -1,25 +1,63 @@
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from db.repositories.experiment_parameters_repos import ExperimentParametersRepository
from db.crud import *
from db.models import LoadParameters
from network.schemas import ExperimentParametersBody from network.schemas import ExperimentParametersBody
router = APIRouter() router = APIRouter()
@router.post('/create') @router.post('/create')
async def create_experiment_parameters(data: ExperimentParametersBody): async def create_experiment_parameters(body: ExperimentParametersBody):
try: try:
await ExperimentParametersRepository.create_from_pydantic(data) await create(ExperimentParameters,
outer_blades_count=body.outer_blades_count,
outer_blades_length=body.outer_blades_length,
outer_blades_angle=body.outer_blades_angle,
middle_blades_count=body.middle_blades_count,
load_id=body.load_id,
recycling_id=body.recycling_id,
experiment_hash=body.experiment_hash
)
return {"message": "Новая запись <ExperimentParameters> успешно добавлена"} return {"message": "Новая запись <ExperimentParameters> успешно добавлена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/all') @router.get('/all')
async def get_all_experiment_parameters(): async def get_all_experiment_parameters():
try: try:
result = await ExperimentParametersRepository.get_all() result = await get_all(ExperimentParameters)
if result: if result is not None:
return result return result
else: else:
return {"message": "Нет записей в <ExperimentParameters>, либо произошла непредвиденная ошибка"} return {"message": "Нет записей в <ExperimentParameters>"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/{id}')
async def get_by_id_experiment_parameters(id: int):
try:
result = await get_by_id(ExperimentParameters, id)
if result is not None:
return result
else:
return {"message": "Запись <ExperimentParameters> не найдена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.delete('/{id}/delete')
async def delete_experiment_parameters(id: int):
try:
is_deleted = await delete(LoadParameters, id)
if is_deleted:
return {"message": "Запись <ExperimentParameters> успешно удалена"}
else:
return {"message": "Запись <ExperimentParameters> не найдена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

View File

@ -1,15 +1,22 @@
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from db.repositories.load_parameters_repos import LoadParametersRepository
from db.crud import *
from db.models import LoadParameters
from network.schemas import LoadParametersBody from network.schemas import LoadParametersBody
router = APIRouter() router = APIRouter()
@router.post('/create') @router.post('/create')
async def create_load_parameters(data: LoadParametersBody): async def create_load_parameters(body: LoadParametersBody):
try: try:
await LoadParametersRepository.create_from_pydantic(data) await create(LoadParameters,
load=body.load,
primary_air_consumption=body.primary_air_consumption,
secondary_air_consumption=body.secondary_air_consumption,
gas_inlet_consumption=body.gas_inlet_consumption
)
return {"message": "Новая запись <LoadParameters> успешно добавлена"} return {"message": "Новая запись <LoadParameters> успешно добавлена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@ -18,12 +25,36 @@ async def create_load_parameters(data: LoadParametersBody):
@router.get('/all') @router.get('/all')
async def get_all_load_parameters(): async def get_all_load_parameters():
try: try:
result = await LoadParametersRepository.get_all() result = await get_all(LoadParameters)
if result is not None: if result is not None:
# return {"status": "success", "data": [LoadParametersBody.model_validate(param) for param in result]}
return result return result
else: else:
return {"message": "Нет записей в <LoadParameters>, либо произошла непредвиденная ошибка"} return {"message": "Нет записей в <LoadParameters>"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/{id}')
async def get_by_id_load_parameters(id: int):
try:
result = await get_by_id(LoadParameters, id)
if result is not None:
return result
else:
return {"message": "Запись <LoadParameters> не найдена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.delete('/{id}/delete')
async def delete_load_parameters(id: int):
try:
is_deleted = await delete(LoadParameters, id)
if is_deleted:
return {"message": "Запись <LoadParameters> успешно удалена"}
else:
return {"message": "Запись <LoadParameters> не найдена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

View File

@ -1,25 +1,61 @@
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from db.repositories.recycling_parameters_repos import RecyclingParametersRepository
from db.crud import *
from db.models import RecyclingParameters
from network.schemas import RecyclingParametersBody from network.schemas import RecyclingParametersBody
router = APIRouter() router = APIRouter()
@router.post('/create') @router.post('/create')
async def create_recycling_parameters(data: RecyclingParametersBody): async def create_recycling_parameters(body: RecyclingParametersBody):
try: try:
await RecyclingParametersRepository.create_from_pydantic(data) await create(RecyclingParameters,
load_id=body.load_id,
recycling_level=body.recycling_level,
co2=body.co2,
n2=body.n2,
h2o=body.h2o,
o2=body.o2
)
return {"message": "Новая запись <RecyclingParameters> успешно добавлена"} return {"message": "Новая запись <RecyclingParameters> успешно добавлена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/all') @router.get('/all')
async def get_all_recycling_parameters(): async def get_all_recycling_parameters():
try: try:
result = await RecyclingParametersRepository.get_all() result = await get_all(RecyclingParameters)
if result is not None:
if result:
return result return result
else: else:
return {"message": "Нет записей в <RecyclingParameters>, либо произошла непредвиденная ошибка"} return {"message": "Нет записей в <RecyclingParameters>"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.get('/{id}')
async def get_by_id_recycling_parameters(id: int):
try:
result = await get_by_id(RecyclingParameters, id)
if result is not None:
return result
else:
return {"message": "Запись <RecyclingParameters> не найдена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.delete('/{id}/delete')
async def delete_recycling_parameters(id: int):
try:
is_deleted = await delete(RecyclingParameters, id)
if is_deleted:
return {"message": "Запись <RecyclingParameters> успешно удалена"}
else:
return {"message": "Запись <RecyclingParameters> не найдена"}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

View File

@ -2,6 +2,7 @@ from typing import Optional
from pydantic import BaseModel, ConfigDict from pydantic import BaseModel, ConfigDict
class ExperimentParameters(BaseModel): class ExperimentParameters(BaseModel):
outer_blades_count: str outer_blades_count: str
outer_blades_length: str outer_blades_length: str
@ -10,6 +11,7 @@ class ExperimentParameters(BaseModel):
load: str load: str
recycling: str recycling: str
class ChExperimentDBExperimentDataBody(BaseModel): class ChExperimentDBExperimentDataBody(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
volume: float volume: float
@ -22,6 +24,12 @@ class ChExperimentDBExperimentDataBody(BaseModel):
z: float z: float
file_id: str file_id: str
class ExperimentCategoryBody(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
class ExperimentDataBody(BaseModel): class ExperimentDataBody(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
direction: float direction: float
@ -31,6 +39,7 @@ class ExperimentDataBody(BaseModel):
co: float co: float
file_id: Optional[str] file_id: Optional[str]
class ExperimentParametersBody(BaseModel): class ExperimentParametersBody(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
outer_blades_count: int outer_blades_count: int
@ -41,6 +50,7 @@ class ExperimentParametersBody(BaseModel):
recycling_id: Optional[int] recycling_id: Optional[int]
experiment_hash: str experiment_hash: str
class LoadParametersBody(BaseModel): class LoadParametersBody(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
load: int load: int
@ -48,6 +58,7 @@ class LoadParametersBody(BaseModel):
secondary_air_consumption: float secondary_air_consumption: float
gas_inlet_consumption: float gas_inlet_consumption: float
class RecyclingParametersBody(BaseModel): class RecyclingParametersBody(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
load_id: Optional[int] load_id: Optional[int]

Binary file not shown.