ref Medical Card List

This commit is contained in:
dderbentsov
2023-08-05 02:43:17 +03:00
parent 2199be3109
commit 687659f42b
7 changed files with 92 additions and 68 deletions

View File

@@ -1,49 +1,57 @@
from typing import Any, List, Optional
from medical_info.db.models import MedicalCard
from medical_info.db.schemas import MedicalCardCreate, MedicalCardBase, MedicalCardResponse, PersonDetail, MedicalCardDetail
from medical_info.db.schemas import (
PersonOut,
MedicalCardOut,
MedicalCardCreate, MedicalCardBase, MedicalCardResponse, MedicalCardDetail)
from medical_info.services.base import BaseService
from sqlalchemy.orm import Session
from pydantic import parse_obj_as
from pydantic.types import UUID4
from medical_info.db import schemas, models
import requests
from starlette.exceptions import HTTPException
import os
import httpx
class MedicalCardService(BaseService[MedicalCard, MedicalCardCreate, Any]):
def __init__(self, db_session: Session):
super(MedicalCardService, self).__init__(MedicalCard, db_session)
LOCAL_PERSONAL_INFO_URL = 'http://localhost:8001/persons'
self.PERSONAL_INFO_URL = os.environ.get('ASTRA-PESONAL-INFORMATION') or LOCAL_PERSONAL_INFO_URL
def list(self, searchstring: str) -> Any:
#TODO установи корректные коды ошибки
if searchstring is None or searchstring == '':
raise HTTPException(status_code=404, detail='searchstring is required')
def get_persons(self, searchstring: str) -> List[PersonOut]:
personal_information_host = os.getenv('ASTRA-PESONAL-INFORMATION')
# personal_information_host = 'http://localhost:8001/persons'
#TODO обобщение хоста personal_info
#TODO обработка ошибок ответа сервиса personal_info
try:
response = httpx.get(f'{self.PERSONAL_INFO_URL}/?full_name={searchstring}')
response.raise_for_status()
except httpx.RequestError as exc:
print(f"Ошибка вызова {exc.request.url!r}.")
raise HTTPException(status_code=500, detail=f"Ошибка вызова {exc.request.url!r}.")
except httpx.HTTPStatusError as exc:
print(f"Ошибка {exc.response.status_code} при запросе {exc.request.url!r}.")
raise HTTPException(status_code=exc.response.status_code, detail=f"Ошибка вызова {exc.request.url!r}.")
person_response = requests.get(f'{personal_information_host}/?full_name={searchstring}')
return parse_obj_as(List[schemas.PersonOut], response.json())
persons = person_response.json()
person_ids = [person['id'] for person in persons]
def list(self, searchstring: str) -> Any:
if searchstring is None or searchstring == '':
raise HTTPException(status_code=409, detail='searchstring is required')
persons = self.get_persons(searchstring)
person_ids = [person.id for person in persons]
if len(person_ids) < 1:
return []
objs = self.db_session.query(models.MedicalCard).filter(models.MedicalCard.person_id.in_(person_ids)).all()
medical_cards = parse_obj_as(List[schemas.MedicalCard], objs)
medical_cards = [medical_card.dict() for medical_card in medical_cards]
medical_card_objs = self.db_session.query(models.MedicalCard).filter(models.MedicalCard.person_id.in_(person_ids)).all()
medical_cards = parse_obj_as(List[MedicalCardOut], medical_card_objs)
res = list()
for m in medical_cards:
person = next(filter(lambda person: str(person["id"]) == str(m["person_id"]) , persons), None)
if person is not None:
m['person'] = {**person}
res.append(m)
return res
for mc in medical_cards:
for p in persons:
if str(mc.person_id) == str(p.id):
mc.person = p
return medical_cards
def get(self, id: UUID4) -> Optional[schemas.MedicalCardDetail]:
obj: Optional[models.MedicalCard] = self.db_session.get(self.model, id)
@@ -51,7 +59,7 @@ class MedicalCardService(BaseService[MedicalCard, MedicalCardCreate, Any]):
raise HTTPException(status_code=404, detail='NotFound')
personal_information_host = os.getenv('ASTRA-PESONAL-INFORMATION')
# personal_information_host = 'http://localhost:8001/persons'
#personal_information_host = 'http://localhost:8001/persons'
#TODO обработка ошибок ответа сервиса personal_info