Exemple #1
0
    def _parse_patients(self, records):
        if not isinstance(records, list):
            name, patient_id, patronymic, surname, gender, birth_date, mobile_number, place, address = records
            return Patient(name, patient_id, patronymic, surname, gender,
                           birth_date, mobile_number, place, address)

        for i in range(len(records)):
            name, patient_id, patronymic, surname, gender, birth_date, mobile_number, place, address = records[
                i]
            records[i] = Patient(name, patient_id, patronymic, surname, gender,
                                 birth_date, mobile_number, place, address)
        return records
Exemple #2
0
    def test_descriptors(self):
        with self.assertRaises(ValueError):
            patient = Patient(mobile='07894565434581')

        with self.assertRaises(TypeError):
            patient = Patient(id='Nathan')

        with self.assertRaises(TypeError):
            patient = Patient(name=1000)

        with self.assertRaises(ValueError):
            patient = Patient(name='Abiira Nathan of Uganda')
Exemple #3
0
def create_patient():
    patient_data = json.loads(request.data)

    doctor = Doctor.query.get(patient_data['doctor_id'])
    if not doctor:
        return jsonify({
            "success": False,
            "description": "doctor id not found"
        }), 404

    patient = Patient(
        name=patient_data["name"],
        age=patient_data["age"],
        address=patient_data["address"],
        email=patient_data["email"],
        examine_report=patient_data["examine_report"],
    )
    patient.doctor = doctor
    try:
        patient.insert()
    except IntegrityError as err:
        print(err)
        return jsonify({
            "success": False,
            "description": "there is patient with the same email"
        }), 200
    except Exception as err:
        # print(err)
        return jsonify({"success": False, "error": str(err)}), 500

    return jsonify({
        "success": True,
        "patient": Patient.query.get(patient.id).format()
    }), 200
def add_patient(request):
    if request.method == 'POST':
        print request.POST
        firstname = request.POST.get('firstname')
        print firstname
        lastname = request.POST.get('lastname')
        age = request.POST.get('age')
        dob = request.POST.get('dob')
        gender = request.POST.get('gender')
        phone = request.POST.get('phone')
        description = request.POST.get('description')
        response_data = {}

        patient = Patient(firstname=firstname,
                          lastname=lastname,
                          age=age,
                          dob=dob,
                          gender=gender,
                          phone=phone,
                          description=description)
        patient.save()

        response_data['result'] = 'Data stored successfully!'
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")
    else:
        return HttpResponse(json.dumps(
            {"nothing to see": "this isn't happening"}),
                            content_type="application/json")
    def add(self, contract_id, clinic_id):
        contract = Contract.query.filter_by(id=contract_id).first()

        if not contract:
            patient_info = self.medsenger_api.get_patient_info(contract_id)

            try:
                patient_id = int(patient_info['id'])
            except:
                raise Exception("No patient info, contract_id = {}".format(contract_id))

            patient = Patient.query.filter_by(id=patient_id).first()
            if not patient:
                patient = Patient(id=patient_id)
                self.db.session.add(patient)

            contract = Contract(id=contract_id, patient_id=patient.id, clinic_id=clinic_id)
            self.db.session.add(contract)

        contract.is_active = True
        contract.clinic_id = clinic_id
        contract.agent_token = self.medsenger_api.get_agent_token(contract_id).get('agent_token')

        self.__commit__()

        return contract
Exemple #6
0
def add_patient(patient_id):
    from forms import PatientForm
    if patient_id:
        id = int(patient_id.replace('P00', '').replace(
            'P0', '').replace('P', ''))
        patient = Patient.query.get(id)
    else:
        patient = Patient()
    form = PatientForm(obj=patient)
    if form.validate_on_submit():
        if 'photo' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['photo']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = uuid.uuid4().hex+'.' + \
                secure_filename(file.filename).split('.')[-1].lower()
            form.photo.data.save(os.path.join(
                app.config['UPLOAD_FOLDER'], 'patients', filename))
            form.populate_obj(patient)
            patient.photo = filename
            patient.gender = Gender(form.gender.data)
            db.session.add(patient)
            db.session.commit()
            url = url_for('patient_profile', patient_id=repr(patient))
            flash(
                'Patient saved with ID: {}, <a href="{}">view patient profile</a>'.format(repr(patient), url))
        return redirect(url_for('add_patient'))
    return render_template('add-patient.html', form=form)
