Esempio n. 1
0
def patient_list():
    start = request.args.get('start', 0)
    length = request.args.get('length', 100)

    start = int(start)
    length = int(length)

    count = db.engine.execute("select count(*) from T_Patients").scalar()
    result = db.engine.execute("select * from T_Patients limit %d, %d" %
                               (start, length))
    plist = []
    total = count

    for row in result:
        patient = p.Patient({'id': row['pat_id']})

        name = hn.HumanName()
        name.given = [row['pat_first']]
        name.family = row['pat_last']
        patient.name = [name]

        address = addr.Address()
        address.city = row['pat_city']
        address.state = row['pat_state']
        address.postalCode = row['pat_zip']
        address.district = row['pat_address']
        patient.address = [address]

        patient.gender = row['pat_gender']
        patient.birthDate = fd.FHIRDate(
            datetime.strftime(row['pat_birthdate'], "%Y-%m-%d"))
        # patient.maritalStatus = row['pat_marital']
        plist.append(patient.as_json())

    return jsonify(results=plist, total=total)
Esempio n. 2
0
def patient(id):
    # https://{FHIR Base URL}/Patient/{id}?
    # name={name}&
    # family={family name}&
    # gender={gender}&
    # _format=json

    # TODO: query params
    name = request.args.get('name', None)
    family = request.args.get('family', None)
    gender = request.args.get('gender', None)

    # TODO: connect to database to search patient

    result = db.engine.execute("select * from T_Patients limit 1")
    names = []
    for row in result:
        patient = p.Patient({'id': row['pat_id']})
        name = hn.HumanName()
        name.given = [row['pat_first']]
        name.family = row['pat_last']
        patient.name = [name]

        address = addr.Address()
        address.city = row['pat_city']
        address.state = row['pat_state']
        address.postalCode = row['pat_zip']
        address.district = row['pat_address']
        patient.address = [address]

        patient.gender = row['pat_gender']
        patient.birthDate = fd.FHIRDate(
            datetime.strftime(row['pat_birthdate'], "%Y-%m-%d"))
        patient.maritalStatus = row['pat_marital']
    return jsonify(result=patient.as_json())
Esempio n. 3
0
    def __init__(self, Organization=None):
        """
        Uses fhirclient.models to create and post practitoner resource. Currently, using class variables.

        :param smart: fhirclient.client.FHIRClient object.
        :returns: practitioner id created by server
        """
        if Organization is None:
            self.Organization = generateorganization.GenerateOrganization(
            ).Organization
        else:
            self.Organization = Organization

        Practitioner = pr.Practitioner()
        PractitionerQualification = pr.PractitionerQualification()
        CodeableConcept = cc.CodeableConcept()
        Coding = c.Coding()
        Coding.code = random.choice(['MD', 'DO'])
        Coding.system = 'https://www.hl7.org/fhir/v2/0360/2.7/index.html'
        CodeableConcept.coding = [Coding]
        PractitionerQualification.code = CodeableConcept
        Practitioner.qualification = [PractitionerQualification]
        name = hn.HumanName()
        self.family, self.given, Practitioner.gender = self._generate_person()
        name.family = [self.family]
        name.given = [self.given]
        Practitioner.name = name
        self._validate(Practitioner)
        self.response = self.post_resource(Practitioner)
        Practitioner.id = self._extract_id()
        self.Practitioner = Practitioner
        print(self)
 def addPatientToServer(self, given_name, family_name):
     patient = p.Patient()
     name = hn.HumanName()
     name.given = [given_name]
     name.family = [family_name]
     patient.name = [name]
     result_json = patient.create(self.smart.server)
     patient.id = self.getCreatedId(result_json)
     return patient.id
 def to_fhir_obj(self):
     patient = p.Patient()
     identifier = p.identifier.Identifier()
     identifier.value = self.id
     patient.identifier = [identifier]
     name = hn.HumanName()
     name.given = [self.first_name]
     name.family = self.last_name
     patient.name = [name]
     patient.gender = self.sex
     patient.birthDate = fd.FHIRDate(str(datetime.utcnow().date()))
     # prints patient's JSON representation, now with id and name
     address = a.Address()
     address.state = self.state
     address.district = self.district
     patient.address = [address]
     json = patient.as_json()
     return patient
def mkpatient():
    """
    make a Patient resource using the data model
    """
    import fhirclient.models.patient as p
    import fhirclient.models.humanname as hn
    patient = p.Patient()
    # patient.id = 'patient-1'
    # print(patient.id)
    # prints `patient-1`
    name = hn.HumanName()
    name.given = ['Peter']
    name.family = 'Parker'
    patient.name = [name]
    # print(json.dumps(patient.as_json(), indent=4))
    patient.uuid = uuid.uuid4().urn
    print(patient.uuid)
    return (patient)
