def edit_useism(id):
    url = current_app.config["API_URL"] + "/unverified-seism/" + str(id)
    form = f.SeismForm()

    query = makeRequest("GET", url, authenticated_user=True)
    unverified_seism = query.json()

    if not form.is_submitted():

        # If the form is not sent, makes a request
        if query.status_code == 404:
            flash("Seism not found", "warning")
            return redirect(url_for('u_seism.main'))

        form.depth.data = unverified_seism["depth"]
        form.magnitude.data = unverified_seism["magnitude"]

    if form.validate_on_submit():
        seism = {"depth": form.depth.data, "magnitude": form.magnitude.data}
        seism_json = json.dumps(seism)

        query = makeRequest("PUT",
                            url,
                            authenticated_user=True,
                            data=seism_json)
        return redirect(url_for('u_seism.main'))

    return render_template('/derived/unverified-seisms/edit-useism.html',
                           id=id,
                           form=form,
                           unverified_seism=unverified_seism)
def main():
    url = current_app.config["API_URL"] + "/unverified-seisms"
    sensors_url = current_app.config["API_URL"] + "/sensors"

    filters = f.USeismsFilterForm(request.args, meta={'csrf': False})

    query = makeRequest("GET", sensors_url, authenticated_user=True)
    sensors = json.loads(query.text)["sensors"]

    filters.sensor_id.choices = [(int(sensor['id_num']), sensor['name'])
                                 for sensor in sensors]
    filters.sensor_id.choices.insert(0, [0, "-"])

    data = {}

    if 'sensor_id' in request.args:
        data["sensor_id"] = request.args.get('sensor_id', '')

    if "from_datetime" in request.args and request.args["from_datetime"] != "":
        date = datetime.datetime.strptime(
            request.args.get("from_datetime", ""), "%Y-%m-%dT%H:%M")
        data["from_date"] = datetime.datetime.strftime(date,
                                                       "%Y-%m-%d %H:%M:%S")

    if "to_datetime" in request.args and request.args["to_datetime"] != "":
        date = datetime.datetime.strptime(request.args.get("to_datetime", ""),
                                          "%Y-%m-%dT%H:%M")
        data["to_date"] = datetime.datetime.strftime(date, "%Y-%m-%d %H:%M:%S")

    if 'sort_by' in request.args and request.args['sort_by'] != "":
        data["sort_by"] = request.args.get('sort_by', '')

    if 'page_num' in request.args and request.args['page_num'] != "":
        data["page_num"] = request.args.get('page_num', '')

    if 'elem_per_page' in request.args and request.args['elem_per_page'] != "":
        data["elem_per_page"] = request.args.get('elem_per_page', '')

    data = json.dumps(data)
    query = makeRequest("GET", url, authenticated_user=True, data=data)

    if query.status_code == 200:

        unverified_seisms = json.loads(query.text)["unverified_seisms"]

        pagination = {
            "items_num": json.loads(query.text)["items_num"],
            "total_pages": json.loads(query.text)["total_pages"],
            "page_num": json.loads(query.text)["page_num"]
        }

        return render_template('/derived/unverified-seisms/main.html',
                               unverified_seisms=unverified_seisms,
                               filters=filters,
                               pagination=pagination)
    else:
        return redirect(url_for('u_seism.main'))
def verify_useism(id):
    url = current_app.config["API_URL"] + "/unverified-seism/" + str(id)
    query = makeRequest("GET", url, authenticated_user=True)
    if query.status_code == 404:
        flash("Seism not found", "warning")
        return redirect(url_for('u_seism.main'))

    verification = {"verified": True}
    data_json = json.dumps(verification)
    _query = makeRequest("PUT", url, authenticated_user=True, data=data_json)

    return redirect(url_for('u_seism.main'))
