Exemplo n.º 1
0
 def follow(self, following):
     from models.record import Record
     # check if relationship is in database
     if self.follow_status(following) == None:
         # check if the followed user is private
         if following.is_private == True:
             return Record(follower=self.id,
                           following=following.id,
                           approved=False).save()
         else:
             return Record(follower=self.id,
                           following=following.id,
                           approved=True).save()
     else:
         return 0
Exemplo n.º 2
0
 def create_record(self, id, doc):
     patient = id
     doctor = doc.id
     header = self.header.data
     body = self.body.data
     record = Record(None, patient, doctor, header, body)
     self._repository.create(record)
Exemplo n.º 3
0
    def post(self, zone_name):

        json_validator = DNSRecordJSONValidator(request)

        if not json_validator.validate():
            return {"message": "validation error", "errors": json_validator.errors}, 422

        try:

            record_dto = request.json
            record = Record(record_dto, zone_name, self.__avaliable_zones)
            added = self.__dns_records_facade.insert_record(record)

            if not added:
                return {"message": "could not insert entry in DNS record", "errors": []}, 422

            return "", 201, {
                'Location': f'{request.path}/{record.name}'
            }

        except InvalidZone as e:
            return {"message": "zone not found", "errors": [str(e)]}, 404

        except Exception:
            return {"message": "internal error"}, 500
Exemplo n.º 4
0
def update(id):
    date = request.form["date"]
    entry = request.form["entry"]
    animal = animal_repository.select(request.form["animal_id"])
    record = Record(date, entry, animal, id)
    record_repository.update(record)
    return redirect(f"/records/{id}")
Exemplo n.º 5
0
def create():
    date = request.form["date"]
    entry = request.form["entry"]
    animal = animal_repository.select(request.form["animal_id"])
    record = Record(date, entry, animal)
    record_repository.save(record)
    return redirect(f"/animals/{request.form['animal_id']}")
Exemplo n.º 6
0
 def monthly_pnl(self):
     from models.record import Record
     from models.account import Account
     '''sample output : a list of object
 [
   { month: 'Jan', np: 200, gp: 300, exp:100 , revenue: 500, cos: 200 },
   { month: 'Feb', np: 133, gp: 233, exp:100 , revenue: 333, cos: 100 },
 ]
 '''
     # only profit/loss accounts ((5+6)-(7+8))
     # get all records according to months
     month_list = []
     months = [
         'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec'
     ]
     for m in range(1, 13):
         result = {}
         result['month'] = months[m - 1]
         result['np'] = 0
         result['revenue'] = 0
         result['exp'] = 0
         for i in range(5, 9):
             records = Record.select().join(Account).where(
                 Account.acc_type == i, Record.date.month == m,
                 Record.assessment == self.id)
             for r in records:
                 result['np'] -= r.amount / 100
                 if r.account.acc_type in [5, 6]:
                     result['revenue'] -= r.amount / 100
                 if r.account.acc_type in [7, 8]:
                     result['exp'] += r.amount / 100
         month_list.append(result)
     return month_list
Exemplo n.º 7
0
def search():
    id = request.args.get("record_id")
    record = Record.get_or_none(Record.id == id)

    if record:
        return jsonify({
            "record_id": record.id,
            "appointment_id": record.appointment_id,
            "report": record.report,
            "prescription": record.prescription,
            "payment_amount": str(record.payment_amount),
            "paid": record.paid,
            "cholestrol_level": str(float(record.cholestrol_level)),
            "sugar_level": str(float(record.sugar_level)),
            "systolic_blood_pressure": str(float(record.systolic_blood_pressure)),
            "diastolic_blood_pressure": str(float(record.diastolic_blood_pressure)),
            "doctor_name": record.appointment.doctor.name,
            "doctor_ic": record.appointment.doctor.ic_number,
            "patient_name": record.appointment.patient.name,
            "patient_ic": record.appointment.patient.ic_number,
            "record_photo": record.photo
        })
    else:
        return jsonify({
            "message": "There is no such record.",
            "status": "fail"
        })
Exemplo n.º 8
0
 def deleteById(self, record_id):
    record = Record.objects(id_number= record_id)
    if record is not None:
        record.delete()
        return True
    else:
         return False
