· 4 years ago · Aug 29, 2021, 11:08 PM
1from flask.globals import g
2import pandas as pd
3import numpy as np
4import json
5import os
6
7from flask import Flask, Blueprint, jsonify, request
8from collections import defaultdict
9
10api = Blueprint('api',__name__)
11
12def get_month_name(month_number):
13 months = {
14 1: "January",
15 2: "February",
16 3: "March",
17 4: "April",
18 5: "May",
19 6: "June",
20 7: "July",
21 8: "August",
22 9: "September",
23 10: "October",
24 11: "November",
25 12: "December"
26 }
27 return months[month_number]
28
29def calculate(sub_df, index):
30 if index == 'LF':
31 total_seats = sub_df['seats'].sum()
32 total_paid = sub_df['passengers_paid'].sum()
33 load_factor = total_paid / total_seats * 100
34
35 if total_seats == 0:
36 return 0
37 else:
38 return load_factor
39 else:
40 return float(sub_df[index].sum())
41
42def filter_df(request):
43
44 fd = get_flight_data() #fd = flight_data
45
46 input_data = request.get_json()
47 input_filters = input_data['filters']
48
49 from_year = input_data.get('from_year', 2011)
50 to_year = input_data.get('to_year', 2021)
51
52 # Subset flight data to period between start_year and end_year
53 fd = fd[(fd['year'] >= from_year) & (fd['year'] <= to_year)]
54
55 if len(input_filters) >= 1:
56 for key, [value] in input_filters:
57 # Subset dataframe for each filter requested by user
58 fd = fd[fd[key] == value]
59
60 return input_data, fd
61
62def get_flight_data():
63 filename = os.path.join(os.getcwd(), 'datasets', 'flight_log.csv')
64 return pd.read_csv(filename)
65
66@api.route('/heatmap', methods=['POST'])
67def heatmap():
68 input_data, fd = filter_df(request)
69 index = input_data.get('index', 'lf') # If user does not provide an index, we calculate the load factor
70
71 output_data = defaultdict(dict)
72
73 for year_month, sub_df in fd.groupby(["year", "month"]):
74 year, month = year_month # Unpack year and month from tuple index
75 month_name = get_month_name(month)
76 #output_data[year]["year"] = int(year)
77 output_data[year][month_name] = calculate(sub_df, index)
78
79 return jsonify(
80 {
81 'request' : input_data,
82 'response' : output_data.items()
83 }
84 )
85
86@api.route('/line', methods=['POST'])
87def line():
88 input_data, fd = filter_df(request)
89
90
91