-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
974 lines (669 loc) · 38.2 KB
/
views.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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
from django.shortcuts import render, redirect , HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.contrib import messages
from .models import Profile , Officer
from geopy.geocoders import Nominatim
import requests
import json
import geocoder
from geopy.distance import geodesic
from dotenv import load_dotenv
import os
load_dotenv()
alert = [
{
'warning': 'thunderstorm with heavy rain',
'id':'202',
'message': """Attention Please!
🌩 Skysense Weather Update 🌧
Hello there! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
🚨 Today's Weather Alert:
⚠ Severe Thunderstorm Warning ⚠
A thunderstorm with heavy rain is approaching Coimbatore. Take immediate precautions to ensure your safety.
🌧 Weather Impact:
Heavy Rainfall: Expect intense downpour with the potential for localized flooding. Be vigilant around low-lying areas and avoid crossing flooded roads.
Thunder and Lightning: Anticipate frequent thunder and lightning activity. Stay indoors and avoid open areas to reduce the risk of lightning strikes.
Strong Winds: Prepare for gusty winds that may result in fallen branches or flying debris. Secure loose objects to prevent damage or injury.
Reduced Visibility: Exercise caution while driving or traveling due to decreased visibility caused by heavy rain and thunderstorm activity.
📝 Safety Tips:
Seek Shelter: Move indoors to a safe location, preferably a sturdy building or a designated storm shelter. Stay away from windows and doors.
Stay Informed: Stay updated with the latest weather updates from reliable sources. Follow instructions and warnings issued by local authorities.
Emergency Preparedness: Have essential supplies like flashlights, batteries, non-perishable food, and a first aid kit readily available.
Postpone Outdoor Activities: Avoid outdoor activities until the thunderstorm subsides and conditions improve.
Please stay safe and take necessary precautions during this thunderstorm with heavy rain. If you have any further inquiries, feel free to reach out. Take care! ⛈😊
Skysense Weather Team
""",
},
{
'warning': 'heavy thunderstorm',
'id':'212',
'message': """
Attention Please!
🌩 Skysense Weather Update 🌩
Hello there! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
🚨 Today's Weather Alert:
⚠ Severe Thunderstorm Warning ⚠
A heavy thunderstorm is approaching Coimbatore, bringing potential hazards. Take immediate precautions to ensure your safety.
🌧 Weather Impact:
Intense Rainfall: Expect heavy downpour and localized flooding. Be cautious of water accumulation and potential flash floods.
Strong Winds: Prepare for gusty winds and take measures to secure loose objects to prevent damage or injury.
Lightning Strikes: Seek shelter indoors and avoid open areas to reduce the risk of lightning strikes.
Reduced Visibility: Exercise caution while driving or traveling due to limited visibility caused by heavy rain and thunderstorm activity.
📝 Safety Tips:
Seek Shelter: Move indoors to a safe location, preferably a sturdy building or a designated storm shelter. Stay away from windows and doors.
Stay Informed: Keep updated with the latest weather updates from reliable sources. Follow instructions from local authorities.
Emergency Preparedness: Have essential supplies like flashlights, batteries, non-perishable food, and a first aid kit on hand.
Postpone Outdoor Activities: Avoid venturing outside until the storm passes and conditions improve.
Please stay safe and take necessary precautions during this heavy thunderstorm. Feel free to reach out if you have any further inquiries. Take care! ⛈😊
Skysense Weather Team""",
},
{
'warning': 'thunderstorm with heavy drizzle',
'id':'232',
'message': """
Greeting! This is Skysense, your weather companion bot. Here's your daily weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
📝 Today's Weather Advisories:
⚠ Severe Weather Alert: A thunderstorm with heavy drizzle is expected in Coimbatore. Take the following precautions:
Seek shelter: Find a safe location indoors, away from windows and exterior walls.
Stay informed: Keep updated on the latest weather reports and follow any instructions from local authorities.
Be cautious on the roads: Exercise caution while driving due to reduced visibility and potentially slippery conditions.
Secure outdoor objects: Safely secure or bring indoors any items that could be affected by strong winds.
Avoid flooded areas: Stay away from flooded roads, bridges, and low-lying areas. Do not attempt to cross flowing water.
Stay safe and dry during the thunderstorm with heavy drizzle. If you have any questions or need further assistance, feel free to ask. Take care! ☔😊
Skysense Weather Team
Regenerate response
""",
},
{
'warning': 'heavy intensity drizzle',
'id':'302',
'message': """Attention Please!
☔ Skysense Weather Update ☁
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
Heavy Intensity Drizzle Warning ⚠
A heavy intensity drizzle is expected in Coimbatore. While not severe, it's important to stay prepared and take precautions.
🌧 Weather Impact:
Moderate Rainfall: Anticipate a continuous and steady drizzle with moderate rainfall throughout the day.
Reduced Visibility: Be cautious while driving or commuting due to reduced visibility caused by the heavy intensity drizzle.
Slippery Conditions: Watch out for slippery surfaces, such as roads, walkways, and stairs. Take necessary precautions to prevent accidents.
📝 Safety Tips:
Carry an Umbrella: Keep an umbrella or raincoat handy to stay dry during the heavy drizzle.
Wear Proper Footwear: Opt for non-slip shoes or boots to maintain better traction on wet surfaces.
Drive Safely: Slow down and maintain a safe distance from other vehicles. Turn on your headlights and use caution while braking.
Stay Dry: Wear appropriate rain gear and protect electronic devices from moisture.
Please stay cautious and take necessary measures during this period of heavy intensity drizzle. If you have any further inquiries, feel free to reach out. Stay safe! ☔😊
Skysense Weather Team""",
},
{
'warning': 'heavy intensity drizzle rain',
'id':'312',
'message': """Attention Please!
☔ Skysense Weather Update ☁
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
Heavy Intensity Drizzle with Rain Warning ⚠
Coimbatore is experiencing heavy intensity drizzle with rain. Please take necessary precautions to ensure your safety.
🌧 Weather Impact:
Heavy Intensity Drizzle: Expect continuous and heavy drizzle combined with rainfall throughout the day.
Reduced Visibility: Exercise caution while driving or commuting due to reduced visibility caused by the heavy intensity drizzle and rain.
Slippery Conditions: Be mindful of slippery surfaces, such as roads, walkways, and stairs. Take necessary precautions to prevent accidents.
📝 Safety Tips:
Carry an Umbrella: Keep an umbrella or raincoat handy to stay dry during the heavy intensity drizzle and rain.
Wear Proper Footwear: Opt for non-slip shoes or boots to maintain better traction on wet surfaces.
Drive Safely: Slow down and maintain a safe distance from other vehicles. Turn on your headlights and use caution while braking.
Stay Dry: Wear appropriate rain gear and protect electronic devices from moisture.
Please stay cautious and take necessary measures during this period of heavy intensity drizzle with rain. If you have any further inquiries, feel free to reach out. Stay safe! ☔😊
Skysense Weather Team""",
},
{
'warning': 'heavy intensity rain',
'id':'502',
'message': """Attention Please!
☔ Skysense Weather Update ☔
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
Heavy Intensity Rain Warning ⚠
Coimbatore is currently experiencing heavy intensity rain. Please take necessary precautions to ensure your safety.
🌧 Weather Impact:
Heavy Intensity Rainfall: Expect continuous and heavy rainfall throughout the day.
Possible Flooding: Be cautious of potential flooding in low-lying areas and near water bodies. Avoid crossing flooded roads.
Reduced Visibility: Exercise caution while driving or commuting due to reduced visibility caused by the heavy intensity rain.
📝 Safety Tips:
Stay Indoors: If possible, remain indoors until the heavy rain subsides. Seek shelter in a safe and dry location.
Monitor Water Levels: Stay informed about any flood warnings or advisories issued by local authorities.
Avoid Flooded Areas: Do not attempt to walk, drive, or swim through flooded areas. Turn around and find an alternate route.
Stay Connected: Keep your mobile devices charged and stay updated with weather alerts and updates from reliable sources.
Please stay cautious and take necessary measures during this period of heavy intensity rain. If you have any further inquiries, feel free to reach out. Stay safe! ☔😊
Skysense Weather Team""",
},
{
'warning': 'extreme rain',
'id':'504',
'message': """Attention Please!
☔ Skysense Weather Update ☔
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
Extreme Rain Warning ⚠
Coimbatore is currently experiencing extreme rainfall. Please take immediate precautions to ensure your safety.
🌧 Weather Impact:
Extreme Rainfall: Expect intense and prolonged rainfall throughout the day, potentially leading to widespread flooding.
Flash Floods: Be aware of the possibility of flash floods in low-lying areas and near water bodies. Avoid crossing flooded roads.
Limited Visibility: Exercise extreme caution while driving or commuting due to significantly reduced visibility caused by the heavy rain.
📝 Safety Tips:
Stay Indoors: It is strongly advised to stay indoors and avoid unnecessary travel during extreme rain conditions.
Emergency Preparedness: Have essential supplies, such as food, water, flashlights, and a first aid kit, readily available.
Monitor Updates: Stay tuned to local weather reports and emergency notifications for the latest information and guidance.
Follow Authorities' Instructions: Adhere to any evacuation orders or safety directives issued by local authorities.
Please prioritize your safety and take immediate measures during this period of extreme rain. If you have any further inquiries, feel free to reach out. Stay safe! ☔😊
Skysense Weather Team""",
},
{
'warning': 'freezing rain',
'id':'511',
'message': """
Attention Please!
❄ Skysense Weather Update ❄
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
Freezing Rain Warning ⚠
Coimbatore is currently experiencing freezing rain. Please take immediate precautions as this can create hazardous conditions.
❄ Weather Impact:
Freezing Rain: Expect rain that freezes upon contact with the ground or surfaces, forming a layer of ice.
Hazardous Road Conditions: Be cautious of icy roadways, sidewalks, and other surfaces. They can be extremely slippery.
Power Outages: Freezing rain can cause ice accumulation on power lines, potentially leading to power outages.
📝 Safety Tips:
Stay Indoors: If possible, remain indoors and avoid travel until conditions improve.
Use Caution: If you must go outside, walk slowly and carefully on icy surfaces. Use handrails for support.
Dress Warmly: Wear warm clothing and appropriate footwear to stay comfortable in cold temperatures.
Be Prepared: Have emergency supplies, such as flashlights, batteries, non-perishable food, and blankets, readily available.
Please prioritize your safety and take immediate measures during freezing rain conditions. If you have any further inquiries, feel free to reach out. Stay safe! ❄😊
Skysense Weather Team""",
},
{
'warning': 'heavy intensity shower rain',
'id':'522',
'message': """Attention Please!
☔ Skysense Weather Update ☔
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
- Heavy Intensity Shower Rain Warning ⚠
Coimbatore is currently experiencing heavy intensity shower rain. Please take necessary precautions as this may cause localized impacts.
🌧 Weather Impact:
Heavy Intensity Rainfall: Expect intense and heavy showers with increased rainfall rates for a limited period of time.
Rapid Accumulation: Be cautious of rapid water accumulation in low-lying areas and potential localized flooding.
Reduced Visibility: Exercise caution while driving or commuting due to reduced visibility caused by heavy shower rain.
📝 Safety Tips:
Carry an Umbrella or Raincoat: Keep an umbrella or raincoat handy to stay dry during the heavy intensity shower rain.
Watch for Flooded Areas: Be mindful of potential flooding in low-lying areas and near water bodies. Avoid crossing flooded roads.
Drive Safely: Reduce speed and maintain a safe distance from other vehicles. Turn on your headlights and use caution while braking.
Stay Dry Indoors: If possible, stay indoors until the heavy shower rain subsides to minimize exposure to wet conditions.
Please stay cautious and take necessary measures during this period of heavy intensity shower rain. If you have any further inquiries, feel free to reach out. Stay safe! ☔😊
Skysense Weather Team""",
},
{
'warning': 'heavy snow',
'id':'602',
'message':"""Attention Please!
❄ Skysense Weather Update ❄
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
- Heavy Snowfall Warning ⚠
Coimbatore is currently experiencing heavy snowfall. Please take immediate precautions as this can create challenging conditions.
❄ Weather Impact:
Heavy Snowfall: Expect intense and continuous snowfall, leading to significant snow accumulation.
Reduced Visibility: Exercise extreme caution while driving or commuting due to reduced visibility caused by heavy snow.
Hazardous Road Conditions: Be aware of slippery and icy roadways. Travel may be difficult or dangerous.
📝 Safety Tips:
Stay Indoors: If possible, remain indoors and avoid unnecessary travel until conditions improve.
Dress Warmly: Layer up with warm clothing, including hats, gloves, scarves, and insulated footwear.
Clear Pathways: Safely remove snow from driveways, walkways, and stairs to prevent slips and falls.
Use Caution: If you must go outside, walk slowly and carefully on snowy or icy surfaces. Use handrails for support.
Please prioritize your safety and take immediate measures during heavy snowfall conditions. If you have any further inquiries, feel free to reach out. Stay safe and warm! ❄😊
Skysense Weather Team""",
},
{
'warning': 'heavy shower snow',
'id':'622',
'message': """Attention Please!
❄ Skysense Weather Update ☔
Hello! This is Skysense, your trusted weather companion. Here's your weather forecast for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
- Heavy Shower Snow Warning ⚠
Coimbatore is currently experiencing heavy shower snow. Please take necessary precautions as this may cause localized impacts.
❄ Weather Impact:
Heavy Snowfall: Expect intense and heavy snow showers for a limited period of time.
Rapid Snow Accumulation: Be cautious of rapid snow accumulation, which may lead to slippery surfaces and reduced visibility.
Hazardous Road Conditions: Drive with caution and be aware of slippery and icy roadways.
📝 Safety Tips:
Dress Warmly: Layer up with warm clothing, including hats, gloves, scarves, and insulated footwear.
Use Caution: If you must go outside, walk slowly and carefully on snowy or icy surfaces. Use handrails for support.
Clear Pathways: Safely remove snow from driveways, walkways, and stairs to prevent slips and falls.
Drive Safely: Reduce speed and maintain a safe distance from other vehicles. Use winter tires or chains if necessary.
Please stay cautious and take necessary measures during this period of heavy shower snow. If you have any further inquiries, feel free to reach out. Stay safe and warm! ❄😊
Skysense Weather Team""",
},
{
'warning': 'tornado',
'id':'781',
'message': """Attention Please!
🌪 Skysense Weather Update 🌪
Hello! This is Skysense, your trusted weather companion. Here's your weather alert for today:
Location: Coimbatore
Date: 16/7/23
🌡 Temperature: {temperature}
☁ Weather Condition: {description}
💨 Wind Speed: {wind}
💦 Humidity: {humidity}
⚠ Today's Weather Alert:
- Tornado Warning ⚠
Coimbatore is currently under a tornado alert. Please take immediate precautions as this is a dangerous weather situation.
🌪 Weather Impact:
Tornado Formation: A tornado is expected to form in the area, bringing strong and destructive winds.
High Wind Speeds: Expect rapidly increasing wind speeds, with gusts potentially exceeding 100 km/h.
Structural Damage: Tornadoes can cause significant damage to buildings, trees, and infrastructure.
Flying Debris: Take caution against flying debris, which can pose a serious risk to personal safety.
📝 Safety Tips:
Seek Shelter: Move immediately to a sturdy and secure location, preferably an underground shelter or an interior room without windows.
Stay Informed: Keep updated with the latest weather information through local news, radio, or weather alert systems.
Follow Authorities' Instructions: Adhere to any evacuation orders or safety directives issued by local authorities.
Stay Away from Windows: Protect yourself from broken glass and flying debris by staying away from windows and exterior walls.
Remain Calm: Stay calm and reassure others, especially children and pets, while taking necessary precautions.
Please prioritize your safety and take immediate measures during this tornado alert. If you have any further inquiries, feel free to reach out. Stay safe! 🌪😊
Skysense Weather Team""",
},
]
def lati(landmark):
# Create a geocoder object
geolocator = Nominatim(user_agent="my_app")
# Get the landmark input from the user
# Perform geocoding to retrieve the latitude and longitude
location = geolocator.geocode(landmark)
# Check if a valid location was found
if location is not None:
latitude = location.latitude
longitude = location.longitude
return latitude,longitude
else:
return None,None
def datas(x):
l=Profile.objects.get(user_id=x)
latitude = l.latitude # g.latlng[0]
longitude = l.longitude # g.latlng[1]
# Usage
# Set the API endpoint URL
url = "https://api.openweathermap.org/data/2.5/weather"
next_5days = "https://api.openweathermap.org/data/2.5/forecast"
# Set the parameters, including your API key and location
appid = os.getenv("apikey")
next_5days += f'?lat={latitude}&lon={longitude}&appid={appid}'
# Make the HTTP GET request
response = requests.get(next_5days)
# Parse the JSON response
data = response.json()
weather_list = data['list']
weather_id = []
past_date = []
i =0
for day in weather_list:
date = day['dt_txt'].split()
first_word = date[0]
if first_word not in past_date:
past_date.append(first_word)
li = {
'temp':day['main']['temp'],
'humidity':day['main']['humidity'],
'date':day['dt_txt'],
'id':day['weather'][0]['id'],
'main':day['weather'][0]['main'],
'description':day['weather'][0]['description'],
'temp_min':day['main']['temp_min'],
'temp_max':day['main']['temp_max'],
'location':l.landmark.capitalize()
}
print(li['main'])
print('des',li['description'])
weather_id.append(li)
return weather_id
def alerts(first):
print(first)
climate_id = first['id']
print('cid ::',climate_id)
fl = 0
for climate in alert:
if str(climate_id) in climate['id']:
message = climate['message']
message = message.format(temperature=first['temp'],description=first['description'],wind=50,humidity=first['humidity'])
print(message)
fl = 1
final_temp = int(((first['temp_min']+first['temp_max'])-2*273)//2)
mes="""
\tCondition: {main}
\tDescription: {description}!
\tTemperature: {final_temp}°C
\tHumidity: {humidity}%
""".format(final_temp=final_temp,temp_min=first['temp_min'],temp_max=first['temp_max'],description=first['description'].capitalize(),humidity=first['humidity'],main=first['main'])
return mes
def home(request):
first={'id':None,'main':None,'temp':None,'location':None}
next_four=None
if request.user.is_authenticated:
climate_data = datas(request.user.id)
first = climate_data[0]
alerts(first)
second =climate_data[1]
third =climate_data[2]
froth = climate_data[3]
fifth = climate_data[4]
next_four =[[second['id'],second['main'],'Day - 2',second['humidity'],int(second['temp']-273),second['description']],[third['id'],third['main'],'Day - 3',third['humidity'],int(third['temp']-273),third['description']],[froth['id'],froth['main'],'Day - 4',froth['humidity'],int(froth['temp']-273),froth['description']],[fifth['id'],fifth['main'],'Day - 5',fifth['humidity'],int(fifth['temp']-273),fifth['description']]]
first['temp']=int(first['temp']-273)
return render(request,'home.html',{
'first_id':first['id'],
'first_main':first['main'],
'land':first['location'],
'temp':first['temp'],
'next_four':next_four,
})
def signup(request):
us=list(User.objects.all().values_list('username',flat=True))
if request.method=='POST':
username=request.POST.get('username')
phone=request.POST.get('phone')
city=request.POST.get('inputdistrict')
state=request.POST.get('inputstate')
sms=bool(request.POST.get('sms'))
password1=request.POST.get('pass1')
password2=request.POST.get('pass2')
land=request.POST.get('land')
lat,lon=lati(land)
if len(phone)!=10 or not phone.isdigit():
messages.error('Enter a valid phone number of 10 digits...')
elif username not in us and password1==password2 and lat and lon and len(str(phone))==10:
x=User.objects.create(
username=username,
password=password1,
)
Profile.objects.create(
user=x,
phone_no=phone,
city=city,
state=state,
sms_enabled=sms,
landmark=land,
latitude=lat,
longitude=lon,
)
login(request,x)
return redirect('whatsapp_permission')
elif lat==None and lon==None:
messages.error(request,'Couldn\'t find the location. Try giving any city names...')
elif username in us:
messages.error(request,'Username already exits...')
elif password1!=password2:
messages.error(request,'Passwords doesn\'t match...')
else:
messages.error(request,'Enter a valid phone number')
print(messages,'hi')
return render(request, 'signup.html')
def Login(request):
if request.method=='POST':
username=request.POST.get('username')
password=request.POST.get('password')
try:
user=User.objects.get(username=username)
except:
#messages="User doesn't exist."
messages.error(request, 'User doesn\'t exist')
user=authenticate(request,username=username,password=password)
print(user)
if user is not None:
login(request,user )
return redirect('home')
else:
messages.error(request,'Username or password doesn\'t match...')
return render(request,'login.html')
def Logout(request):
logout(request)
return redirect('home')
def whatsapp_permission(request):
if not request.user.is_authenticated:
return redirect('login')
if request.method=='POST':
climate_data = datas(request.user.id)
first = climate_data[0]
mes=alerts(first[0])
profile=Profile.objects.get(user_id=request.user.id)
# from twilio.rest import Client
account_sid = os.getenv("account_sid")
auth_token = os.getenv("auth_token")
client = Client(account_sid, auth_token)
message = client.messages.create(
from_='whatsapp:+14155238886',
body="""Hello! This is Sky Sense, your trusted weather companion.\n🌤️ Weather Forecast for Today - {} 🌤️""".format(str(profile.landmark))+str(mes),
to='whatsapp:+91'+str(profile.phone_no)
)
return redirect('home')
return render(request,'whatsapp.html')
def smsdetails(request):
return render(request,'sms.html')
def about(request):
return render(request,'about.html')
def emergency(request):
if request.method == 'POST':
user_id = request.user.id
user = Profile.objects.get(user_id=user_id)
call = request.POST.get('call')
call = warning_message(call)
if call!= 0:
user_lat = user.latitude
user_lon = user.longitude
profiles= Profile.objects.all()
fl =0
for profile in profiles:
if profile == user:
continue
else:
if profile.job =='officer':
officer_lat = profile.latitude
officer_lon = profile.longitude
if nearby(user_lat,user_lon,officer_lat,officer_lon) <= 20:
officer_num = profile.phone_no
print(f'got it {user} {profile}')
whatsapp_fun(officer_num,warning_officer[call],user.phone_no)
officer = User.objects.get(id=profile.user.id)
officer_details = {'name':officer.username,'phone_no':profile.phone_no}
request.session['officer_details'] = officer_details
# rdirect to success page is found officer
return redirect('/success/')
else:
HttpResponse('<h1>Trying to reach to nearby officers</h1>')
return redirect('/rescue_process/')
else:
messages.error(request,'Invalid Emergency number')
return render(request,'emergency.html')
def emergency_numbers(request):
return render(request,'emgreference.html')
def success(request):
# access the message if any
# messages.get_messages(request)
#access the object from the session if any
officer_details = request.session.get('officer_details')
return render(request,'success.html',{
'officer_details':officer_details,
})
# views.py
from django.http import JsonResponse
def handle_ajax_request(request):
if request.method == 'POST':
# Assuming your data is sent as JSON, you can access it using request.POST
try:
# Load JSON data from the request body
data = json.loads(request.body)
# Access the 'data_from_js' field
# latitude = data.get('latitude', None)
# longitude = data.get('longitude', None)
try:
user = request.user
# Process the data or perform any required actions
# ...
user = User.objects.get(username=user)
print(user)
user = Profile.objects.get(user=user)
lat = user.latitude
lon = user.longitude
user.latitude = lat
user.longitude = lon
user.save()
except:
print('in ajax function')
# Return a response (e.g., JSON response)
response_data = {
'message': 'Data received and processed successfully!',
'status': 'success',
}
return JsonResponse(response_data)
except json.JSONDecodeError as e:
return JsonResponse({'error': 'Invalid request method'}, status=400)
else:
return JsonResponse({'error': 'Invalid request method'}, status=400)
def officer_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
trying = 0
# try:
# print('helloworld')
# # user = Profile.objects.get(user=user,job='officer')
# # print(user)
# except:
# messages.error(request,'Officer with this name doesn\'t exits')
try:
user = User.objects.get(username=username)
trying = Profile.objects.filter(user=user)
if trying[0].job == 'officer':
print('passed 1')
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
print('passed 2')
return redirect('/about/')
else:
HttpResponse('you are not allowed you fucker')
except:
print('worked correctly for not officers')
messages.error(request,'you are not allowed')
return render(request,'officer.html')
def rescue_process(request):
return render(request,'rescue.html')
def warning_message(em_num):
final = 0
if str(em_num) == '351':
final = 'cyclone'
print(em_num)
elif str(em_num) == '361':
final = 'thunder'
elif str(em_num) == '451':
final = 'flood'
elif str(em_num) == '551':
final = 'landslides'
else:
final = 0
return final
def nearby(user_lat,user_lon,officer_lat,officer_lon):
return geodesic((user_lat, user_lon), (officer_lat, officer_lon)).kilometers
from twilio.rest import Client
def whatsapp_fun(num,message,danger_user_no):
account_sid = os.getenv("account_sid")
auth_token = os.getenv("auth_token")
client = Client(account_sid, auth_token)
message = client.messages.create(
from_='whatsapp:+14155238886',
body=f'{message} \n Mobile no : {danger_user_no}📱',
to='whatsapp:+91'+str(num)
)
print('success')
warning_officer = {
'flood':""" safety officers!
🚨 I have an emergency situation here, and I urgently need your help at the Flood Zone.
🚑 Please come to the location as fast as you can!
🏃♂️🏃♀️💨 #HelpNeeded #Emergency 🆘""",
'thunder':"""safety officers!
🚨 I have an emergency situation here, and I urgently need your help at the Thunder Zone.
🚑 Please come to the location as fast as you can!
🏃♂️🏃♀️💨 #HelpNeeded #Emergency 🆘""",
'cyclone':"""safety officers!
🚨 I have an emergency situation here, and I urgently need your help at the cyclone Zone.
🚑 Please come to the location as fast as you can!
🏃♂️🏃♀️💨 #HelpNeeded #Emergency 🆘""",
'landslides':"""safety officers!
🚨 I have an emergency situation here, and I urgently need your help at the landslides Zone.
🚑 Please come to the location as fast as you can!
🏃♂️🏃♀️💨 #HelpNeeded #Emergency 🆘""",
}