Exemple #7
0
def new_post():
    if (current_user.role != 'desk'):
        return render_template('auth/accessDenied.html')

    if request.method == 'POST':
        patient_ssnId = request.form['ssnId']
        patient_name = request.form['name']
        patient_age = request.form['age']
        patient_admissionDate = request.form['admissionDate']
        patient_bedType = request.form['bedType']
        patient_address = request.form['address']
        patient_city = request.form['city']
        patient_state = request.form['state']
        newPatient = Patient(ssnId=patient_ssnId,
                             name=patient_name,
                             age=patient_age,
                             admissionDate=patient_admissionDate,
                             bedType=patient_bedType,
                             address=patient_address,
                             city=patient_city,
                             state=patient_state)
        db.session.add(newPatient)
        db.session.commit()
        flash('Patient created')
        return redirect('/patients')
    else:
        return render_template('deskExec/newPatient.html')
Exemple #8
0
def registration_details():
    """Remember to specify login required for only Secretaries."""
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        dob = request.form['dob']
        street = request.form['street']
        town = request.form['town']
        parish = request.form['parish']
        phone_num = request.form['phone_num']

        patient_id = str(uuid.uuid4().fields[-1])[:8]

        flash('Paient Registerd')

        patient = Patient(id=patient_id,
                          dob=dob,
                          first_name=first_name,
                          last_name=last_name,
                          street=street,
                          town=town,
                          parish=parish,
                          phone_num=phone_num)
        db.session.add(patient)
        db.session.commit()
        return redirect(url_for('home'))
    """Render the website's registration_details page."""
    return render_template('registration_details.html')
def importDatabase(filename, user):
    '''Imports the uploaded excel file to the database than deletes the excel file
    '''
    df = pd.read_excel(
        os.path.join(current_app.config['UPLOAD_FOLDER'], filename))

    for index, row in df.iterrows():
        new_patient = Patient(user_id=user,
                              status="undiag",
                              diagnose=str(row[3]))
        featureA = Feature(featureName='A',
                           featureValue=str(row[0]),
                           classifier_id=1)
        featureB = Feature(featureName='B',
                           featureValue=str(row[1]),
                           classifier_id=1)
        featureC = Feature(featureName='C',
                           featureValue=str(row[2]),
                           classifier_id=1)
        new_patient.features.append(featureA)
        new_patient.features.append(featureB)
        new_patient.features.append(featureC)
        db.session.add(new_patient)
        db.session.commit()

    os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
Exemple #10
0
def signup(request):
    """
    Sign Up Page, uses built in Sign-Up
    """
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            name = form.cleaned_data.get('name')
            category = form.cleaned_data.get('category')
            user = authenticate(username=username, password=raw_password)
            if category == "doctor":
                doctor = Doctor(user=user, name=name)
                doctor.save()
            if category == "pharmacist":
                pharmacist = Pharmacist(user=user, name=name)
                pharmacist.save()
            if category == "patient":
                patient = Patient(user=user, name=name)
                patient.save()
            login(request, user)
            return redirect('/pharm/profile')
    else:
        form = SignUpForm()
    return render(request, 'pharmeasyflow/signup.html', {'form': form})
 def deserialize(self, session):
     race_ext, ethnicity_ext = None, None
     for ext in self.raw_data.get("extension", []):
         if (
             ext["url"]
             == "http://hl7.org/fhir/us/core/StructureDefinition/us-core-race"
         ):
             race_ext = ext
         if (
             ext["url"]
             == "http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity"
         ):
             ethnicity_ext = ext
     return Patient(
         source_id=self.raw_data["id"],
         birth_date=self.raw_data["birthDate"],
         gender=self.raw_data["gender"],
         country=self.raw_data["address"][0]["country"]
         if "address" in self.raw_data and "country" in self.raw_data["address"][0]
         else None,
         race_code=race_ext["valueCodeableConcept"]["coding"][0]["code"]
         if race_ext
         else None,
         race_code_system=race_ext["valueCodeableConcept"]["coding"][0]["system"]
         if race_ext
         else None,
         ethnicity_code=ethnicity_ext["valueCodeableConcept"]["coding"][0]["code"]
         if ethnicity_ext
         else None,
         ethnicity_code_system=ethnicity_ext["valueCodeableConcept"]["coding"][0][
             "system"
         ]
         if ethnicity_ext
         else None,
     )