Пример #4
0
def main():
    url = current_app.config["API_URL"] + "/sensors"
    filters = f.SensorsFilterForm(request.args, meta={'csrf': False})

    query = makeRequest("GET", url, authenticated_user=True)
    sensors = json.loads(query.text)["sensors"]

    data = {}

    if 'name' in request.args and request.args['name'] != "":
        data["name"] = request.args.get('name', '')

    if 'status' in request.args and request.args['status'] != "":
        data["status"] = request.args.get('status', '')

    if 'active' in request.args and request.args['active'] != "":
        data["active"] = request.args.get('active', '')

    if 'user_email' in request.args and request.args['user_email'] != "":
        data["user_email"] = request.args.get('user_email', '')

    if 'sort_by' in request.args and request.args['sort_by'] != "":
        data["sort_by"] = request.args.get('sort_by', '')

    if 'page_num' in request.args and request.args['page_num'] != "":
        data["page_num"] = request.args.get('page_num', '')

    if 'elem_per_page' in request.args and request.args['elem_per_page'] != "":
        data["elem_per_page"] = request.args.get('elem_per_page', '')

    data = json.dumps(data)
    query = makeRequest("GET", url, authenticated_user=True, data=data)

    if query.status_code == 200:
        sensors = json.loads(query.text)["sensors"]

        pagination = {
            "items_num": json.loads(query.text)["items_num"],
            "total_pages": json.loads(query.text)["total_pages"],
            "page_num": json.loads(query.text)["page_num"]
        }

        return render_template('/derived/sensors/main.html',
                               sensors=sensors,
                               filters=filters,
                               pagination=pagination)

    else:
        return redirect(url_for('sensors.main'))
Пример #5
0
def add_sensor():
    url = current_app.config["API_URL"] + "/sensors"
    form = f.NewSensorForm()
    """
    We make a GET request to achieve the user emails and append them to the user_id.choices of the form
    """
    users_url = current_app.config["API_URL"] + "/users"
    u_data = makeRequest("GET", users_url, authenticated_user=True)
    user_json = json.loads(u_data.text)

    email_list = [(0, "Select one seismologist email")]
    for user in user_json["users"]:
        email_list.append((user["id_num"], user["email"]))
    form.user_id.choices = email_list

    if form.validate_on_submit():
        """
        Once it is validated and submitted, we store the form's parameters data inside the json for the POST request.
        """
        if form.status.data == 0:
            form.status.data = False
        else:
            form.status.data = True

        if form.active.data == 0:
            form.active.data = False
        else:
            form.active.data = True

        u_id = form.user_id.data

        sensor = {
            "name": form.name.data,
            "ip": form.ip.data,
            "port": form.port.data,
            "status": form.status.data,
            "active": form.active.data,
            "user_id": u_id
        }
        sensor_json = json.dumps(sensor)

        u_data = makeRequest("POST",
                             url,
                             authenticated_user=True,
                             data=sensor_json)
        return redirect(url_for('sensors.main'))

    return render_template('/derived/sensors/add-sensor.html', form=form)
def delete_useism(id):
    url = current_app.config["API_URL"] + "/unverified-seism/" + str(id)
    query = makeRequest("DELETE", url, authenticated_user=True)
    if query.status_code == 409:
        flash("Seism not found", "warning")
        return redirect(url_for('u_seism.main'))
    return redirect(url_for('u_seism.main'))
Пример #7
0
def view_sensor(id):
    url = current_app.config["API_URL"] + "/sensor/" + str(id)
    query = makeRequest("GET", url, authenticated_user=True)
    if query.status_code == 404:
        flash("Sensor not found", "warning")
        return redirect(url_for('sensors.main'))
    sensor = query.json()
    return render_template('/derived/sensors/view-sensor.html', sensor=sensor)
Пример #8
0
def delete_sensor(id):
    url = current_app.config["API_URL"] + "/sensor/" + str(id)
    query = makeRequest("DELETE", url, authenticated_user=True)
    if query.status_code == 409:
        flash(query.text.replace('"', ''), "danger")
        return redirect(url_for('sensors.main'))
    else:
        return redirect(url_for('sensors.main'))
def view_vseism(id):
    url = current_app.config["API_URL"] + "/verified-seism/" + str(id)
    query = makeRequest("GET", url)
    if query.status_code == 404:
        flash("Seism not found", "warning")
        return redirect(url_for('v_seism.main'))
    verified_seism = json.loads(query.text)
    return render_template('/derived/verified-seisms/view-vseism.html',
                           verified_seism=verified_seism)
