Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django json strategy?

I am using wunderground's json api to query for weather conditions on my site. The api gives me a nice json object with all the neccesary data, but I am limited to a number of calls per day. What would be the preferred way to store this data?

I was thinking to dump the json to a file, and check for it's timestamp: if it's say older than 60 minutes, then fetch the new one and overwrite, if it is not, read the file from the disk. I wouldn't create a database table just to store weather data that I don't essentially need. Is there some clever Django way of caching this process or should I do it manually?

like image 927
freethrow Avatar asked Oct 28 '25 14:10

freethrow


1 Answers

Yes, Django has a built in caching mechanism. If you don't want to install a caching server, you could use the file system cache, which would be pretty much the same as what you're talking about, but you wouldn't have to roll it yourself.

Here's the documentation.

You would put something like this in your settings.py

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
}

In your app code, you could then have some logic to check the cache, and if it isn't found, then load it from the server and cache it.

from django.core.cache import cache

weather_json_data = cache.get('weather_90210'):
if not weather_json_data:
    weather_json_data = get_data_from_api(zip)

    cache.set('weather_{0}'.format(zip), weather_json_data, 60)

#return the weather_json_data through HttpResponse here
like image 169
Jordan Avatar answered Oct 31 '25 04:10

Jordan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!