-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
292 lines (221 loc) · 8.19 KB
/
main.py
File metadata and controls
292 lines (221 loc) · 8.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import json
from datetime import datetime as dt
from typing import Any, Coroutine, List, Dict, Optional
from fastapi import FastAPI, File, Body
from fastapi.middleware.cors import CORSMiddleware
from pandas import io
from pydantic import BaseModel
import citizens_data
import osmapi
import trucks_data
app = FastAPI()
origins = [
'http://localhost:4200',
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/city/details')
async def get_city_details():
return {'id': 'Gniezno', 'ratio': 0.89, 'mean': {'water_means': []}}
@app.get('/containers')
async def get_all_containers():
# data = citizens_data.create_map_datapoints(citizens_data.generate_df())
data = citizens_data.create_map_datapoints(citizens_data.generate_map_datapoints_df())
with open("./data/location_data.json") as f:
location_data = json.load(f)
for v in location_data:
k = v['name']
if k in data:
long = v['longtitude']
lat = v['latitude']
data[k]['longtitude'] = long
data[k]['latitude'] = lat
data = [{**{'id': key}, **value} for key, value in data.items() if
value is not None and 'longtitude' in value and value['longtitude'] is not None and 'latitude' in value and
value['latitude'] is not None]
data.sort(key=lambda x: x['st_oddanej_do_pobranej'])
return data
@app.get('/containers/default')
async def get_containers_default():
return await get_containers_higher_than_percent(str(70))
@app.get('/containers/{precent}')
async def get_containers_higher_than_percent(percent: str):
percent_i = int(percent)
data = list(filter(
lambda x: x and x != {} and 'st_oddanej_do_pobranej' in x and x['st_oddanej_do_pobranej'] < percent_i * 0.01,
await get_all_containers()))
data.sort(key=lambda x: x['st_oddanej_do_pobranej'])
return data
@app.get('containers/details/{id}')
async def get_all_data_by_id(id: str):
data = await get_all_containers()
data = list(filter(lambda x: x['id'] == id, data))[0]
return data
class Essa(BaseModel):
graph_name: str
id: str
@app.get('/containers/graphs/{id}/{graph_name}')
async def get_graph_by_id_graph_name(id: str, graph_name: str):
if graph_name == 'quotient_timeseries':
data = citizens_data.graph_quotient_timeseries(citizens_data.generate_quotient_timeseries_df(), id)
else:
data = citizens_data.graph_amount_timeseries(citizens_data.generate_quotient_timeseries_df(), id)
return data
@app.post("/upload", status_code=200)
async def create_upload_file(
declaredSewage: bytes = File(None),
realSewage: bytes = File(None),
waterConsumption: bytes = File(None),
companies: bytes = File(None),
meters: bytes = File(None),
sewageReception: bytes = File(None),
residents: bytes = File(None),
containers: bytes = File(None)
):
files = [
(declaredSewage, "declaredSewage"),
(realSewage, 'realSewage'),
(waterConsumption, 'waterConsumption'),
(companies, 'companies'),
(meters, 'meters'),
(sewageReception, 'sewageReception'),
(residents, 'residents'),
(containers, 'containers')]
json_data: Dict[str, Any]
try:
with open('data/modification.json', "r+") as modifictaion_file:
json_data = json.load(modifictaion_file)
except Exception as e:
json_data = {}
current_date = dt.now().strftime("%d-%m-%Y %H:%M")
for file, json_name in files:
if (file):
json_data[json_name] = current_date
with open(f"data/{json_name}.xlsx", "wb+") as buffer:
buffer.write(file)
with open('data/modification.json', 'w+') as modifictaion_file:
json.dump(json_data, modifictaion_file)
return None
@app.get('/last_modified')
async def last_uploaded():
try:
with open(f"data/modification.json") as modifictaion_file:
return json.load(modifictaion_file)
except Exception:
return {}
# ciezaruwy
@app.get('/trucks')
async def get_all_trucks_info():
# trucks_data: Dict[str, Any]
try:
with open("data/trucks_data.json", "r") as f:
truck_data = json.load(f)
except Exception as e:
truck_data = {}
with open("data/trucks_data.json", "w+") as f:
json.dump(truck_data, f)
data2 = io.json.read_json('data/trucks_data.json')
new_data_frame_final = trucks_data.get_truck_data().join(data2) # .to_json()
# return new_data_frame_final
# {"id": str, "comment": str, "checked": bool}
essa = [{**value} for key, value in json.loads(new_data_frame_final.to_json()).items()]
return essa
@app.post('/location')
async def location(loc_str: str, body: Optional[List[str]] = Body(None)):
loc_list: List[osmapi.Location_Type] = []
loc_list_await: List[Coroutine[Any, Any, osmapi.Location_Type]] = []
if body:
for elem in body:
ret = osmapi.getLocation(elem)
if ret:
loc_list_await.append(ret)
else:
loc_list.append((52.535203, 17.6470747, elem))
loc_list.extend([await ret for ret in loc_list_await if ret is not None])
return [{"latitude": x[0], "longtitude": x[1], "name": x[2]} for x in loc_list if x is not None]
class Switch(BaseModel):
id: str
value: str = ""
async def update_location_data(body: Switch, inner_value: str):
data = {}
try:
with open('data/s_c_data.json') as f:
data = json.load(f)
except Exception as e:
with open('data/s_c_data.json', 'w+') as f:
json.dump(data, f)
if body.id not in data:
data[body.id] = {}
data[body.id][inner_value] = body.value
with open('data/s_c_data.json', 'w+') as f:
json.dump(data, f)
async def get_location_data(id: str, inner_value: str):
ret = {'id': id, 'value': None}
try:
with open('data/s_c_data.json') as f:
data = json.load(f)
if id in data:
ret = data[id][inner_value]
except Exception as e:
with open('data/s_c_data.json', 'w+') as f:
json.dump({}, f)
return ret
# typical crud on notatki and switch zalezne od adresu
# {id: adress, value: value}
@app.put('/switch')
async def make_a_switch(body: Switch = Body(...)):
await update_location_data(body, 'switch')
@app.get('/switch/{id}')
async def get_value_switch(id: str):
return await get_location_data(id, 'switch')
@app.put('/comment')
async def make_a_comment_location(body: Switch = Body(...)):
await update_location_data(body, 'comment')
@app.get('/comment/{id}')
async def get_value_comment(id: str):
return await get_location_data(id, 'comment')
# ciezaruwa
async def update_data_truck(body: Switch, inner_value: str):
data = {}
try:
with open('data/trucks_data.json') as f:
data = json.load(f)
except Exception as e:
with open('data/trucks_data.json', 'w+') as f:
json.dump(data, f)
# data_payload = json.loads(body)
if body.id not in data:
data[body.id] = {}
data[body.id][inner_value] = body.value
with open('data/trucks_data.json', 'w+') as f:
json.dump(data, f)
async def get_data_truck(id: str, inner_value: str):
ret = {'id': id, 'value': None}
try:
with open('data/trucks_data.json') as f:
data = json.load(f)
if id in data:
ret = data[id][inner_value]
except Exception as e:
with open('data/trucks_data.json', 'w+') as f:
json.dump({}, f)
return ret
@app.put('/truck/switch')
async def make_a_switch_for_truck(body: Switch = Body(...)):
await update_data_truck(body, 'switch')
return ''
@app.get('/truck/switch/{id}')
async def get_value_switch_for_truck(id: str):
return await get_data_truck(id, 'switch')
@app.put('/truck/comment')
async def make_a_comment_for_truck(body: Switch = Body(...)):
await update_data_truck(body, 'comment')
return ''
@app.get('/truck/comment/{id}')
async def get_value_comment_for_truck(id: str):
return await get_data_truck(id, 'comment')