Esempio n. 7
0
def fhir():
    import fhirclient.models.patient as p
    import fhirclient.models.humanname as hn
    patient = p.Patient({'id': 'patient-1'})
    print(patient.id)
    # prints `patient-1`

    name = hn.HumanName()
    name.given = ['Peter']
    name.family = 'Parker'
    patient.name = [name]

    print(mongodb)

    print(patient.as_json())
    dict01 = patient.as_json()
    ret = mongodb.a.insert_one(dict01)
    print(ret)
    ret = mongodb.a.find()
    for i in ret:
        print(i)
    print('111111111111111111')

    import json
    import fhirclient.models.patient as p
    with open('/home/python/Desktop/odk/patient-example.json', 'r') as h:
        pjs = json.load(h)
    patient = p.Patient(pjs)
    dict02 = patient.as_json()

    ret = mongodb.a.insert_one(dict02)
    print(ret)
    ret = mongodb.a.find()
    for i in ret:
        print(i)
    print('2222222222222222')
    print(patient.name[0].given)
    print(patient.name)
    print(patient.gender)
    print(patient.photo)
    print(patient.address)
    print("-------------------------")
    # prints patient's given name array in the first `name` property
    return ret_data(200, '请求成功', 1000)
Esempio n. 8
0
def fhir_gen_humanname(use='official', first_name=None, last_name=None, middle_name=None, suffix=None, prefix=None):
    """
    Helper function to generate a fhirclient HumanName class object from standard person attributes
    :param use:
    :param first_name:
        String representation of person first name
    :param last_name:
        String representation of person last name
    :param middle_name:
        String representation of person middle name
    :param suffix:
        String representation of name suffix
    :param prefix:
        String representation of name prefix
    :return:
        fhirclient HumanName class object
    """
    hn = humanname.HumanName()
    if use:
        hn.use = use
    hn.family = last_name
    given_name = []
    if first_name:
        given_name.append(first_name)
    if middle_name:
        given_name.append(middle_name)
    if given_name:
        hn.given = given_name
    if suffix:
        hn.suffix = [suffix]
    if prefix:
        hn.prefix = [prefix]

    hn.text = '{}{}{}{}'.format(last_name + ',' if last_name else '',
                                ' ' + first_name if first_name else '',
                                ' ' + middle_name if middle_name else '',
                                ' ' + suffix if suffix else '')
    return hn
Esempio n. 9
0
df_a['date_of_birth'] = df_a['date_of_birth'].apply(
    lambda x: x.strftime('%Y-%m-%d') if not pd.isnull(x) else '')

print(df_a.head())

# In[6]:

# default server/path
server = "https://localhost:3000/Patient"
# 3 records, modify if more are required
limit = 100
for index, row in itertools.islice(df_a.iterrows(), limit):
    # for index, row in df_a.iterrows():
    patient = p.Patient()  # not using rec_id as pandas id, leaving empty
    patient.gender = row['sex']
    name = hn.HumanName()
    name.given = [row['given_name']]
    name.family = row['surname']
    name.use = 'official'
    patient.name = [name]
    phone = cp.ContactPoint()
    phone.system = 'phone'
    phone.value = row['phone_number']
    patient.telecom = [phone]
    patient.birthDate = fd.FHIRDate(row['date_of_birth'])
    emr = ident.Identifier()
    emr.system = 'http://clientregistry.org/openmrs'
    emr.value = row['rec_id']
    art = ident.Identifier()
    art.system = 'http://system1/artnumber'
    art.value = row['art_number']
