Skip to content

Commit 33b9914

Browse files
committedApr 13, 2025
django cache added to settings.py and view for optimizing external api request
1 parent b2dd106 commit 33b9914

File tree

2 files changed

+32
-13
lines changed

2 files changed

+32
-13
lines changed
 

‎myApp/views.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import requests
33
from django.shortcuts import render
44
from environs import Env
5+
from django.core.cache import cache
6+
57

68

79
env = Env()
@@ -41,19 +43,27 @@ def fetch_weather_data(city):
4143

4244
def receive_coordinates(request):
4345
"""Show the user's current location weather."""
46+
current_location_weather = None
47+
city = None
4448
coords = request.GET.getlist("coord")
4549
api_key = env.str('API_KEY')
4650

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})

‎weatherApp/settings.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,12 @@
134134
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
135135

136136
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
137+
138+
139+
# caching settings
140+
CACHES = {
141+
'default': {
142+
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', # Using local memory
143+
'LOCATION': 'unique-snowflake', # Unique identifier for this cache instance
144+
}
145+
}

0 commit comments

Comments
 (0)
Please sign in to comment.