2
2
import requests
3
3
from django .shortcuts import render
4
4
from environs import Env
5
+ from django .core .cache import cache
6
+
5
7
6
8
7
9
env = Env ()
@@ -41,19 +43,27 @@ def fetch_weather_data(city):
41
43
42
44
def receive_coordinates (request ):
43
45
"""Show the user's current location weather."""
46
+ current_location_weather = None
47
+ city = None
44
48
coords = request .GET .getlist ("coord" )
45
49
api_key = env .str ('API_KEY' )
46
50
47
- if coords :
48
- lat = coords [0 ]
49
- lon = coords [1 ]
50
- url = f"http://api.weatherapi.com/v1/current.json?key={ api_key } &q={ lat } ,{ lon } "
51
- try :
52
- response = response = requests .get (url )
53
- response .raise_for_status ()
54
- current_location = response .json ()
55
- city = current_location ["location" ]["name" ]
56
- except requests .exceptions .RequestException :
57
- current_location = None
58
- city = None
59
- return render (request , 'myApp/index.html' , {'weather' :current_location , 'city' : city })
51
+ if coords and len (coords ) == 2 :
52
+ lat , lon = coords [0 ], coords [1 ]
53
+ cache_key = f"weather_{ lat } _{ lon } "
54
+ current_location_weather = cache .get (cache_key )
55
+ if not current_location_weather :
56
+ print ("Nabood" )
57
+ url = f"http://api.weatherapi.com/v1/current.json?key={ api_key } &q={ lat } ,{ lon } "
58
+ try :
59
+ response = response = requests .get (url )
60
+ response .raise_for_status ()
61
+ current_location_weather = response .json ()
62
+ city = current_location_weather ["location" ]["name" ]
63
+ cache .set (cache_key , current_location_weather , 300 )
64
+ except requests .exceptions .RequestException :
65
+ current_location_weather = None
66
+
67
+ if current_location_weather :
68
+ city = current_location_weather .get ("location" , {}).get ("name" )
69
+ return render (request , 'myApp/index.html' , {'weather' :current_location_weather , 'city' : city })
0 commit comments