def view_useism(id):
    url = current_app.config["API_URL"] + "/unverified-seism/" + str(id)
    query = makeRequest("GET", url, authenticated_user=True)
    if query.status_code == 404:
        flash("Seism not found", "warning")
        return redirect(url_for('u_seism.main'))
    unverified_seism = query.json()
    return render_template('/derived/unverified-seisms/view-useism.html',
                           unverified_seism=unverified_seism)
Пример #11
0
def check_sensor(id):
    url = current_app.config["API_URL"] + "/sensor/check/" + str(id)
    query = makeRequest("GET", url, authenticated_user=True)
    if query.status_code == 409:
        flash(query.text.replace('"', ''), "danger")
        return redirect(url_for('sensors.main'))
    elif query.status_code == 201:
        flash(query.text.replace('"', ''), "success")
        return redirect(url_for('sensors.main'))
    else:
        flash(query.text.replace('"', ''), "success")
        return redirect(url_for('sensors.main'))
Пример #12
0
def send_emails():
    url = current_app.config["API_URL"] + "/sensors/status"
    query = makeRequest("GET", url, authenticated_user=True)
    if query.status_code == 200:
        flash("Email sent to administrators", "success")
    return redirect(url_for('sensors.main'))
Пример #13
0
def edit_sensor(id):
    url = current_app.config["API_URL"] + "/sensor/" + str(id)
    form = f.NewSensorForm()
    """
    We make a GET request to achieve the user emails and append them to the user_id.choices of the form
    """
    users_url = current_app.config["API_URL"] + "/users"
    u_data = makeRequest("GET", users_url, authenticated_user=True)
    user_json = json.loads(u_data.text)
    email_list = [(0, "Select one seismologist email")]
    for user in user_json["users"]:
        email_list.append((int(user["id_num"]), user["email"]))
    form.user_id.choices = email_list

    if not form.is_submitted():
        """
        If form is not submitted, we store the data.json() from the GET request inside the form's parameters.
        """
        data = makeRequest("GET", url, authenticated_user=True)

        if data.status_code == 404:
            flash("Sensor not found", "warning")
            return redirect(url_for('sensors.main'))

        # Saving the json to a Python dict in order to show it for editing
        sensor = data.json()

        form.name.data = sensor["name"]
        form.ip.data = sensor["ip"]
        form.port.data = sensor["port"]
        if sensor["status"] is False:
            form.status.data = 0
        else:
            form.status.data = 1
        if sensor["active"] is False:
            form.active.data = 0
        else:
            form.active.data = 1

        try:
            if sensor["user_id"] in sensor:
                for id_num, _email in email_list:
                    if id_num == int(sensor["user_id"]):
                        form.user_id.data = int(id_num)
        except KeyError:
            pass

        try:
            user_a = sensor["user"]
            for id_num, _email in email_list:
                if id_num == int(user_a["id_num"]):
                    form.user_id.data = int(id_num)
        except KeyError:
            pass

    if form.validate_on_submit():

        if form.status.data == 0:
            form.status.data = False
        else:
            form.status.data = True
        if form.active.data == 0:
            form.active.data = False
        else:
            form.active.data = True

        u_id = form.user_id.data

        sensor = {
            "name": form.name.data,
            "ip": form.ip.data,
            "port": form.port.data,
            "status": form.status.data,
            "active": form.active.data,
            "user_id": u_id
        }
        sensor_data = json.dumps(sensor)
        u_data = makeRequest("PUT",
                             url,
                             authenticated_user=True,
                             data=sensor_data)
        return redirect(url_for('sensors.main'))

    return render_template('/derived/sensors/edit-sensor.html',
                           id=id,
                           form=form)
