Ejemplo n.º 1
0
    def get(self, physician_id):

        requests_cache.install_cache(cache_name="APIcache",
                                     backend="sqlite",
                                     expire_after=timedelta(days=2))
        # Calling environment variable for the authorization header
        headers = dict(Authorization="Bearer " +
                       os.environ.get("PHYSICIAN_BEARER"))
        # Setting up some variables to use on the request
        timeout = 4
        url = "https://cryptic-scrubland-98389.herokuapp.com/v2/physicians/"
        if isinstance(physician_id, int):
            try:
                r = requests_retry_session(retries=2).get(url +
                                                          str(physician_id),
                                                          headers=headers,
                                                          timeout=timeout)
            except Exception as e:
                return ("We have a problem.", e.__class__.__name__)

            if r.status_code == 200:

                return r.json(), 200
            elif r.status_code == 408:
                return get_error("Request Timeout", "07")
            elif r.status_code == 503:
                return get_error("physicians service not available", "05")
            elif r.status_code == 404:
                return get_error("physician not found", "02")
        else:
            return "malformed requests", "01"
Ejemplo n.º 2
0
    def get(self, clinic_id):

        requests_cache.install_cache(
            cache_name="APIcache", backend="sqlite", expire_after=timedelta(hours=12)
        )
        # Calling environment variable for the authorization header
        headers = dict(Authorization="Bearer " + os.environ.get("CLINIC_BEARER"))
        # Setting up some variables to use on the request
        timeout = 3
        url = "https://agile-earth-43435.herokuapp.com/v1/clinics/"

        if isinstance(clinic_id, int):
            try:
                r = requests_retry_session(retries=2).get(
                    url + str(clinic_id), headers=headers, timeout=timeout
                )
            except Exception as e:
                return ("We have a problem.", e.__class__.__name__)

            if r.status_code == 200:

                return r.json(), 200
            elif r.status_code == 408:
                return get_error("Request Timeout", "07")
            elif r.status_code == 503:
                return get_error("clinics service not available", "08")
            elif r.status_code == 404:
                return get_error("clinic not found", "09")
        else:
            return get_error("malformed requests", "01")
Ejemplo n.º 3
0
    def get(self, patient_id):

        requests_cache.install_cache(cache_name="APIcache",
                                     backend="sqlite",
                                     expire_after=timedelta(days=3))
        # Calling environment variable for the authorization header
        headers = dict(Authorization="Bearer " +
                       os.environ.get("PATIENT_BEARER"))
        # Setting up some variables to use on the request
        timeout = 3
        url = "https://limitless-shore-81569.herokuapp.com/v3/patients/"
        if isinstance(patient_id, int):
            try:
                r = requests_retry_session(retries=2).get(url +
                                                          str(patient_id),
                                                          headers=headers,
                                                          timeout=timeout)
            except Exception as e:
                return ("We have a problem.", e.__class__.__name__)

            if r.status_code == 200:

                return r.json(), 200
            elif r.status_code == 408:
                return get_error("Request Timeout", "07")
            elif r.status_code == 503:
                return get_error("patients service not available", "06")
            elif r.status_code == 404:
                return "patient not found", "03"
        else:
            return get_error("malformed requests", "01")
Ejemplo n.º 4
0
def get_special_friends():
    """
    Given 2 people, this method provides their information (Name, Age, Address, phone)
    and the list of their friends in common which have brown eyes and are still alive.
    """
    if not request.args.get('person_1') or not request.args.get('person_2'):
        return jsonify(
            get_error(
                "Request params missing", "Bad Request", 400,
                "Missing parameters",
                "Values for person_1 and person_2 are missing in request params"
            )), 400

    try:
        person_one_index = int(request.args.get('person_1'))
        person_two_index = int(request.args.get('person_2'))
    except ValueError:
        return jsonify(get_index_value_error()), 400

    try:
        results = list(
            get_items_from_collection_by_aggregation(
                'people',
                get_aggregation_pipeline_query_special_friends(
                    person_one_index, person_two_index)))

        # Frame response and send - separate function
        response = frame_response_special_friends_search(results)
        return jsonify(response), 200
    except Exception as e:
        return jsonify(get_server_error()), 500
Ejemplo n.º 5
0
def get_company(id):
    """
    This methods gets all the employees of a company
    """
    try:
        company = get_item_from_collection_by_field('companies', 'index', id)
        if not company:
            return jsonify(get_company_not_found_error(id)), 404

        employees = get_employees_of_company(company['index'])
        if not employees:
            return jsonify(
                get_error('No employees found', 'Not Found', 404,
                          'No employees found',
                          'Company {} has no employees'.format(id))), 404

        return jsonify(employees), 200
    except Exception as e:
        return jsonify(get_server_error()), 404
Ejemplo n.º 6
0
def get_company_not_found_error(id):
    return get_error("Company {} not found".format(id), "Not found", 404,
                     "Not Found",
                     "There was no company with that index {}".format(id))
Ejemplo n.º 7
0
def get_person_not_found_error(id):
    return get_error("Person {} not found".format(id), "Not found", 404,
                     "Not Found",
                     "There was no person with that index {}".format(id))