Esempio n. 10
0
def createPractitioner(dohmpifield, record):
    #extract fields from dohmpi from database
    field = []
    for i in range(len(dohmpifield)):
        f1, = dohmpifield[i]  # dohmpi loads from db as a list of onetuples.
        field.append(f1)  # we make a traditional list to refer to.

    fnamei = field.index('provider_first')
    lnamei = field.index('provider_last')
    genderi = field.index('provider_gender_cd')
    deathyi = field.index('deathccyy')
    deathmi = field.index('deathmm')
    deathdi = field.index('deathdd')
    birthi = field.index('provider_dob_dob')
    provi = field.index('provider_license_no')

    # record is one record from the postgres db
    import fhirclient.models.practitioner as p

    # set practitioner id as provider licence numberS
    p = p.Practitioner({'id': record[provi]})

    # resolve name
    import fhirclient.models.humanname as hn
    name = hn.HumanName()
    name.given = [record[fnamei]]
    name.family = [record[lnamei]]
    p.name = name

    # resolve gender
    if (record[genderi] == "1"):
        p.gender = 'male'
    elif (record[genderi] == "2"):
        p.gender = 'female'
    else:
        p.gender = 'unknown'

    # build and resolve birthdate
    birthdate = record[birthi]
    bsep1 = birthdate.index("/")
    bsep2 = birthdate.index("/", bsep1 + 1)
    birthdate = birthdate[-4:] + "-" + birthdate[0:bsep1] + "-" + birthdate[
        bsep1 + 1:bsep2]
    p.birthDate = fhirclient.models.fhirdate.FHIRDate(birthdate)

    # build and resolve death date
    tz = "00:00:00-0600"  # Utah is in the Mountain Time Zone, setting time as midnight.
    yyyy = record[deathyi]
    mm = record[deathmi]
    if (len(mm) < 2):
        mm = "0%s" % mm
    dd = record[deathdi]
    if (len(dd) < 2):
        dd = "0%s" % dd
    deathdate = "%s-%s-%sT%s" % (yyyy, mm, dd, tz)
    deathdate = fhirclient.models.fhirdate.FHIRDate(deathdate)

    # Create period
    import fhirclient.models.period as per
    per = per.Period()
    per.start = deathdate

    import fhirclient.models.fhirreference as ref

    location = ref.FHIRReference()
    location.reference = 'http://fhir.ehoth.net/deceased'
    location.display = 'deceased'

    # Create role
    import fhirclient.models.practitioner as r
    role = r.PractitionerPractitionerRole()
    role.healthcareservice = 'deceased'
    role.location = [location]
    role.period = per

    role.managingOrganization = location

    #print role.as_json()

    p.practitionerRole = [role]

    # return practitioner.
    return p
Esempio n. 11
0
    def _generate_patient_fhir_object(self):
        """Creates a test patient using fhirclient.models."""
        Patient = p.Patient()
        HumanName = hn.HumanName()
        HumanName.family = [self.name_last]
        HumanName.given = [self.name_first]
        Patient.name = [HumanName]

        Patient.gender = self.gender

        birthDay = fd.FHIRDate()
        birthDay.date = self.bday
        Patient.birthDate = birthDay

        Address = a.Address()
        Address.country = 'USA'
        Address.postalCode = self.zipcode
        Address.state = self.state
        Address.city = self.city
        Address.line = [f'{self.address_number} {self.address_street}']
        Address.use = 'home'
        Address.type = 'postal'
        Patient.active = True
        Patient.address = [Address]
        PatientCommunication = p.PatientCommunication()
        PatientCommunication.language = self._create_FHIRCodeableConcept(
            'en-US', 'urn:ietf:bcp:47', 'English')
        # PatientCommunication.language = self._create_FHIRCodeableConcept('en-US','http://hl7.org/fhir/ValueSet/languages','English')
        PatientCommunication.preferred = True
        Patient.communication = [PatientCommunication]

        race = e.Extension()
        race.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race'
        us_core = e.Extension()
        us_core.url = 'ombCategory'
        us_core.valueCoding = self._create_FHIRCoding(
            self.race_code, 'urn:oid:2.16.840.1.113883.6.238',
            self.race_description)
        race_detailed = e.Extension()
        race_detailed.url = 'detailed'
        race_detailed.valueCoding = self._create_FHIRCoding(
            self.race_code, 'urn:oid:2.16.840.1.113883.6.238',
            self.race_description)
        race_text = e.Extension()
        race_text.url = 'text'
        race_text.valueString = self.race_description
        race.extension = [us_core, race_detailed, race_text]

        ethnicity = e.Extension()
        ethnicity.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity'

        us_core = e.Extension()
        us_core.url = 'ombCategory'
        us_core.valueCoding = self._create_FHIRCoding(
            self.ethnicity_code, 'urn:oid:2.16.840.1.113883.6.238',
            self.ethnicity_description)
        ethnicity_text = e.Extension()
        ethnicity_text.url = 'text'
        ethnicity_text.valueString = self.ethnicity_description
        ethnicity.extension = [us_core, ethnicity_text]

        Patient.extension = [race, ethnicity]
        Patient.managingOrganization = self._create_FHIRReference(
            self.Organization)

        self._validate(Patient)
        self.response = self.post_resource(Patient)
        Patient.id = self._extract_id()
        self.Patient = Patient
        print(self)