Exemplo n.º 9
0
    def record(self):
        from models.record import Record
        from models.patient_photo import Patient_Photo
        r = Record.get_or_none(Record.appointment_id == self.id)
        if r:
            result = {
                "record_id": r.id,
                "appointment_id": r.appointment_id,
                "report": r.report,
                "prescription": r.prescription,
                "payment_amount": str(r.payment_amount),
                "paid": r.paid,
                "cholestrol_level": str(float(r.cholestrol_level)),
                "sugar_level": str(float(r.sugar_level)),
                "systolic_blood_pressure":
                str(float(r.systolic_blood_pressure)),
                "diastolic_blood_pressure":
                str(float(r.diastolic_blood_pressure)),
                "doctor_name": r.appointment.doctor.name,
                "doctor_ic": r.appointment.doctor.ic_number,
                "patient_name": r.appointment.patient.name,
                "patient_ic": r.appointment.patient.ic_number,
                "record_photo": r.photo
            }
        else:
            result = None

        return result
def main():
    """Command line entrypoint for this utility script."""
    parser = argparse.ArgumentParser(
        description=
        'Generate example test inputs in <project_root>/sample_inputs/')
    parser.add_argument(
        '-n',
        type=int,
        default=100,
        help=
        f'Number of records to generate in test files, {MIN_SAMPLE_LENGTH}-{MAX_SAMPLE_LENGTH}'
    )
    args = parser.parse_args()

    if args.n < MIN_SAMPLE_LENGTH or args.n > MAX_SAMPLE_LENGTH:
        parser.print_help()
        return

    fake = Faker()
    records = [
        Record(fake.last_name(), fake.first_name(), fake.email(),
               fake.color_name(),
               fake.date_of_birth().strftime("%m/%d/%Y"))
        for _ in range(args.n)
    ]

    for file_type in RecordFileType:
        write_example_input(records, file_type)
Exemplo n.º 11
0
 def users(self):
     from models.record import Record
     from models.user import User
     reports = Record.find(product_uuid=self.uuid)
     res = []
     if reports:
         user_uuid = set(r.client_uuid for r in reports)
         res = [User.get_uuid(uuid) for uuid in user_uuid]
     return res
Exemplo n.º 12
0
def select_all():
    records = []
    sql = "SELECT * FROM records"
    results = run_sql(sql)
    for row in results:
        animal = animal_repository.select(row["animal_id"])
        record = Record(row["date"], row["entry"], animal, row["id"])
        records.append(record)
    return records
Exemplo n.º 13
0
def select(id):
    record = None
    sql = "SELECT * FROM records WHERE id = %s"
    values = [id]
    row = run_sql(sql, values)[0]
    if row is not None:
        animal = animal_repository.select(row["animal_id"])
        record = Record(row["date"], row["entry"], animal, row["id"])
    return record
Exemplo n.º 14
0
def edit():
    online_user = get_jwt_identity()
    user = User.get_or_none(User.id == online_user['id'])

    if user:
        update_record = Record.get_or_none(Record.id == request.json.get("record_id"))
        if update_record:
            if (user == update_record.appointment.doctor):     
                update_record.report = request.json.get("report")
                update_record.prescription = request.json.get("prescription")
                if update_record.save():
                    response = {
                        "message": "Updated record successfully",
                        "status": "success",
                        "report": update_record.report,
                        "prescription": update_record.prescription
                    }
                else:
                    response = {
                        "message": "Record not saved",
                        "status": "fail"
                    }
            elif ("admin" in user.role):
                update_record.payment_amount = request.json.get("payment_amount")
                if update_record.save():
                    response = {
                        "message": "Updated record successfully",
                        "status": "success",
                        "updated_payment_amount": update_record.payment_amount
                    }
                else:
                    response = {
                        "message": "Record not saved",
                        "status": "fail"
                    }
            else:
                response = {
                    "message": "401 Unauthorized (Only the doctor or admin is allowed.)",
                    "status": "fail"
                }
        else:
            response = {
                "message": "Record not found",
                "status": "fail"
            }
    else:
        response = {
            "message": "User does not exist",
            "status": "fail"
        }
    return jsonify(response)
Exemplo n.º 15
0
def record(id):
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_token = auth_header.split(" ")[1]
    else:
        responseObject = {
            'status': 'failed',
            'message': 'No authorization header found.'
        }
        return make_response(jsonify(responseObject)), 401

    user_id = User.decode_auth_token(auth_token)
    user = User.get(User.id == user_id)
    from models.record import Record
    if (user_id == id) and user:
        post_data = request.get_json()
        record = Record(weight=post_data['weight'],
                        height=post_data['height'],
                        bmi=post_data['bmi'],
                        user=user.id)
        if record.save():
            responseObject = {
                'status': 'success',
                'message': 'Record successfully saved.'
            }
            return make_response(jsonify(responseObject)), 201
        else:
            responseObject = {
                'status': 'failed',
                'message': 'Something happened,try again later.'
            }
            return make_response(jsonify(responseObject)), 400
    else:
        responseObject = {
            'status': 'failed',
            'message': 'Authentication failed'
        }
        return make_response(jsonify(responseObject)), 401
