получение всех данных работает, добавление нет, тк автоинкремент начинает с 1, я добавила в модели последовательность, но все равно не работает

This commit is contained in:
Inohara 2024-10-18 16:42:39 +04:00
parent 16ecd5789f
commit f4b55aacfb
15 changed files with 68 additions and 43 deletions

View File

@ -1,4 +1,4 @@
FROM python:3.9-slim
FROM python:3.12-slim
WORKDIR /app

View File

@ -1,6 +1,6 @@
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from settings import settings
engine = create_async_engine(url=settings.db_url_asyncpg, echo=False)
engine = create_async_engine(url=settings.db_url_asyncpg_docker, echo=False)
async_session = async_sessionmaker(engine)

View File

@ -1,11 +1,14 @@
from db.models.base import Base, int_pk_incr
from sqlalchemy.orm import Mapped
from sqlalchemy import Sequence
from sqlalchemy.orm import Mapped, mapped_column
class ChExperimentDBExperimentData(Base):
__tablename__ = 'ch_experimentdb_experiment_data'
id: Mapped[int_pk_incr]
id: Mapped[int] = mapped_column(primary_key=True,
autoincrement=True,
server_default=Sequence('ch_experimentdb_experiment_data_id_seq', start=11).next_value())
volume: Mapped[float]
nitrogen_oxide_emission: Mapped[float]
temperature: Mapped[float]

View File

@ -1,12 +1,17 @@
from typing import Optional
from sqlalchemy import Sequence
from db.models.base import Base, int_pk_incr
from sqlalchemy.orm import Mapped, mapped_column
id_seq = Sequence('experiment_data_id_seq', start=186581)
class ExperimentData(Base):
__tablename__ = 'experiment_data'
id: Mapped[int_pk_incr]
id: Mapped[int] = mapped_column(primary_key=True,
autoincrement=True,
server_default=Sequence('experiment_data_id_seq', start=186581).next_value())
direction: Mapped[float]
temperature: Mapped[float]
nox: Mapped[float]

View File

@ -1,5 +1,5 @@
from typing import Optional
from sqlalchemy import Sequence
from sqlalchemy import ForeignKey
from db.models.base import Base, int_pk_incr
@ -8,7 +8,9 @@ from sqlalchemy.orm import Mapped, mapped_column
class ExperimentParameters(Base):
__tablename__ = 'experiment_parameters'
id: Mapped[int_pk_incr]
id: Mapped[int] = mapped_column(primary_key=True,
autoincrement=True,
server_default=Sequence('experiment_parameters_id_seq', start=11).next_value())
outer_blades_count: Mapped[int]
outer_blades_length: Mapped[float]
outer_blades_angle: Mapped[float]

View File

@ -1,11 +1,14 @@
from db.models.base import Base, int_pk_incr
from sqlalchemy.orm import Mapped
from sqlalchemy import Sequence
from sqlalchemy.orm import Mapped, mapped_column
class LoadParameters(Base):
__tablename__ = 'load_parameters'
id: Mapped[int_pk_incr]
id: Mapped[int] = mapped_column(primary_key=True,
autoincrement=True,
server_default=Sequence('load_parameters_id_seq', start=6).next_value())
load: Mapped[int]
primary_air_consumption: Mapped[float]
secondary_air_consumption: Mapped[float]

View File

@ -1,14 +1,17 @@
from typing import Optional
from sqlalchemy import Sequence
from sqlalchemy import ForeignKey
from db.models.base import Base, int_pk_incr
from db.models.base import Base
from sqlalchemy.orm import Mapped, mapped_column
class RecyclingParameters(Base):
__tablename__ = 'recycling_parameters'
id: Mapped[int_pk_incr]
id: Mapped[int] = mapped_column(primary_key=True,
autoincrement=True,
server_default=Sequence('recycling_parameters_id_seq', start=41).next_value())
load_id: Mapped[Optional[int]] = mapped_column(ForeignKey('load_parameters.id', ondelete='SET NULL'))
recycling_level: Mapped[int]
co2: Mapped[float]

View File

@ -9,13 +9,14 @@ class ChExperimentDBExperimentDataRepository:
async def get_all() -> Optional[list[ChExperimentDBExperimentData]]:
async with async_session() as session:
result = await session.execute(select(ChExperimentDBExperimentData))
return result.scalar.all()
return result.scalars().all()
@staticmethod
async def get_by_id(id_: int) -> Optional[ChExperimentDBExperimentData]:
async with async_session() as session:
result = await session.execute(select(ChExperimentDBExperimentData).where(ChExperimentDBExperimentData.id == id_))
return result.scalars().first()
result = session.get(ChExperimentDBExperimentData, id_)
return result
@staticmethod

