Skip to content

Commit

Permalink
Rebuild flask api for python project
Browse files Browse the repository at this point in the history
  • Loading branch information
Norukh committed Dec 2, 2023
1 parent 0498c4e commit 6900681
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 14 deletions.
17 changes: 17 additions & 0 deletions lib/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'''
Run from root directory:
flask --app lib/api run
'''
# api.py
from flask import Flask
from sensor_api import sensor_api
from path_api import path_api

app = Flask(__name__)

# Register blueprints
app.register_blueprint(sensor_api, url_prefix='/sensors')
app.register_blueprint(path_api, url_prefix='/path')

if __name__ == '__main__':
app.run(debug=True)
24 changes: 12 additions & 12 deletions lib/path-api.py → lib/path_api.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
'''
Run from root directory:
flask --app lib/path-api run
'''
from flask import Flask
from flask import jsonify
# path_api.py
from flask import Blueprint, jsonify, request, Response
import json
from preprocessing import read_data
from map_service import MapService
from path_finder import PathFinder
from flask import Response

app = Flask(__name__)
data_file = 'data/fill-level.csv'

with open('.env', 'r') as fh:
Expand All @@ -20,15 +14,21 @@
)

n_sensors = 42 # Number of sensors in St. Gallen
no_empty_if_below = 0.4
station_0 = (47.4156038, 9.3325804) # Assumption: Empyting starts and ends at Kehrichtheizkraftwerk St.Gallen
sensor_data = read_data(data_file, use_coordinates=True)
sensor_data = sensor_data.loc[sensor_data.groupby('sensor_id').date.idxmax()] # Get sensor_id only once

map_service = MapService(vars_dict["MAPS_KEY"], sensor_data, n_sensors, station_0, no_empty_if_below)
path_finder = PathFinder(map_service, sensor_data, station_0, n_sensors)
path_api = Blueprint('path_api', __name__)

@app.route("/path", methods=['GET'])

@path_api.route("", methods=['GET'])
def get_path():
selected_date = request.args.get('date')
no_empty_if_below = float(request.args.get('no_empty_if_below')) if request.args.get('no_empty_if_below') is not None else 0.4
glass_type_list = request.args.get('glass_type_list').split(",") if request.args.get('glass_type_list') is not None else None

map_service = MapService(vars_dict["MAPS_KEY"], sensor_data, n_sensors, station_0, no_empty_if_below)
path_finder = PathFinder(map_service, sensor_data, station_0, n_sensors)

_, needed_time, visited_locations = path_finder.find_path()
return jsonify({"visited_locations": visited_locations, "needed_time": needed_time})
13 changes: 11 additions & 2 deletions lib/path_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

class PathFinder:
time_per_working_day = 8 * 60 * 60 # 8 hours in seconds
time_per_emptying = 15 * 60 # 15 minutes in seconds, 5 minutes per container
time_per_emptying = 60 * 60 # 15 minutes in seconds, 5 minutes per container

def __init__(self, map_service: MapService, sensor_data: pd.DataFrame, station_0: tuple, n_sensors: int):
self.sensor_data = sensor_data
Expand All @@ -43,7 +43,16 @@ def find_path(self):
# distances[current_stop_idx, 0] is the time needed from the station to station_0
while (needed_time < (self.time_per_working_day - cost_matrix[current_stop_idx, -1] - self.time_per_emptying)):
visited_stops.append(current_stop_idx)
visited_locations.append(self.sensor_data.iloc[current_stop_idx]["geo_point_2d"].split(", "))

location_information = {}
location_information["lat"] = self.sensor_data.iloc[current_stop_idx]["geo_point_2d"].split(", ")[0]
location_information["lng"] = self.sensor_data.iloc[current_stop_idx]["geo_point_2d"].split(", ")[1]
location_information["level"] = self.sensor_data.iloc[current_stop_idx]["level"]
location_information["sensor_id"] = self.sensor_data.iloc[current_stop_idx]["sensor_id"]
location_information["date"] = self.sensor_data.iloc[current_stop_idx]["date"]
location_information["type"] = self.sensor_data.iloc[current_stop_idx]["type"].split(", ")[0]

visited_locations.append(location_information)

if len(visited_stops) == self.n_sensors+1:
# all stops visited
Expand Down
25 changes: 25 additions & 0 deletions lib/sensor_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# sensor_api.py
from flask import Blueprint, jsonify
from preprocessing import read_data

sensor_api = Blueprint('sensor_api', __name__)

data_file = 'data/fill-level.csv'

sensor_data = read_data(data_file, use_coordinates=True)
sensor_data = sensor_data.loc[sensor_data.groupby('sensor_id').date.idxmax()] # Get sensor_id only once


@sensor_api.route("", methods=['GET'])
def get_sensor_data():
# pandas dataframe to dict
return jsonify(sensor_data.to_dict('records'))


@sensor_api.route("/<sensor_id>", methods=['GET'])
def get_sensor_data_by_id(sensor_id):
sensor = sensors_data.get(sensor_id)
if sensor:
return jsonify(sensor)
else:
return jsonify({'error': 'Sensor not found'}), 404

0 comments on commit 6900681

Please sign in to comment.