1
+ from flask import Flask , Response , jsonify
2
+ from dotenv import load_dotenv , find_dotenv
3
+ from cachetools import cached , LRUCache , TTLCache
4
+ from airtable import Airtable
5
+ from collections import Counter
6
+
7
+ import pandas as pd
8
+ import requests
9
+ import os
10
+
11
+ load_dotenv (find_dotenv ())
12
+
13
+ print ("Starting Server" )
14
+
15
+ AIRTABLE_ID = os .getenv ("AIRTABLE_ID" )
16
+ AIRTABLE_KEY = os .getenv ("AIRTABLE_KEY" )
17
+
18
+ app = Flask (__name__ )
19
+
20
+
21
+ def get_airtable_data (table_name : str ):
22
+ """
23
+ Get data from Airtable with a particular AIRTABLE_ID
24
+ stated in .env file in this directory
25
+
26
+ table_name can be ``talks``, ``jobboard``, ``jobseeker``
27
+ """
28
+ request_url = f"https://api.airtable.com/v0/{ AIRTABLE_ID } /{ table_name } ?api_key={ AIRTABLE_KEY } "
29
+ print (request_url )
30
+ airtable_data = requests .get (request_url ).json ()
31
+ return airtable_data
32
+
33
+
34
+ def format_dict_counter (dict_counter ):
35
+
36
+ result = []
37
+ for k , v in sorted (dict_counter .items (), key = lambda item : item [1 ], reverse = True ):
38
+ result .append ({"budget_type" : k , "amount" : v })
39
+
40
+ return result
41
+
42
+
43
+ @app .route ("/" , defaults = {"path" : "" })
44
+ @app .route ("/<path:path>" )
45
+ def catch_all (path ):
46
+
47
+ #survey = get_airtable_data("survey")
48
+ #survey_df = pd.DataFrame([r["fields"] for r in survey["records"]])
49
+
50
+ survey_table = Airtable (AIRTABLE_ID , 'survey' , AIRTABLE_KEY )
51
+ survey = survey_table .get_all ()
52
+
53
+ survey_df = pd .DataFrame ([r ['fields' ] for r in survey ])
54
+ survey_summary_df = survey_df .groupby ("เขต" ).agg (sum ).reset_index ()
55
+
56
+ print (survey_summary_df )
57
+ survey_summary_df ["to_increase" ] = survey_summary_df ["อยากเพิ่มงบ" ].map (
58
+ lambda x : format_dict_counter (dict (Counter (x )))
59
+ )
60
+ survey_summary_df ["to_decrease" ] = survey_summary_df ["อยากลดงบ" ].map (
61
+ lambda x : format_dict_counter (dict (Counter (x )))
62
+ )
63
+ result = (
64
+ survey_summary_df [["เขต" , "to_increase" , "to_decrease" ]]
65
+ .rename (columns = {"เขต" : "district" })
66
+ .to_dict (orient = "records" )
67
+ )
68
+
69
+ # Add more data
70
+ for r in result :
71
+ r ["sum_to_increase" ] = sum ([x ["amount" ] for x in r ["to_increase" ]])
72
+ r ["sum_to_decrease" ] = sum ([x ["amount" ] for x in r ["to_decrease" ]])
73
+
74
+ return jsonify ({"status" : True , "data" : result })
75
+
76
+
77
+ if __name__ == "__main__" :
78
+ app .run (debug = True , port = 5003 )
0 commit comments