Ejemplo n.º 8
0
    def post(self):
        # Initializing Requests_cache with the expire_after config
        requests_cache.install_cache(cache_name="APIcache",
                                     backend="sqlite",
                                     expire_after=timedelta(hours=12))
        # Calling environment variable for the authorization header
        headers = {
            "Authorization": "Bearer " + os.environ.get("METRICS_BEARER")
        }
        # Setting up some variables to use on the request
        timeout = 6
        urlMetrics = "https://mysterious-island-73235.herokuapp.com/api/metrics"
        # Getting data passed through the post request using request providade by Flask
        requestData = request.get_json(force=True)

        # Checking if the request data is correct else returns "malformed request"
        if (requestData["text"] and requestData["clinic"]
                and requestData["physician"] and requestData["patient"]):
            # Initializing variables
            physician_id = requestData["physician"]["id"]

            physician = False
            resp_physician = None
            try:
                # Check if physician is in the database
                physician = Physician.query.get_or_404(physician_id)
            except Exception as e:
                # If it is, pass, else get it from the api
                if physician:
                    pass
                else:
                    try:
                        resp_physician = requests_retry_session().get(
                            "http://localhost:5000/api/v2/physician/" +
                            str(requestData["physician"]["id"]))

                        resp_physician = resp_physician.json()

                    except:
                        # In case of exception returns error
                        return resp_physician.get_json(force=True)

                    # Create physician object to add to database
                    physician = Physician(
                        id=resp_physician["data"]["id"],
                        fullname=resp_physician["data"]["fullName"],
                        crm=resp_physician["data"]["crm"],
                    )
                    db.session.add(physician)
                    db.session.commit()

            patient_id = requestData["patient"]["id"]
            patient = None
            resp_patient = None
            try:
                # Check if patient is in the database
                patient = Patient.query.get_or_404(patient_id)
            except:
                if patient:
                    # If it is, pass, else get it from the api
                    pass
                else:
                    try:
                        resp_patient = requests_retry_session().get(
                            "http://localhost:5000/api/v2/patient/" +
                            str(requestData["patient"]["id"]))
                        resp_patient = resp_patient.json()
                    except:
                        return resp_patient.get_json(force=True)

                    # Create patient object to add to database
                    patient = Patient(
                        id=resp_patient["data"]["id"],
                        fullname=resp_patient["data"]["fullName"],
                        email=resp_patient["data"]["email"],
                        phone=resp_patient["data"]["phone"],
                        clinic=resp_patient["data"]["clinic"]["id"],
                        active=resp_patient["data"]["active"],
                    )
                    db.session.add(patient)
                    db.session.commit()
            clinic = requestData["clinic"]["id"]

            resp_clinic = None
            try:
                # Check if clinic is in the database
                clinic = Clinic.query.get_or_404(clinic)
            except:
                if clinic:
                    # If it is, pass, else get it from the api
                    pass
                else:
                    try:
                        resp_clinic = requests_retry_session().get(
                            "http://localhost:5000/api/v2/clinic/" +
                            str(requestData["clinic"]["id"]))
                        resp_clinic = resp_clinic.json()
                    except:
                        return resp_clinic.json()
                    # Create clinic object to add to database
                    clinic = Clinic(id=resp_clinic["data"]["id"],
                                    name=resp_clinic["data"]["name"])
                    db.session.add(clinic)
                    db.session.commit()

            # Create generate json to send to POST API Metrics
            jsonForMetrics = generate_json_for_metrics(patient=patient,
                                                       physician=physician,
                                                       clinic=clinic)

            # Create requests Session
            r = requests_retry_session(retries=5)
            try:
                # Try to post to Metrics, returns the json or in case of exception returns an error
                r = r.post(urlMetrics,
                           headers=headers,
                           timeout=timeout,
                           data=jsonForMetrics)
                reqJson = r.json()
            except Exception as e:
                return get_error("metrics service not available", "04")

            if "errorCode" in reqJson:
                # If Metrics API returns an error, execute a rollback.
                db.session.rollback()

                return (get_error(reqJson["userMessage"],
                                  reqJson["errorCode"]), 404)

            else:
                # Create prescription object to add to database
                prescription = Prescription(
                    text=requestData["text"],
                    clinic=requestData["clinic"]["id"],
                    patient=requestData["patient"]["id"],
                    physician=requestData["physician"]["id"],
                )
                db.session.add(prescription)
                try:
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    return get_error(e.__class__.__name__, "10")

                # This is to check if the transaction have been successful
                presc_object = Prescription.query.filter_by(
                    patient=requestData["patient"]["id"],
                    physician=requestData["physician"]["id"],
                    text=requestData["text"],
                ).first()

                # Create dict to be sent as a response
                resp = dict()
                resp["data"] = dict(
                    id=presc_object.id,
                    clinic=dict(id=presc_object.clinic),
                    physician=dict(id=presc_object.physician),
                    patient=dict(id=presc_object.patient),
                    text=presc_object.text,
                )

                current_app.logger.info("POST on /v2/prescriptions/")
                # Flask-Restful sends a JSON back so no need to dump the dict into one
                return resp, 200

        else:
            return get_error("malformed requests", "01"), 200