Exemplo n.º 16
0
 def get_current_record(self):
     record_id = self.get_secure_cookie("record_id")
     if not record_id:
         return None
     else:
         try:
             record = Record.objects(pk=ObjectId(record_id)).get()
         except DoesNotExist:
             self.clear_cookie("record_id")
             # self.redirect(self.get_argument("next", "/"))
             self.clear_all_cookies()
             self.render("login.html", error="请重新登录")
             raise tornado.web.Finish
         else:
             return record
Exemplo n.º 17
0
async def add_record(request: CreateRecordRequestModel) -> List[str]:
    """Handle adding a Record to Record storage."""
    if request.fmt not in ['csv', 'psv', 'ssv']:
        raise HTTPException(status_code=422,
                            detail="unsupported record format")

    try:
        delimiter = RecordFileType.delimiters[RecordFileType(request.fmt)]
        web_records.append([
            Record(*row)
            for row in csv.reader([request.record], delimiter=delimiter)
        ][0])
    except TypeError:
        raise HTTPException(status_code=422,
                            detail="record syntax invalid, failed to parse")
    return web_records[-1].as_list()
Exemplo n.º 18
0
 def total(self):
     from models.record import Record
     from models.account import Account
     '''
 sample result = { 
   1: {'total': 2000.0, 
     'list': [
       {'account_id': 15, 'account_name': 'Equipment', 'account_type': 1, 'account_number': '2000-100', 'amount': 2000.0}
     ]}, 
   2: {'total': 1600.0, 
     'list': [
       {'account_id': 8, 'account_name': 'Cash in Hand', 'account_type': 2, 'account_number': '3200-000', 'amount': -1400.0}, 
       {'account_id': 14, 'account_name': 'Cash At Bank', 'account_type': 2, 'account_number': '3100-000', 'amount': -1950.0}
     ]}, 
   ...
 }
 '''
     result = {}
     for i in range(9):
         records = Record.select().join(Account).where(
             Account.acc_type == i, Record.assessment == self.id)
         check_list = []
         for r in records:
             if not result.get(r.account.acc_type):
                 result[r.account.acc_type] = {}
                 result[r.account.acc_type]['total'] = 0
                 result[r.account.acc_type]['list'] = []
             result[r.account.acc_type]['total'] += (r.amount / 100)
             if not r.account.id in check_list:
                 check_list.append(r.account.id)
                 result[r.account.acc_type]['list'].append({
                     'account_id':
                     r.account.id,
                     'account_name':
                     r.account.name,
                     'account_type':
                     r.account.acc_type,
                     'account_number':
                     r.account.account_number,
                     'amount': (r.amount / 100)
                 })
             else:
                 for acc in result[r.account.acc_type]['list']:
                     if r.account.id == acc['account_id']:
                         acc['amount'] = ((acc['amount']) +
                                          (r.amount / 100))
     return result
Exemplo n.º 19
0
def create():
    amount = request.json.get("amount_paid")
    nonce_from_the_client = request.json.get("payment_method_nonce")
    result = transact({
        "amount": amount,
        "payment_method_nonce": nonce_from_the_client,
        "options": {
            "submit_for_settlement": True
        }
    })

    if result.is_success or result.transaction:
        record = Record.get_or_none(Record.id == request.json.get("record_id"))
        record.paid = True
        if record.save():
            response = {"message": "payment successful", "status": "success"}
    else:
        for x in result.errors.deep_errors:
            flash('Error: %s: %s' % (x.code, x.message))
    return jsonify(response)
