-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
877 lines (728 loc) · 28.2 KB
/
app.py
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
from flask import Flask, redirect, url_for, Response,render_template, request, redirect, session, flash, Blueprint
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from passlib.hash import sha256_crypt
from datetime import datetime
from datetime import timedelta
from flask_login import current_user
from googleapiclient.discovery import build
from forms import CarForm, UserForm
from httplib2 import Http
from oauth2client import file, client, tools
from flask_socketio import SocketIO, emit, send
from pymysql import NULL
from flask_googlemaps import GoogleMaps, Map
from pushbullet import Pushbullet
import speech_recognition as sr
import subprocess
#set up the google calendar
SCOPES = "https://www.googleapis.com/auth/calendar"
store = file.Storage("token.json")
creds = store.get()
if(not creds or creds.invalid):
flow = client.flow_from_clientsecrets("credentials.json", SCOPES)
creds = tools.run_flow(flow, store)
service = build("calendar", "v3", http=creds.authorize(Http()))
#set up flask and sqlachemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = ''
socketio = SocketIO(app)
# set key as config
app.config['GOOGLEMAPS_KEY'] = ""
# Initialize the extension
GoogleMaps(app)
pb = Pushbullet()
#Pages
@app.route("/", methods = ["POST", "GET"])
def login():
"""
check the user typing information
seacher the username and passport from User table
also need verify the password
if exit
:return to the login page
"""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
username_found = User.query.filter_by(username=username).first()
#result = User.query.filter_by(username=username).first()
##verify hash password
if username_found:
password_found = sha256_crypt.verify(password, username_found.password)
if password_found:
username_session = username_found.username
session["username"] = username_session
if username_found.userType == "admin":
return render_template("adminBase.html",username = session["username"])
elif username_found.userType == "manager":
return render_template("managerBase.html",username = session["username"])
elif username_found.userType == "engineer":
return render_template("engineerBase.html",username = session["username"])
else:
return redirect(url_for("current"))
else:
flash("password incorrect")
return render_template("login.html")
else:
flash("username not found")
return render_template("login.html")
else:
return render_template("login.html")
@app.route("/register", methods = ["POST", "GET"])
def register():
"""
define a function hanlder the register html page in the MP pi
implement the register function
if user typing the correct information
register page pass the information to cloud database and save the information into database
User table add a new User in the database
:return a registration succesful message than return to the login html page
if not
:return a fail registration message and return to the register page
"""
if request.method == "POST":
username = request.form.get('username')
#hash password
password = sha256_crypt.hash(request.form.get('password'))
firstname = request.form.get('firstname')
lastname = request.form.get('lastname')
email = request.form.get('EmailAddress')
userType = request.form.get('userType')
if username == "" or password == "" or firstname == "" or lastname == "" or email == "" or userType == "":
flash("You must fill in everything!","error")
return render_template("/register.html")
elif User.query.filter_by(username=username).first():
flash("User already exit! Please use other name! ")
return render_template("/register.html")
else:
user = User(username=username, password=password, firstname=firstname, lastname=lastname, email=email, userType = userType)
db.session.add(user)
db.session.commit()
flash("Your registration is successful!!","info")
return redirect(url_for("login"))
else:
return render_template("/register.html")
@app.route("/logout")
def logout():
"""
define a function to handler the logout button
if user click logout button
then user logout the system
:return to the home login page
"""
flash("You have been logged out", "info")
session.pop("username", None)
return redirect(url_for("login"))
@app.route("/current")
def current():
"""
define a function to handler the current button
do the research on the database
select all the booked car detail by username
:return all the booked car detail append this page
"""
if "username" in session:
usrname = session["username"]
booking_found = Booking.query.filter_by(username = usrname).all()
booking_current=[]
for booking in booking_found:
if booking.status == "Processing":
booking_current.append(booking)
return render_template("current.html", username = session["username"], currents = booking_current)
else:
flash("You must login first!","error")
return redirect(url_for("login"))
@app.route("/cancel/<int:id>")
def cancel(id):
"""
create a method to handler the cancel button
list the booked car for the user
cancle the current booked and also select that car by car_id
and cancel action system delect the booked car detail on cloud database
at the same time, system hanlder the google calendar API and delete the event from google calendar
event select by eventID that saved before
"""
booking_to_cancel = Booking.query.get_or_404(id)
try:
booking_to_cancel.status = "Cancelled"
car_found = Car.query.filter_by(car_id=booking_to_cancel.car_id).first()
car_found.available = True
db.session.commit()
eventID = booking_to_cancel.event_id
service.events().delete(calendarId='primary', eventId=eventID).execute()
return redirect(url_for("current"))
except:
flash("There is a problem to cancel this booking!","error")
return redirect(url_for("current"))
@app.route("/history")
def history():
"""
create a method handler the history
select booked car detail by username
list all the booked car detail to user
"""
if "username" in session:
usrname = session["username"]
booking_found = Booking.query.filter_by(username = usrname).all()
return render_template("history.html", username = session["username"], hists = booking_found)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/adminHistory")
def adminHistory():
"""
create a method handler the history
select booked car detail by username
list all the booked car detail to user
"""
if "username" in session:
usrname = session["username"]
# if usrname.userType == "admin":
booking_found = Booking.query.all()
return render_template("adminHistory.html", username = session["username"], hists = booking_found)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/add", methods=['GET', 'POST'])
def add():
if "username" in session:
usrname = session["username"]
form = CarForm(request.form)
if request.method == 'POST' and form.validate():
car = Car()
save_changes(car, form, new=True)
flash('Car created successfully!')
return render_template('adminBase.html', form = form)
return render_template('addCar.html', form = form)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/addUser", methods=['GET', 'POST'])
def addUser():
if "username" in session:
usrname = session["username"]
form = UserForm(request.form)
if request.method == 'POST' and form.validate():
user = User()
save_changesUser(user, form, new=True)
flash('User created successfully!')
return render_template('adminBase.html', form = form)
return render_template('addUser.html', form = form)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
def save_changesUser(user, form, new=False):
"""
Save the changes to the database
"""
user.username = form.username.data
user.password = sha256_crypt.hash(form.password.data)
user.firstname = form.firstname.data
user.lastname = form.lastname.data
user.email = form.email.data
user.userType = form.userType.data
if new:
db.session.add(user)
db.session.commit()
def save_changes(car, form, new=False):
"""
Save the changes to the database
"""
car.car_id = form.car_id.data
car.brand = form.brand.data
car.model = form.model.data
car.locationX = form.locationX.data
car.locationY = form.locationY.data
print(form.car_id.data)
if new:
db.session.add(car)
db.session.commit()
@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
"""
edit a Car in the database
"""
if "username" in session:
usrname = session["username"]
car = Car.query.filter(Car.car_id==id).first()
if car:
form = CarForm(formdata=request.form, obj=car)
if request.method == 'POST' and form.validate():
save_changes(car, form)
flash('Car updated successfully!')
return render_template('adminBase.html', form = form)
return render_template('edit_car.html', form=form)
else:
return 'Error loading #{id}'.format(id=id)
@app.route('/editUser/<string:username>', methods=['GET', 'POST'])
def editUser(username):
"""
edit a User in the database
"""
if "username" in session:
usrname = session["username"]
user = User.query.filter(User.username == username).first()
if user:
form = UserForm(formdata=request.form, obj=user)
if request.method == 'POST' and form.validate():
save_changesUser(user, form)
flash('User updated successfully!')
return render_template('adminBase.html', form = form)
return render_template('edit_user.html', form=form)
else:
return 'Error loading #{username}'.format(username = username)
@app.route("/cars")
def cars():
"""
define a method list all the available car on web page
select all the car that avaiable
return a list of available cars
"""
if "username" in session:
usrname = session["username"]
cars_found = Car.query.filter_by(available=True).all()
return render_template("cars.html", username = session["username"], cars = cars_found)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/all_car")
def all_cars():
"""
define a method list all the cars on web page
return a list of cars
"""
if "username" in session:
usrname = session["username"]
cars_found = Car.query.all()
return render_template("all_car.html", username = session["username"], cars = cars_found)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/allReports")
def getAllReports():
if "username" in session:
usrname = session["username"]
cars_found = Car.query.filter(Car.issues.isnot(None)).all()
return render_template("allReports.html", username = session["username"], hists = cars_found)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/search", methods=['GET', 'POST'])
def search():
"""
implement the search function
that user could search by car_id, brand, or model
system select the car table
:return a list of car that detail match the user type in
"""
if "username" in session:
usrname = session["username"]
if request.method == "POST":
search_word = request.form.get('searching')
id_found = Car.query.filter_by(car_id=search_word).all()
brand_found = Car.query.filter_by(brand=search_word).all()
model_found = Car.query.filter_by(model=search_word).all()
cars = []
if id_found or brand_found or model_found:
if id_found:
cars = id_found
elif brand_found:
cars = brand_found
else:
cars = model_found
return render_template("search.html", username=usrname, cars=cars)
else:
flash("No result found!","info")
return render_template("search.html", username=usrname)
else:
flash("You have to enter some word to search!","error")
return render_template("search.html", username=usrname)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/adminSearch", methods=['GET', 'POST'])
def adminSearch():
"""
implement the search function
that user could search by car_id, brand, or model
system select the car table
:return a list of car that detail match the user type in
"""
if "username" in session:
usrname = session["username"]
if request.method == "POST":
search_word = request.form.get('searching')
id_found = Car.query.filter_by(car_id=search_word).all()
brand_found = Car.query.filter_by(brand=search_word).all()
model_found = Car.query.filter_by(model=search_word).all()
username_found = User.query.filter_by(username=search_word).all()
cars = []
users = []
if id_found or brand_found or model_found:
if id_found:
cars = id_found
elif brand_found:
cars = brand_found
else:
cars = model_found
return render_template("adminSearch.html", username=usrname, cars=cars)
if username_found:
users = username_found
return render_template("adminSearch.html", username=usrname, users = users)
else:
flash("No result found!","info")
return render_template("adminSearch.html", username=usrname)
else:
flash("You have to enter some word to search!","error")
return render_template("adminSearch.html", username=usrname)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
def Listening():
MIC_NAME = "Microsoft® LifeCam HD-3000: USB Audio (hw:1,0)"
# Set the device ID of the mic that we specifically want to use to avoid ambiguity
for i, microphone_name in enumerate(sr.Microphone.list_microphone_names()):
if(microphone_name == MIC_NAME):
device_id = i
break
# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone(device_index = device_id) as source:
# clear console of errors
subprocess.run("clear")
# wait for a second to let the recognizer adjust the
# energy threshold based on the surrounding noise level
r.adjust_for_ambient_noise(source)
print("Say something!")
try:
audio = r.listen(source, timeout = 1.5)
except sr.WaitTimeoutError:
print("Listening timed out whilst waiting for phrase to start")
quit()
# recognize speech using Google Speech Recognition
try:
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
print("Google Speech Recognition thinks you said '{}'".format(r.recognize_google(audio)))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
@app.route("/delete/<int:id>", methods=['GET', 'POST'])
def delete(id):
"""
method for handler the delete button on website
admin can delete a car
if deleted successful
:return a deleted successful message and return to current page
"""
car = Car.query.filter(Car.car_id == id).first()
if car:
if request.method == 'GET' :
db.session.delete(car)
db.session.commit()
flash('Car deleted successfully!')
return render_template('adminBase.html')
else:
return 'Error loading #{id}'.format(id=id)
@app.route("/deleteUser/<string:username>", methods=['GET', 'POST'])
def deleteUser(username):
"""
method for handler the delete button on website
admin can delete a car
if deleted successful
:return a deleted successful message and return to current page
"""
user = User.query.filter(User.username == username).first()
if user:
if request.method == 'GET' :
db.session.delete(user)
db.session.commit()
flash('User deleted successfully!')
return render_template('adminBase.html')
else:
return 'Error loading #{username}'.format(username = username)
@app.route("/book/<int:id>", methods=['GET', 'POST'])
def book(id):
"""
method for handler the book button on website
user could book a car during the time that user want to use
if book successful
:return a booking successful message and return to current page
"""
if "username" in session:
usrname = session["username"]
to_book = Car.query.get_or_404(id)
if request.method == 'POST':
duration_post = request.form['duration']
if duration_post == "":
flash("You must enter an duration", "error")
return render_template("book.html", username=usrname, car = to_book)
else:
time = int(duration_post)
eventId = insert(time)
print(eventId)
new_booking = Booking(username=usrname, car_id=id, duration=duration_post, event_id=eventId)
car_found = Car.query.filter_by(car_id = id).first()
car_found.available = False
db.session.add(new_booking)
db.session.commit()
flash("Your booking is successful!", "info")
return redirect(url_for("current"))
else:
return render_template("book.html", username=usrname, car = to_book)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/report/<int:id>", methods=['GET', 'POST'])
def report(id):
"""
method for handler the report button on admin website
admin could report a car with issues to the engineer
:return a reporting successful message and return to admin home page
"""
if "username" in session:
usrname = session["username"]
to_report = Car.query.get_or_404(id)
if request.method == 'POST':
issue_post = request.form['issue']
if issue_post == "":
flash("You must enter an Issue", "error")
return render_template("report.html", username=usrname, car = to_report)
else:
car_found = Car.query.filter_by(car_id = id).first()
car_found.issues = issue_post
car_found.available = False
to_report = "Car Id: " + str(car_found.car_id) + "\nBrand: " + car_found.brand + "\nModel: " + car_found.model + "\nIssues: " + car_found.issues
push = pb.push_note("A new car is reported by the admin!", to_report)
db.session.commit()
flash("You Have succesffuly Reported The Car !", "info")
return render_template('adminBase.html')
else:
return render_template("report.html", username=usrname, car = to_report)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
@app.route("/repair/<int:id>")
def repair(id):
"""
Method to repair the reported cars.
"""
car_to_repair = Car.query.get_or_404(id)
try:
car_to_repair.issues = None
car_to_repair.available = True
db.session.commit()
return redirect(url_for("getAllReports"))
except:
flash("There is a problem to repair this car!","error")
return redirect(url_for("getAllReports"))
def insert(time):
"""
method for insert the event to user google calendar
after booked a car calling this method and than insert event during the user book car time
:return the eventID and save into the database for late if user want to delete this event
"""
now = datetime.utcnow().isoformat() + "Z"
date = datetime.now()
book = (date + timedelta(hours=time)).strftime("%Y-%m-%dT%H:%M:%S+10:00")
time_start = date.strftime("%Y-%m-%dT%H:%M:%S+10:00").format()
time_end = book.format()
event = {
"summary": "New Car Booking Event",
"location": "RMIT Building 14",
"description": "Adding New Car Booking Event",
"start": {
"dateTime": time_start,
"timeZone": "Australia/Melbourne",
},
"end": {
"dateTime": time_end,
"timeZone": "Australia/Melbourne",
},
"attendees": [
{ "email": "[email protected]" },
],
"reminders": {
"useDefault": False,
"overrides": [
{ "method": "email", "minutes": 5 },
{ "method": "popup", "minutes": 10 },
],
}
}
event = service.events().insert(calendarId ="primary", body = event).execute()
eventId = event.get('id')
return eventId
## store the eventID into the database
#socketio event handler
#when use img to log in
def img_authenticate(imgname):
"""
socketio event handler
when use img to login
"""
userimgname = User.query.filter_by(firstname=imgname).first()
if imgname:
return True
#when use password to log in
def authenticate(username, password):
"""
socketio event handler
when use username and password to login
"""
username_found = User.query.filter_by(username=username).first()
##verify hash password
password_found = sha256_crypt.verify(password, username_found.password)
if username_found and password_found:
return True
else:
return False
def finishBook(carId):
"""
this function for find list of car that user booked
and after return change the car status
"""
car_to_finish = Car.query.filter_by(car_id=carId).first()
booking_to_finish = Booking.query.filter_by(car_id=carId, finish=False).first()
booking_to_finish.status = "Finished"
car_to_finish.available = True
db.session.commit()
eventID = booking_to_finish.event_id
service.events().delete(calendarId='primary', eventId=eventID).execute()
print('Succefully return the car!!')
def ack():
print ('message was received!')
@socketio.on('identity')
def handle_my_custom_event(json):
"""
handle the customer event by json
"""
print('received json: ' + str(json))
username = json['username']
password = json['password']
authenticate_pass = authenticate(username,password)
if authenticate_pass == True:
emit('validate', {'result' : 'success'}, callback=ack)
else:
emit('validate', {'result' : 'fail'}, callback=ack)
@socketio.on('name')
def handle_my_custom_event(json):
"""
handle the customer event by json
"""
print('received json: ' + str(json))
imgname = json['imgname']
authenticate_pass = img_authenticate(imgname)
if authenticate_pass == True:
emit('validate', {'result' : 'success'}, callback=ack)
else:
emit('validate', {'result' : 'fail'}, callback=ack)
@socketio.on('finish')
def handle_finish(json):
car_id = json['car_id']
finishBook(car_id)
emit('my response', {'result': 'Return succeed!'})
@socketio.on('connect')
def test_connect():
"""
that just for return a message when connected
"""
print('Client connected')
emit('my response', {'data': 'Connected'})
@socketio.on('disconnect')
def test_disconnect():
"""
that just for return a message when disconnected
"""
print('Client disconnected')
def updateNumOfBrand():
#For the visualisation dashboard
labels = [
'BMW', 'Benz', 'Telsla', 'Mazda',
'Toyota', 'Honda', 'Maruti' ]
#find the number of each brand in all bookings
bmw = 0
benz = 0
telsla = 0
mazda = 0
toyota = 0
honda = 0
maruti = 0
bookings = Booking.query.all()
for booking in bookings:
id = booking.car_id
car = Car.query.filter_by(car_id = id).first()
if car != None:
if car.brand == "BMW":
bmw = bmw + 1
if car.brand == "Benz":
benz = benz + 1
if car.brand == "Telsla":
telsla = telsla + 1
if car.brand == "Mazda":
mazda = mazda + 1
if car.brand == "Toyota":
toyota = toyota + 1
if car.brand == "Honda":
honda = honda + 1
if car.brand == "Maruti":
maruti = maruti + 1
values = [bmw, benz, telsla, mazda, toyota, honda, maruti]
return labels, values
@app.route('/bar')
def bar():
update = updateNumOfBrand()
bar_labels = update[0]
bar_values= update[1]
return render_template('bar_chart.html', title='Number of Car Brand Booked', max=30, labels=bar_labels, values=bar_values)
@app.route('/line')
def line():
update = updateNumOfBrand()
line_labels = update[0]
line_values = update[1]
return render_template('line_chart.html', title='Number of Car Brand Booked', max=30, labels=line_labels, values=line_values)
@app.route('/pie')
def pie():
update = updateNumOfBrand()
pie_labels = update[0]
pie_values = update[1]
colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA", "#ABCDEF", "#DDDDDD", "#ABCABC"]
return render_template('pie_chart.html', title='Number of Car Brand Booked', max=30, set=zip(pie_values, pie_labels, colors))
#Google map
@app.route("/map")
def mapview():
if "username" in session:
usrname = session["username"]
cars_found = Car.query.filter(Car.issues.isnot(None)).all()
carMarkers = list()
for car in cars_found:
carMarker = {
'icon': 'http://maps.google.com/mapfiles/kml/pal4/icon15.png',
'lat': car.locationY,
'lng': car.locationX,
'infobox': "Car Id: " + str(car.car_id) +
" Brand: " + car.brand +
" Model: " + car.model +
" Issues: " + car.issues
}
carMarkers.append(carMarker)
sndmap = Map(
identifier = "sndmap",
lat = 37.4419 ,
lng = -122.1419 ,
markers = carMarkers,
fit_markers_to_bounds = True,
style="height:600px;width:1000px;margin:0;"
)
return render_template('map.html', sndmap=sndmap)
else:
flash("You must login first!","info")
return redirect(url_for("login"))
# creating a map in the view
if __name__ == "__main__":
socketio.run(app, debug = True)