我正在使用wunderground的json api查询我的网站上的天气情况。该api为我提供了一个不错的json对象,其中包含所有必要的数据,但我每天只能进行多次调用。存储该数据的首选方式是什么?

我当时正在考虑将json转储到文件中,并检查其时间戳:如果说它早于60分钟,则获取新的json并覆盖,如果不是,则从磁盘读取文件。我不会创建数据库表来存储我本质上不需要的天气数据。是否有一些聪明的Django缓存此过程的方法,还是应该手动执行?

最佳答案

是的,Django具有内置的缓存机制。如果您不想安装缓存服务器,则可以使用文件系统缓存,该缓存与您正在谈论的缓存几乎相同,但是您不必自己滚动它。

Here's the documentation.

您可以在settings.py中放入类似的内容

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

然后,在您的应用程序代码中,您可以具有一些逻辑来检查高速缓存,如果找不到高速缓存,则可以从服务器加载它并对其进行高速缓存。
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

10-08 02:36