View File

@ -9,13 +9,13 @@ class ExperimentDataRepository:
async def get_all() -> Optional[list[ExperimentData]]:
async with async_session() as session:
result = await session.execute(select(ExperimentData))
return result.scalar.all()
return result.scalars().all()
@staticmethod
async def get_by_id(id_: int) -> Optional[ExperimentData]:
async with async_session() as session:
result = await session.execute(select(ExperimentData).where(ExperimentData.id == id_))
return result.scalars().first()
result = session.get(ExperimentData, id_)
return result
@staticmethod

View File

@ -9,13 +9,13 @@ class ExperimentParametersRepository:
async def get_all() -> Optional[list[ExperimentParameters]]:
async with async_session() as session:
result = await session.execute(select(ExperimentParameters))
return result.scalar.all()
return result.scalars().all()
@staticmethod
async def get_by_id(id_: int) -> Optional[ExperimentParameters]:
async with async_session() as session:
result = await session.execute(select(ExperimentParameters).where(ExperimentParameters.id == id_))
return result.scalars().first()
result = session.get(ExperimentParameters, id_)
return result
@staticmethod
async def create(outer_blades_count: int,

View File

@ -1,7 +1,8 @@
from typing import Optional
from sqlalchemy import select
from sqlalchemy.future import select
from db.db_connection import async_session
from db.models.load_parameters_model import LoadParameters
from network.bodies import LoadParametersBody
class LoadParametersRepository:
@ -9,19 +10,19 @@ class LoadParametersRepository:
async def get_all() -> Optional[list[LoadParameters]]:
async with async_session() as session:
result = await session.execute(select(LoadParameters))
return result.scalar.all()
return result.scalars().all()
@staticmethod
async def get_by_id(id_: int) -> Optional[LoadParameters]:
async with async_session() as session:
result = await session.execute(select(LoadParameters).where(LoadParameters.id == id_))
return result.scalars().first()
result = session.get(LoadParameters, id_)
return result
@staticmethod
async def create(load: int,
primary_air_consumption: float,
secondary_air_consumption: float,
gas_inlet_consumption: float):
gas_inlet_consumption: float) -> None:
new_data = LoadParameters(
load=load,
primary_air_consumption=primary_air_consumption,
@ -33,7 +34,16 @@ class LoadParametersRepository:
await session.commit()
@staticmethod
async def create(new_data: LoadParameters):
async def create_from_pydantic(body: LoadParametersBody):
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() as session:
session.add(new_data)
await session.commit()

View File

@ -9,7 +9,7 @@ class RecyclingParametersRepository:
async def get_all() -> Optional[list[RecyclingParameters]]:
async with async_session() as session:
result = await session.execute(select(RecyclingParameters))
return result.scalar.all()
return result.scalars.all()
@staticmethod
async def get_by_id(id_: int) -> Optional[RecyclingParameters]:

View File

@ -1,4 +1,3 @@
version: '3.8'
services:
db:

18
main.py
View File

@ -47,22 +47,24 @@ def init_db_data():
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@app.post('/test')
def test(data = LoadParametersBody):
@app.post('/create')
async def test(data: LoadParametersBody):
try:
asyncio.run(LoadParametersRepository.create(data))
return {"status": "success", "message": "test +"}
await LoadParametersRepository.create_from_pydantic(data)
return {"status": "success", "message": "Новая запись успешно добавлена"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@app.get('/all')
def get_all():
async def get_all():
try:
result = asyncio.run(LoadParametersRepository.get_all())
result = await LoadParametersRepository.get_all()
if result is not None:
return {"status": "success", "data": [LoadParametersBody.model_validate(param) for param in result]}
# return {"status": "success", "data": [LoadParametersBody.model_validate(param) for param in result]}
return result
else:
return {"status": "success", "message":"result is not None"}
except Exception as e:

View File

@ -1,12 +1,9 @@
from pydantic import BaseModel
from pydantic import BaseModel, ConfigDict
class LoadParametersBody(BaseModel):
id:int
model_config = ConfigDict(from_attributes=True)
load:int
primary_air_consumption: float
secondary_air_consumption:float
gas_inlet_consumption:float
class Config:
from_attributes = True # Позволяет Pydantic работать с объектами SQLAlchemy
gas_inlet_consumption:float