Esempio n. 12
0
def createPatient(dohmpifield, record):
    #extract fields from dohmpi from database
    field = []
    for i in range(len(dohmpifield)):
        f1, = dohmpifield[i]  # dohmpi loads from db as a list of onetuples.
        field.append(f1)  # we make a traditional list to refer to.

    fnamei = field.index('provider_first')
    lnamei = field.index('provider_last')
    genderi = field.index('provider_gender_cd')
    deathyi = field.index('deathccyy')
    deathmi = field.index('deathmm')
    deathdi = field.index('deathdd')
    birthi = field.index('provider_dob_dob')
    provi = field.index('provider_license_no')

    # record is one record from the postgres db
    import fhirclient.models.patient as p

    # set patient id as provider licence numberS
    pid = record[provi]
    p = p.Patient({})
    import fhirclient.models.identifier as idf
    identifier = idf.Identifier()
    identifier.value = pid
    p.identifier = [identifier]

    # resolve name
    import fhirclient.models.humanname as hn
    name = hn.HumanName()
    name.given = [record[fnamei]]
    name.family = [record[lnamei]]
    p.name = [name]
    #[name.family, name.given]

    # resolve gender
    if (record[genderi] == "1"):
        p.gender = 'male'
    elif (record[genderi] == "2"):
        p.gender = 'female'
    else:
        p.gender = 'unknown'

    # build and resolve birthdate
    birthdate = record[birthi]
    bsep1 = birthdate.index("/")
    bsep2 = birthdate.index("/", bsep1 + 1)
    year = birthdate[-4:]
    month = birthdate[0:bsep1]
    if (len(month) < 2):
        month = "0%s" % month
    date = birthdate[bsep1 + 1:bsep2]
    if (len(date) < 2):
        date = "0%s" % date
    birthdate = year + "-" + month + "-" + date
    p.birthDate = fhirclient.models.fhirdate.FHIRDate(birthdate)

    # build and resolve death date
    tt = "12:00:00"  #Setting time to noon
    yyyy = record[deathyi]
    mm = record[deathmi]
    if (len(mm) < 2):
        mm = "0%s" % mm
    dd = record[deathdi]
    if (len(dd) < 2):
        dd = "0%s" % dd
    deathdate = "%s-%s-%sT%s" % (yyyy, mm, dd, tt)
    deathdate = fhirclient.models.fhirdate.FHIRDate(deathdate)

    # Create period
    import fhirclient.models.period as per
    per = per.Period()
    per.start = deathdate

    p.deceasedBoolean = True
    p.deceasedDateTime = deathdate

    return p
Esempio n. 13
0
def patient():
    user = get_jwt_identity()
    print("user:"******"name_given"]]
            name.family = request.form["name_family"]
            patient.name = [name]
            # 设置性别 只能是male或者female
            patient.gender = request.form["gender"] if request.form[
                "gender"] == "男" or request.form["女"] == "female" else ""
            # 设置生日
            patient.birthDate = fdate.FHIRDate().with_json(
                request.form["birthDate"])
            # 设置逻辑删除
            patient.active = True
            # 设置地址
            patient.address = [ad.Address({"city": request.form["city"]})]
            ret = mongodb.basic_information.insert_one(patient.as_json())
            print(ret)
            return ret_data(200, '请求成功', 1003)
        else:
            return ret_data(200, "请求成功", 2008)

    elif request.method == 'GET':
        dict01 = mongodb.basic_information.find_one({
            'id': str(user),
            'active': True
        })
        if dict01 is None:
            return ret_data(200, '请求成功', 2011)
        dict02 = {}
        del dict01['_id']
        dict02['city'] = dict01['address'][0]['city']
        dict02['birthDate'] = dict01['birthDate']
        dict02['gender'] = dict01['gender']
        dict02['name'] = str(dict01['name'][0]['family']) + str(
            dict01['name'][0]['given'][0])
        return ret_data(200, '请求成功', 1005, **dict02)

    elif request.method == 'DELETE':
        count = 0
        for i in patientList:
            print(i['active'])
            if i['active'] is True:
                count += 1
        if count >= 1:
            mongodb.basic_information.update_one(
                {
                    'id': str(user),
                    'active': True
                }, {'$set': {
                    'active': False
                }})
            # mongodb.basic_information.delete_one({'id':str(user)})
            return ret_data(200, '请求成功', 1004)
        else:
            return ret_data(200, '请求成功', 2010)

    elif request.method == 'PUT':
        count = 0
        for i in patientList:
            print(i['active'])
            if i['active'] is True:
                count += 1
        if count == 1:
            patient = p.Patient({'id': str(user)})
            # 设置名字
            name = hn.HumanName()
            name.given = [request.form["name_given"]]
            name.family = request.form["name_family"]
            patient.name = [name]
            # 设置性别 只能是male或者female
            patient.gender = request.form["gender"] if request.form[
                "gender"] == "男" or request.form["女"] == "female" else ""
            # 设置生日
            patient.birthDate = fdate.FHIRDate().with_json(
                request.form["birthDate"])
            # 设置逻辑删除
            patient.active = True
            # 设置地址
            patient.address = [ad.Address({"city": request.form["city"]})]
            mongodb.basic_information.update_one({'id': str(user)},
                                                 {'$set': patient.as_json()})
            return ret_data(200, '请求成功', 1006)
        else:
            return ret_data(200, '请求成功', 2009)
    return ret_data(200, '请求成功', 1000, test='hello world')