Exemple #12
0
def index():
    form = PatientForm()
    patients = Patient.query.all()
    #
    # if form.refresh.data:
    #     flash(u'Làm sạch thông tin OK')

    if form.view_all.data:
        patients = Patient.query.all()

    elif form.add_new.data:
        if form.validate_on_submit():
            new_patient = Patient(form.patient_name.data,
                                  form.patient_phone.data,
                                  form.patient_age.data,
                                  form.patient_gender.data,
                                  form.patient_address.data,
                                  form.patient_history.data,
                                  form.patient_family_history.data)
            db.session.add(new_patient)
            db.session.commit()

            # patients = [new_patient]
            flash(u'Thêm mới thành công:' + form.patient_name.data)
        else:
            flash(u"Error: Vui lòng điền thông tin")

    elif form.update.data:
        if form.validate_on_submit():
            updated_patient = models.Patient.query.filter_by(id=int(form.patient_id.data)).first()

            updated_patient.patient_name = form.patient_name.data
            updated_patient.patient_phone = form.patient_phone.data
            updated_patient.patient_age = form.patient_age.data
            updated_patient.patient_gender = form.patient_gender.data
            updated_patient.patient_address = form.patient_address.data
            updated_patient.patient_history = form.patient_history.data
            updated_patient.patient_family_history = form.patient_family_history.data
            db.session.commit()

            # patients = [updated_patient]
            flash(u'Cập nhật thành công: ' + form.patient_name.data)
        else:
            flash(u"Error: Vui lòng điền thông tin")

    elif form.delete.data:
        if form.validate_on_submit():
            delete_patient = models.Patient.query.filter_by(id=int(form.patient_id.data)).first()

            db.session.delete(delete_patient)
            db.session.commit()

            patients = [delete_patient]
            flash(u'Xóa thành công:' + form.patient_name.data)
        else:
            flash(u"Error: Vui lòng điền thông tin")

    return render_template('index.html',
                           form=form,
                           patients=patients)