def main():
    url = current_app.config["API_URL"] + "/verified-seisms"

    filters = f.VSeismsFilterForm(request.args, meta={'csrf': False})

    query = makeRequest("GET", url)
    verified_seisms = json.loads(query.text)["verified_seisms"]

    data = {}

    file_name = "total_vseisms"

    if 'depth_min' in request.args and request.args['depth_min'] != "":
        data["depth_min"] = request.args.get('depth_min', '')
        file_name = file_name + "-" + str(data["depth_min"])

    if 'depth_max' in request.args and request.args['depth_max'] != "":
        data["depth_max"] = request.args.get('depth_max', '')
        file_name = file_name + "-" + str(data["depth_max"])

    if 'mag_min' in request.args and request.args['mag_min'] != "":
        data["mag_min"] = request.args.get('mag_min', '')
        file_name = file_name + "-" + str(data["mag_min"])

    if 'mag_max' in request.args and request.args['mag_max'] != "":
        data["mag_max"] = request.args.get('mag_max', '')
        file_name = file_name + "-" + str(data["mag_max"])

    if 'sensor_name' in request.args and request.args['sensor_name'] != "":
        data["sensor_name"] = request.args.get('sensor_name', '')
        file_name = file_name + "-" + str(data["sensor_name"])

    if "from_datetime" in request.args and request.args["from_datetime"] != "":
        date = datetime.datetime.strptime(
            request.args.get("from_datetime", ""), "%Y-%m-%dT%H:%M")
        data["from_date"] = datetime.datetime.strftime(date,
                                                       "%Y-%m-%d %H:%M:%S")
        file_name = file_name + "-" + str(
            datetime.datetime.strftime(date, "%Y%m%dT%H%M%S"))

    if "to_datetime" in request.args and request.args["to_datetime"] != "":
        date = datetime.datetime.strptime(request.args.get("to_datetime", ""),
                                          "%Y-%m-%dT%H:%M")
        data["to_date"] = datetime.datetime.strftime(date, "%Y-%m-%d %H:%M:%S")
        file_name = file_name + "-" + str(
            datetime.datetime.strftime(date, "%Y%m%dT%H%M%S"))

    if 'sort_by' in request.args and request.args['sort_by'] != "":
        data["sort_by"] = request.args.get('sort_by', '')
        filters.sort_by.data = data["sort_by"]
        file_name = file_name + "-" + str(data["sort_by"])

    if 'page_num' in request.args:
        data["page_num"] = request.args.get('page_num', '')

    if 'elem_per_page' in request.args and request.args['elem_per_page'] != "":
        data["elem_per_page"] = request.args.get('elem_per_page', '')

    if 'download' in request.args:
        if request.args.get('download', '') == 'Download seisms into CSV':
            # Start parameters
            code = 200
            page_num = 1
            seisms_list = []

            while code == 200:
                data['page_num'] = page_num

                query = makeRequest("GET", url, data=json.dumps(data))
                code = query.status_code

                if query.status_code == 200:
                    v_seisms = json.loads(query.text)["verified_seisms"]

                    for seism in v_seisms:
                        seism_dict = {
                            'datetime': seism["datetime"],
                            'depth': seism["depth"],
                            'magnitude': seism["magnitude"],
                            'latitude': seism["latitude"],
                            'longitude': seism["longitude"],
                            'sensor': seism["sensor"]["name"]
                        }
                        seisms_list.append(seism_dict)
                    page_num += 1

            if seisms_list:
                # Str IO and CSV writer inicialization. Dictionary's keys are parsed as headers
                si = io.StringIO()
                fc = csv.DictWriter(
                    si,
                    fieldnames=seisms_list[0].keys(),
                )

                # CSV writing. First titles, then rows
                fc.writeheader()
                fc.writerows(seisms_list)

                output = make_response(si.getvalue())

                # Headers for file download
                output.headers[
                    "Content-Disposition"] = "attachment; filename=" + file_name + ".csv"
                output.headers["Content-type"] = "text/csv"

                return output

    data = json.dumps(data)
    query = makeRequest("GET", url, data=data)

    if query.status_code == 200:
        verified_seisms = json.loads(query.text)["verified_seisms"]

        pagination = {
            "items_num": json.loads(query.text)["items_num"],
            "total_pages": json.loads(query.text)["total_pages"],
            "page_num": json.loads(query.text)["page_num"]
        }

        return render_template('/derived/verified-seisms/main.html',
                               verified_seisms=verified_seisms,
                               filters=filters,
                               pagination=pagination)

    else:
        return redirect(url_for('v_seism.main'))