list medical card base
This commit is contained in:
@@ -1,36 +0,0 @@
|
||||
import uuid
|
||||
from typing import Any
|
||||
import datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects.postgresql import UUID, ARRAY
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import relationship, DeclarativeBase
|
||||
from sqlalchemy.sql.schema import ForeignKey
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
class BaseModel(Base):
|
||||
__abstract__ = True
|
||||
|
||||
id = sa.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
|
||||
created_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now())
|
||||
updated_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now(), onupdate=datetime.datetime.now())
|
||||
|
||||
class MedicalCard(BaseModel):
|
||||
number = sa.Column(sa.String(100), nullable=False)
|
||||
checkups = relationship('Checkup', back_populates='medical_card')
|
||||
confidant_persons = sa.Column(ARRAY(UUID(as_uuid=True)))
|
||||
|
||||
|
||||
class Checkup(BaseModel):
|
||||
medical_card_id = sa.Column(UUID(as_uuid=True), sa.ForeignKey("medical_cards.id"), nullable=False)
|
||||
medical_card = relationship('MedicalCard', back_populates='medical_cards')
|
||||
medic_id = sa.Column(UUID(as_uuid=True))
|
||||
claims = sa.Column(ARRAY(String)) # жалобы
|
||||
allergies = sa.Column(ARRAY(String)) # аллергологический анамнез
|
||||
diseases = sa.Column(ARRAY(String)) # перенесенные и сопутствующие заболевания
|
||||
medicines = sa.Column(ARRAY(String)) # принимаемые лекарственные препараты
|
||||
disease_process = sa.Column(sa.Text) # Развитие настоящего заболевания
|
||||
visual_inspection = sa.Column(ARRAY(String)) # внешний осмотр
|
||||
33
src/medical_info/config.py
Normal file
33
src/medical_info/config.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from functools import lru_cache
|
||||
from typing import Optional
|
||||
from os import getenv
|
||||
from pydantic import BaseSettings, PostgresDsn
|
||||
|
||||
class Settings(BaseSettings):
|
||||
database_url: Optional[PostgresDsn]
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
settings = Settings() # type: ignore
|
||||
|
||||
if (db := getenv("POSTGRES_DB")) is not None:
|
||||
# settings.database_url = PostgresDsn.build(
|
||||
# scheme="postgresql",
|
||||
# user=settings.database_url.user,
|
||||
# password=settings.database_url.password,
|
||||
# host=settings.database_url.host,
|
||||
# port=settings.database_url.port,
|
||||
# path=f"/{db}",
|
||||
# )
|
||||
settings.database_url = PostgresDsn.build(
|
||||
scheme="postgresql",
|
||||
user='barbie',
|
||||
password='redStar4,1',
|
||||
host='localhost',
|
||||
port='5432',
|
||||
path=f"/{db}",
|
||||
)
|
||||
elif (db := getenv("CONNECTION_STRING")) is not None:
|
||||
settings.database_url = getenv("CONNECTION_STRING")
|
||||
|
||||
return settings
|
||||
53
src/medical_info/db/models.py
Normal file
53
src/medical_info/db/models.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import uuid
|
||||
from typing import Any
|
||||
import datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects.postgresql import UUID, ARRAY, JSONB
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import relationship, DeclarativeBase
|
||||
from sqlalchemy.sql.schema import ForeignKey
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
class BaseModel(Base):
|
||||
__abstract__ = True
|
||||
|
||||
id = sa.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
|
||||
created_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now())
|
||||
updated_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now(), onupdate=datetime.datetime.now())
|
||||
|
||||
class MedicalCard(BaseModel):
|
||||
__tablename__ = 'medical_cards'
|
||||
|
||||
number = sa.Column(sa.String(100), nullable=False)
|
||||
checkups = relationship('Checkup', back_populates='medical_card')
|
||||
health_maps = relationship('HealthMap', back_populates='medical_card')
|
||||
confidant_persons = sa.Column(ARRAY(UUID(as_uuid=True)))
|
||||
person_id = sa.Column(UUID(as_uuid=True), nullable=False)
|
||||
|
||||
|
||||
class Checkup(BaseModel):
|
||||
__tablename__ = 'checkups'
|
||||
|
||||
medical_card_id = sa.Column(UUID(as_uuid=True), sa.ForeignKey("medical_cards.id"), nullable=False)
|
||||
medical_card = relationship('MedicalCard', back_populates='checkups')
|
||||
medic_id = sa.Column(UUID(as_uuid=True))
|
||||
claims = sa.Column(ARRAY(sa.String)) # жалобы
|
||||
allergies = sa.Column(ARRAY(sa.String)) # аллергологический анамнез
|
||||
diseases = sa.Column(ARRAY(sa.String)) # перенесенные и сопутствующие заболевания
|
||||
medicines = sa.Column(ARRAY(sa.String)) # принимаемые лекарственные препараты
|
||||
disease_process = sa.Column(sa.Text) # Развитие настоящего заболевания
|
||||
visual_inspection = sa.Column(ARRAY(sa.String)) # внешний осмотр
|
||||
|
||||
dental_formula = sa.Column(JSONB)
|
||||
dental_formula_ext = sa.Column(JSONB)
|
||||
|
||||
class HealthMap(BaseModel):
|
||||
__tablename__ = 'health_maps'
|
||||
|
||||
comment = sa.Column(sa.Text)
|
||||
attachments = sa.Column(ARRAY(sa.String))
|
||||
medical_card_id = sa.Column(UUID(as_uuid=True), sa.ForeignKey("medical_cards.id"), nullable=False)
|
||||
medical_card = relationship('MedicalCard', back_populates='health_maps')
|
||||
1
src/medical_info/db/schemas/__init__.py
Normal file
1
src/medical_info/db/schemas/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .medical_card import *
|
||||
11
src/medical_info/db/schemas/medical_card.py
Normal file
11
src/medical_info/db/schemas/medical_card.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class MedicalCard(BaseModel):
|
||||
number: str
|
||||
person_id: str
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
class MedicalCardCreate(BaseModel):
|
||||
person_id: str
|
||||
23
src/medical_info/db/session.py
Normal file
23
src/medical_info/db/session.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from functools import lru_cache
|
||||
from typing import Generator
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
|
||||
from medical_info.config import get_settings
|
||||
|
||||
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
|
||||
|
||||
@lru_cache
|
||||
def create_session() -> scoped_session:
|
||||
Session = scoped_session(
|
||||
sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
)
|
||||
return Session
|
||||
|
||||
def get_session() -> Generator[scoped_session, None, None]:
|
||||
Session = create_session()
|
||||
try:
|
||||
yield Session
|
||||
finally:
|
||||
Session.remove()
|
||||
@@ -1,9 +1,16 @@
|
||||
from fastapi import Depends
|
||||
from fastapi.routing import APIRouter
|
||||
from typing import List
|
||||
|
||||
from medical_info.db import models
|
||||
from medical_info.db.schemas import MedicalCard
|
||||
from medical_info.services import MedicalCardService, get_medical_cards_service
|
||||
|
||||
router = APIRouter(prefix='/medical_cards')
|
||||
|
||||
@router.get('/')
|
||||
def list_persons():
|
||||
return "ok"
|
||||
@router.get('/', response_model=List[MedicalCard])
|
||||
def list_medical_cards(
|
||||
medical_cards_service: MedicalCardService = Depends(get_medical_cards_service)
|
||||
) -> List[models.MedicalCard]:
|
||||
return medical_cards_service.list()
|
||||
|
||||
|
||||
11
src/medical_info/services/__init__.py
Normal file
11
src/medical_info/services/__init__.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from medical_info.db.session import get_session
|
||||
|
||||
from .medical_cards import MedicalCardService
|
||||
|
||||
def get_medical_cards_service(db_session: Session = Depends(get_session)) -> MedicalCardService:
|
||||
return MedicalCardService(db_session)
|
||||
|
||||
__all__ = ('get_medical_cards_service')
|
||||
52
src/medical_info/services/base.py
Normal file
52
src/medical_info/services/base.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from typing import Any, Generic, List, Optional, Type, TypeVar
|
||||
|
||||
import sqlalchemy
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from medical_info.db.models import Base
|
||||
|
||||
ModelType = TypeVar('ModelType', bound=Base)
|
||||
CreateSchemaType = TypeVar('CreateSchemaType', bound=BaseModel)
|
||||
UpdateSchemaType = TypeVar('UpdateSchemaType', bound=BaseModel)
|
||||
|
||||
class BaseService(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
||||
def __init__(self, model: Type[ModelType], db_session: Session):
|
||||
self.model = model
|
||||
self.db_session = db_session
|
||||
|
||||
def get(self, id: Any) -> Optional[ModelType]:
|
||||
obj: Optional[ModelType] = self.db_session.get(self.model, id)
|
||||
if obj is None:
|
||||
raise HTTPException(status_code=404, detail='NotFound')
|
||||
return obj
|
||||
|
||||
def list(self) -> List[ModelType]:
|
||||
objs: List[ModelType] = self.db_session.query(self.model).all()
|
||||
return objs
|
||||
|
||||
def create(self, obj: CreateSchemaType) -> ModelType:
|
||||
db_obj: ModelType = self.model(**obj.dict())
|
||||
self.db_session.add(db_obj)
|
||||
try:
|
||||
self.db_session.commit()
|
||||
except sqlalchemy.exc.IntegrityError as e:
|
||||
self.db_session.rollback()
|
||||
if 'duplicate key' in str(e):
|
||||
raise HTTPException(status_code=409, detail='Conflict Error')
|
||||
else:
|
||||
raise e
|
||||
return db_obj
|
||||
|
||||
def update(self, id: Any, obj: UpdateSchemaType) -> Optional[ModelType]:
|
||||
db_obj = self.get(id)
|
||||
for column, value in obj.dict(exclude_unset=True).items():
|
||||
setattr(db_obj, column, value)
|
||||
self.db_session.commit()
|
||||
return db_obj
|
||||
|
||||
def delete(self, id: Any) -> None:
|
||||
db_obj = self.db_session.get(self.model, id)
|
||||
self.db_session.delete(db_obj)
|
||||
self.db_session.commit()
|
||||
9
src/medical_info/services/medical_cards.py
Normal file
9
src/medical_info/services/medical_cards.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from typing import Any
|
||||
from medical_info.db.models import MedicalCard
|
||||
from medical_info.db.schemas import MedicalCardCreate
|
||||
from medical_info.services.base import BaseService
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
class MedicalCardService(BaseService[MedicalCard, MedicalCardCreate, Any]):
|
||||
def __init__(self, db_session: Session):
|
||||
super(MedicalCardService, self).__init__(MedicalCard, db_session)
|
||||
Reference in New Issue
Block a user