def importDatabase(filename, user):
    '''Imports the uploaded excel file to the database than deletes the excel file
    '''
    df = pd.read_excel(
        os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
    user_id = _request_ctx_stack.top.current_user.get('sub')
    classifier = Classifier.query.filter_by(user_id=user_id).first()

    rows = df.shape[1]

    for index, row in df.iterrows():
        new_patient = Patient(user_id=user,
                              status="undiag",
                              diagnose=str(row[row.size - 1]))
        for idx, r in enumerate(row):
            if (idx != row.size - 1):
                feature = Feature(featureName=df.columns[idx],
                                  featureValue=str(r),
                                  classifier_id=classifier.id)
                new_patient.features.append(feature)

        db.session.add(new_patient)
        db.session.commit()

    r = Feature.query.with_entities(
        Feature.featureName).filter_by(classifier_id=classifier.id).distinct()
    classifier.numberOfFeatureTypes = r.count()
    db.session.add(classifier)
    db.session.commit()

    os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
Exemple #14
0
def create_edited_patient(hospital_id,patient_id):
    query = db.select(Patient).where(Patient.id==patient_id)
    patient = db.session.execute(query).first()[0]
    updated_patient = Patient(patient_id, patient.name,
        patient.surname,
        patient.dni,
        patient.hospital_id)
    return render_template("edit.html",hospital=hospital_id, patient= updated_patient)
Exemple #15
0
 def putItem(self, PatientName):
     PatientId = "p-" + uuid.uuid4().hex
     info = {
         DATASTORE_COLUMN_PATIENT_ID: PatientId,
         DATASTORE_COLUMN_PATIENT_NAME: PatientName
     }
     Patient().createPatient(info)
     return PatientId
Exemple #16
0
def patient_all():
    if request.method == "GET":
        records = Patient.select()
        return template("index.html", items=records)

    elif request.method == "POST":
        json = request.POST

        # check to see if request has provided all necessary values to create object
        #

        name = json["pname"]
        surname = json["surname"]
        dob = json["dob"]
        gp = GP[app.config["user_id"]]
        status = True
        city = json["city"]
        district = json["district"]

        address = Address(cityName=city,
                          districtName=district,
                          districtCode="fix this")

        patient = Patient(name=name,
                          sex="fix this",
                          dob=dob,
                          address=address,
                          gp=gp,
                          status=status)
        #save progress
        db.commit()

        #redirect to the newly created patient's page
        redirect("/patient/{}".format(patient.id))

    elif request.method == "DELETE":

        patient_id = request.POST.id.strip()
        try:
            patient = Patient[patient_id]
        except:
            return "Patient does not exist"
        patient.delete()

    elif request.method == "PUT":
        json = request.POST
        update = json["update"]
        value = json["value"]
        id = json["id"]
        with db_session():
            try:
                patient = Patient[id]
            except:
                return {"message": 'patient not found'}
            setattr(patient, update, value)
            return {"message": "patient updated"}
    return {"message": "missing token"}
Exemple #17
0
    def _get_all_patients(self):
        url = 'https://drchrono.com/api/patients'

        # Fetch the objects one "page" at a time until they are all loaded
        while url:
            data = requests.get(url, headers=self.headers).json()
            for item in data['results']:
                Patient().save_from_dict(item)
            url = data['next']  # Value = None on the last page
Exemple #18
0
def create_patient():
    'Api end-point for creating a new user'
    if not request.form: 
        return ''
    db.session.add(Patient(**request.form))
    db.session.commit()
    p = db.session.query(Patient).order_by(Patient.patient_id.desc()).first()
    url = url_for('patients.view_patient', patient_id=p.patient_id)
    return redirect(url, code=302)
Exemple #19
0
 def test_patient_model(self):
     """Does basic model work?"""
     p = Patient(first_name="Nonkoff",
                 last_name="Jegrold",
                 date_of_birth=datetime.date(1999, 1, 19))
     db.session.add(p)
     db.session.commit()
     """Doctor should have no patients & no medications"""
     self.assertEqual(len(p.medications), 0)
     self.assertEqual(len(p.medications_given), 0)
Exemple #20
0
def create_patient(user_data):
    user = Patient(
            first_name = user_data["first_name"],
            last_name = user_data["last_name"],
            email = user_data["email"],
            phone_number = user_data["phone_number"],
            password_hash = create_password_hash( user_data["password"] )
        )

    return user
Exemple #21
0
 def _get_patient(self, mongo_patient):
     cancer_images = self._get_cancer_images(mongo_patient)
     return Patient(id=str(mongo_patient["_id"]),
                    name=mongo_patient["name"],
                    image=mongo_patient["image"],
                    is_diagnosed=mongo_patient["is_diagnosed"],
                    has_cancer=mongo_patient["has_cancer"],
                    registration_date=mongo_patient["registration_date"],
                    diagnosis_date=mongo_patient["diagnosis_date"],
                    cancer_images=cancer_images)
Exemple #22
0
    def setUp(self):
        """Create test client, add sample data."""
        db.drop_all()
        db.create_all()

        d1 = Doctor(first_name="John", last_name="Fulcan")
        d2 = Doctor(first_name="Mike", last_name="NightRider")

        db.session.add(d1)
        db.session.add(d2)

        p1 = Patient(first_name="Blub",
                     last_name="Booper",
                     date_of_birth=datetime.date(1999, 1, 19))
        p2 = Patient(first_name="Jak",
                     last_name="Alomaty",
                     date_of_birth=datetime.date(2001, 3, 21))

        db.session.add(p1)
        db.session.add(p2)

        n1 = Nurse(first_name='Marko', last_name="jamie")
        n2 = Nurse(first_name='Jimbo', last_name="Kilayin")

        db.session.add(n1)
        db.session.add(n2)

        db.session.commit()

        d1 = Doctor.query.get(1)
        d2 = Doctor.query.get(2)
        p1 = Patient.query.get(1)
        p2 = Patient.query.get(2)

        self.d1 = d1
        self.d2 = d2
        self.p1 = p1
        self.p2 = p2
        self.n1 = n1
        self.n2 = n2

        self.client = app.test_client()
Exemple #23
0
def register_patient(unregistered_patient: UnregisteredPatient):
    """Register patient and returns saved record."""
    vaccination_delay = timedelta(days=len([letter for letter
                                            in unregistered_patient.name + unregistered_patient.surname
                                            if letter.isalpha()]))
    patient = Patient(name=unregistered_patient.name, surname=unregistered_patient.surname,
                      id=len(app.patients) + 1,
                      vaccination_date=(date.today() + vaccination_delay))
    app.patients.append(patient)
    logger.info(f'Added {patient=}')
    return patient
Exemple #24
0
def load_patient():
    for f in glob.glob(os.path.join(data_dir, 'patient?.csv')):
        df = pd.read_csv(f)
        for ix, row in df.iterrows():
            pnt = Patient(first_name=row['first_name'],
                          last_name=row['last_name'],
                          id=row['id'],
                          email=row['email'],
                          gender=row['gender'],
                          birthdate=parse_date(row['birthdate']))
            session.add(pnt)
        session.commit()
Exemple #25
0
def registration():
    form = Patients()
    if form.validate_on_submit():
        patient = Patient(first_name=form.first_name.data,
                          last_name=form.last_name.data,
                          sex=form.sex.data,
                          age=form.age.data)
        if patient is not None:
            db.session.add(patient)
            db.session.commit()
            flash("Stored patient in the database.")
            return render_template(url_for('registration'))
    return render_template('registration.html', form=form)
Exemple #26
0
 def add_patient(self, ccd_file, pref_email):
     #Because of a chicken-egg problem, we need to write the CCDA to disk then have bluebutton parse it before we can
     #pass it to a model
     with NamedTemporaryFile(delete=False) as xml_file:
         for chunk in ccd_file.chunks():
             xml_file.write(chunk)
     ccda = parse_ccda(xml_file.name)
     new_user = User.objects.create_user(pref_email, pref_email, 'password')
     new_user.first_name = ccda['demographics']['name']['given'][0]
     new_user.last_name = ccda['demographics']['name']['family']
     new_user.save()
     new_patient = Patient(user=new_user, chart=ccd_file)
     new_patient.save()
Exemple #27
0
def create_patient():
    content = request.get_json(silent=True)
    session = DBSession()
    session.expire_on_commit = False
    patient = Patient()
    if content and ("mac_address" in content):
        patient.mac_address = content["mac_address"].upper()
    stmt = session.add(patient)
    print(patient.id)
    session.commit()
    id = patient.id
    print(patient.id)
    session.close()
    return jsonify(patient.id)
Exemple #28
0
def add_patient():
    patient_form = request.form['patient']
    patient_form = json.loads(patient_form)
    patient_model = Patient("", patient_form["name"])
    patient_model.registration_date = datetime.datetime.now()
    patient_model.diagnosis_date = datetime.datetime.min
    patient_model.id = db_api.insert_patient(patient_model)

    if "image" in patient_form:
        patient_model.image = patient_img_manager.upload_profile(
            patient_model, patient_form["image"])
        db_api.update_patient(patient_model)

    return jsonify(PatientEncoder().encode(patient_model))
Exemple #29
0
def patient_signup():

    if request.method == "POST":

        name = request.form['name']
        last_name = request.form['last_name']
        phone = request.form['phone']
        email = request.form['email']
        address = request.form['address']
        meds = request.form['meds']
        risk_assessment = request.form['risk_assessment']
        created_date = request.form['created_date']
        pharmacy = request.form['pharmacy']
        last_filled = request.form['last_filled']
        last_filled_amount = request.form['last_filled_amount']
        dob = request.form["dob"]
        insurance = request.form['insurance']
        group_no = request.form['group_no']
        ss_no = request.form['ss_no']
        Rx_no = request.form['Rx_no']
        chronic_conditions = request.form['chronic_conditions']
        allergies = request.form['allergies']
        cell_phone = request.form['cell_phone']
        gender = request.form['gender']

        new_patient = Patient(name=name,
            last_name=last_name,
            phone=phone,
            email=email,
            address=address,
            meds=meds,
            risk_assessment=risk_assessment,
            created_date=created_date,
            pharmacy=pharmacy,
            last_filled=last_filled,
            last_filled_amount=last_filled_amount,
            dob=dob,
            insurance=insurance,
            group_no=group_no,
            ss_no=ss_no,
            Rx_no=Rx_no,
            chronic_conditions=chronic_conditions,
            allergies=allergies,
            cell_phone=cell_phone,
            gender=gender)

        db.session.add(new_patient)
        db.session.commit()
    return 'SIGNUP VIEW (This is not necessary)'
Exemple #30
0
    def add_patient(self, fname, lname, height, weight, sex):
        #TODO: are duplicate names allowed?
        from models import HealthValue, HealthParameter, Patient, PatientHealth
        from models import session, base, db
        p = Patient(first_name=fname,
                    last_name=lname,
                    height=height,
                    weight=weight,
                    sex=sex)

        try:
            session.add(p)
            session.commit()
            return "Patient {} {} added.".format(p.first_name, p.last_name)
        except Exception as e:
            return str(e)