Exemplo n.º 20
0
 def record(self):
     from models.record import Record
     from models.appointment import Appointment
     from models.patient_photo import Patient_Photo
     record = Record.select().join(Appointment).where((
         Appointment.doctor == self) | (Appointment.patient == self))
     record_list = []
     for r in record:
         record_list.append({
             "record_id":
             r.id,
             "appointment_id":
             r.appointment_id,
             "report":
             r.report,
             "prescription":
             r.prescription,
             "payment_amount":
             str(r.payment_amount),
             "paid":
             r.paid,
             "cholestrol_level":
             str(float(r.cholestrol_level)),
             "sugar_level":
             str(float(r.sugar_level)),
             "systolic_blood_pressure":
             str(float(r.systolic_blood_pressure)),
             "diastolic_blood_pressure":
             str(float(r.diastolic_blood_pressure)),
             "doctor_name":
             r.appointment.doctor.name,
             "doctor_ic":
             r.appointment.doctor.ic_number,
             "patient_name":
             r.appointment.patient.name,
             "patient_ic":
             r.appointment.patient.ic_number,
             "record_photo":
             r.photo
         })
     return record_list
Exemplo n.º 21
0
    def delete(self, zone_name, record_name):

        try:

            record = Record({"recordName": record_name}, zone_name,
                            self.__avaliable_zones)
            removed = self.__dns_records_facade.delete_record(record)

            if not removed:
                return {
                    "message": "could not remove entry in DNS record",
                    "errors": []
                }, 422

            return None, 204

        except InvalidZone as e:
            return {"message": "zone not found", "errors": [str(e)]}, 404

        except Exception as e:
            print(str(e))
            return {"message": "internal error"}, 500
Exemplo n.º 22
0
def read_records(files: List[str]) -> List[Record]:
    """Given a list of files, combines them and maps them to Record entries."""
    records = []
    for file in files:
        try:
            *_, extension = file.rpartition(".")
            fmt = RecordFileType(extension)
        except ValueError:
            logger.warning(
                f'{file} is an unsupported file format, it will be skipped')
            continue

        try:
            with open(file, 'r', newline='') as in_stream:
                records += [
                    Record(*row) for row in csv.reader(
                        in_stream, delimiter=RecordFileType.delimiters[fmt])
                ]
        except (TypeError, UnicodeDecodeError, ParserError):
            logger.warning(f'{file} could not be parsed, it will be skipped')
            continue

    return records
Exemplo n.º 23
0
def get_record():
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_token = auth_header.split(" ")[1]
        user_id = User.decode_auth_token(auth_token)
        user = User.get(User.id == user_id)
        from models.record import Record
        records = Record.select().where(Record.user == user.id).order_by(
            Record.id.asc())
        chart = []
        chartBmi = []
        result = []
        for record in records:
            chart.append(
                [str(record.created_at.strftime('%d-%m-%Y')), record.weight])
            chartBmi.append(
                [str(record.created_at.strftime('%d-%m-%Y')), record.bmi])
            result.append({
                'date': record.created_at.strftime('%d-%m-%Y'),
                'weight': record.weight,
                'height': record.height,
                'bmi': record.bmi,
            })
        responseObject = {
            'age': user.age,
            'sex': user.sex,
            'records': result,
            'chart': chart,
            'chartBmi': chartBmi
        }
        return make_response(jsonify(responseObject)), 200
    else:
        responseObject = {
            'status': 'failed',
            'message': 'No authorization header found.'
        }
        return make_response(jsonify(responseObject)), 401
Exemplo n.º 24
0
    def put(self, zone_name, record_name):

        request.json['recordName'] = record_name

        json_validator = DNSRecordJSONValidator(request)

        if not json_validator.validate():
            return {
                "message": "validation error",
                "errors": json_validator.errors
            }, 422

        record_dto = request.json
        record = Record(record_dto, zone_name, self.__avaliable_zones)

        try:

            updated = self.__dns_records_facade.update_record(record)

            if not updated:
                return {
                    "message": "could not update entry in DNS record",
                    "errors": []
                }, 422

            return None, 204

        except InvalidZone as e:
            return {"message": "zone not found", "errors": [str(e)]}, 404

        except RecordNotExists:
            return {"message": "record not exists", "errors": []}, 404

        except Exception as e:
            print(str(e))
            return {"message": "internal error"}, 500
Exemplo n.º 25
0
vet_repository.delete_all()
owner_repository.delete_all()

vet_1 = Vet("Sandra", "Jones")
vet_2 = Vet("Sarah", "Johnson")
vet_3 = Vet("Steve", "Slater")
vet_repository.save(vet_1)
vet_repository.save(vet_2)
vet_repository.save(vet_3)

owner_1 = Owner("Jam", "Jimson", "07162626243", "*****@*****.**")
owner_2 = Owner("Jim", "Jamson", "07162626243", "*****@*****.**")
owner_repository.save(owner_1)
owner_repository.save(owner_2)

