gpt4 book ai didi

Django json 策略?

转载 作者:行者123 更新时间:2023-12-01 11:01:46 28 4
gpt4 key购买 nike

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

我正在考虑将 json 转储到一个文件中,并检查它的时间戳:如果它超过 60 分钟,则获取新的并覆盖,如果不是,则从磁盘读取文件。我不会创建一个数据库表来存储我根本不需要的天气数据。是否有一些聪明的 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

关于Django json 策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990347/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com