pet_1 = Animal("Floof", "01-02-1987", "cat", owner_1, vet_1, "05-08-2020")
pet_2 = Animal("Fluff", "03-04-1958", "dog", owner_2, vet_1, "05-08-2020")
pet_3 = Animal("Puff", "03-04-1958", "dog", owner_2, vet_3, "05-08-2020")
animal_repository.save(pet_1)
animal_repository.save(pet_2)
animal_repository.save(pet_3)

record_1 = Record("06-08-2020", "Cat is ill", pet_1)
record_2 = Record("07-08-2020", "Cat is still ill", pet_1)
record_3 = Record("06-08-2020", "Now dog is sick", pet_2)
record_repository.save(record_1)
record_repository.save(record_2)
record_repository.save(record_3)

pdb.set_trace()
Exemplo n.º 26
0
    def get(self):
        """
        生成背诵列表
        使用Cookie来记录用户的Record
        :return:
        """
        user = self.get_current_user_mongo()

        # 获取上次未完成的背诵
        record = self.get_current_record()
        if record:
            # self.write_response(record.format_response())
            next_word = record.next_word
            self.set_secure_cookie("next_word", next_word)
            self.render("recite.html", record=record.format_response(), next_word=next_word)
            return

        # 已背的单词们
        # Pipeline
        pipeline = [
            # Stage 1
            {
                "$match": {
                    "user": user.pk,
                }
            },

            # Stage
            {
                "$unwind": "$words"
            },

            # Stage
            {
                "$match": {
                    "words.status": WORD_FINISHED
                }
            },

            # Stage
            {
                "$group": {
                    "_id": "$user",
                    "words_recited": {"$addToSet": "$words.word"}
                }
            },

            # Stage
            {
                "$project": {
                    "_id": 0,
                    "words_recited": 1
                }

            }
        ]
        logging.info(user.pk)
        recited_words = Record.objects(user=user, words__status=WORD_FINISHED).aggregate(*pipeline)
        # 如果有值, 会返回只拥有一个元素的列表
        recited_words = list(recited_words)

        query = [Q(scope__in=[user.scope])]
        if recited_words:
            query.append(Q(word__nin=recited_words[0]['words_recited']))

        query = reduce(lambda x, y: x & y, query)
        # 获取新的待背诵单词
        wait_words = Word.objects(query).limit(user.quota)
        # 记录新的背诵记录
        new_record = Record(
            user=user, words=[{"word": word.word, "status": WORD_UNDONE} for word in wait_words]
        ).save()
        self.set_secure_cookie("record_id", str(new_record.id))
        next_word = new_record.words[0]['word']
        # self.set_secure_cookie("next_word", next_word)
        self.render("recite.html", record=new_record.format_response(), next_word=next_word)
        return
Exemplo n.º 27
0
    def get(self):
        """
        生成背诵列表
        使用Cookie来记录用户的Record
        :return:
        """
        user = self.get_current_user_mongo()

        # 获取上次未完成的背诵
        record = self.get_current_record()
        if record:
            # self.write_response(record.format_response())
            next_word = record.next_word
            self.set_secure_cookie("next_word", next_word)
            self.render("recite.html",
                        record=record.format_response(),
                        next_word=next_word)
            return

        # 已背的单词们
        # Pipeline
        pipeline = [
            # Stage 1
            {
                "$match": {
                    "user": user.pk,
                }
            },

            # Stage
            {
                "$unwind": "$words"
            },

            # Stage
            {
                "$match": {
                    "words.status": WORD_FINISHED
                }
            },

            # Stage
            {
                "$group": {
                    "_id": "$user",
                    "words_recited": {
                        "$addToSet": "$words.word"
                    }
                }
            },

            # Stage
            {
                "$project": {
                    "_id": 0,
                    "words_recited": 1
                }
            }
        ]
        logging.info(user.pk)
        recited_words = Record.objects(
            user=user, words__status=WORD_FINISHED).aggregate(*pipeline)
        # 如果有值, 会返回只拥有一个元素的列表
        recited_words = list(recited_words)

        query = [Q(scope__in=[user.scope])]
        if recited_words:
            query.append(Q(word__nin=recited_words[0]['words_recited']))

        query = reduce(lambda x, y: x & y, query)
        # 获取新的待背诵单词
        wait_words = Word.objects(query).limit(user.quota)
        # 记录新的背诵记录
        new_record = Record(user=user,
                            words=[{
                                "word": word.word,
                                "status": WORD_UNDONE
                            } for word in wait_words]).save()
        self.set_secure_cookie("record_id", str(new_record.id))
        next_word = new_record.words[0]['word']
        # self.set_secure_cookie("next_word", next_word)
        self.render("recite.html",
                    record=new_record.format_response(),
                    next_word=next_word)
        return
Exemplo n.º 28
0
 def __check_zone(cls, record: Record):
     if not record.is_valid_zone():
         raise InvalidZone("'zone' not enabled")
Exemplo n.º 29
0
            except NoResultFound, e:
                tracker = Tracker(last_url="https://en.wikipedia.org/wiki/Main_Page")
                self.session.add(tracker)
                self.session.commit()
                url = "https://en.wikipedia.org/wiki/Main_Page"
        else:
            tracker = self.session.query(Tracker).one()
            self.session.query(Tracker).filter(Tracker.id == tracker.id).update({'last_url': url})
            self.session.commit()

        response = requests.head(url)
        if int(response.headers["content-length"]) <= 2097152:
            data = requests.get(url)
            if self.session.query(Record).filter(Record.url == url).count() == 0:
                try:
                    record = Record(url=url, text=data.content)
                    self.session.add(record)
                    self.session.commit()
                except Exception as e:
                    print(Terminal().bold_green_on_bright_green("Error " + url))
                    sleep(5)
                    self.open_conn()
                    return False
            for data in re.findall(
                    r'(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?',
                    data.content):
                print(data)
                url = (data[0] + "://" + data[1] + data[2])
                print(Terminal().bold_red_on_bright_green("Scanning......." + url))
                try:
                    if self.session.query(Record).filter(Record.url == url).count() == 0:
Exemplo n.º 30
0
 def readById(self, record_id):
     record = Record.objects(id_number= record_id)
     return record
Exemplo n.º 31
0
def create():
    appointment_id = request.form.get("appointment_id")
    a = Appointment.get_or_none(Appointment.id == appointment_id)
    if a.record:
        return jsonify({
            "message": "This appointment already has an existing record.",
            "status": "fail"
        })
    else:
        pass
    
    cholestrol_level = request.form.get("cholestrol_level")
    sugar_level = request.form.get("sugar_level")
    systolic_blood_pressure = request.form.get("systolic_blood_pressure")
    diastolic_blood_pressure = request.form.get("diastolic_blood_pressure")

    online_user = get_jwt_identity()
    user = User.get_or_none(User.id == online_user['id'])

    if (user) and ("patient" in user.role): #need to be updated if allow guardian to create record
        patient_record = Record(cholestrol_level=cholestrol_level, sugar_level=sugar_level, systolic_blood_pressure=systolic_blood_pressure, diastolic_blood_pressure=diastolic_blood_pressure, appointment_id=appointment_id)
        if patient_record.save():
            response = {
                "message": f"Successfully created record.",
                "status": "success",
                "cholestrol level" : patient_record.cholestrol_level,
                "sugar level" : patient_record.sugar_level,
                "systolic_blood_pressure" : patient_record.systolic_blood_pressure,
                "diastolic_blood_pressure" : patient_record.diastolic_blood_pressure,
                "appointment_id": patient_record.appointment_id
            }
        else:
            return jsonify({
                "message": "Add record failed, please try again",
                "status": "fail"
            })
            # Image Upload Start
        images = []
        for i in range(int(request.form.get('image_count'))):
            image = request.files['image_files' + str(i)]
            caption = request.form.get('caption' + str(i))

            if 'image' not in image.mimetype:
                patient_record.delete_instance()
                return jsonify({
                    "message": "One or more of the uploaded files is not an image. Please try again",
                    "status": "fail"
                })
            else:
                file_extension = image.mimetype
                file_extension = file_extension.replace('image/', '.')
                image.filename = str(datetime.now()) + file_extension
                image.filename = secure_filename(image.filename)
                image_url = upload_file_to_s3(image, user.ic_number)
                upload_image = Patient_Photo(record_id=patient_record.id, image_url=image_url, caption=caption)

                if upload_image.save():
                    images.append({
                        "image_url": upload_image.full_image_url,
                        "caption": caption
                    })
                else:
                    patient_record.delete_instance()
                    return jsonify({
                        "message": "Image upload failed, please try again",
                        "status": "fail"
                    })
        response["images"] = images
    else:
        response = {
            "message": "User not found/ Only patient is allowed to create record.",
            "status": "fail"
        }
    return jsonify(response)