python - 如何在 django 中限制对外部 API 的调用
问题描述
我有一个显示 YouTube 频道所有帖子的应用程序。为此,我使用我在 views.py 中调用的 youtube-API v3。然后我将所有数据保存在我的数据库中,这些数据作为上下文传递给我的渲染函数:
return render(request, "blog/home.html", context)
我想知道如果最后一次 API 调用是在 5 分钟前,是否可以只调用 API,否则只使用数据库中的数据。
我的一个想法是在进行 API 调用时将当前日期时间保存到文件中,并且每当调用视图函数时,将当前日期时间与文件中的日期时间进行比较。但是,这似乎效率低下,我想知道是否有更好的方法。
解决方案
我做了类似于你描述的事情,不确定这是否对你有帮助。对我来说,它只能每分钟再次请求
@api_view(['GET'])
@permission_classes([AllowAny])
def api_get_cha3_price(request):
response_data = {}
# Get Cha3 price and the logics
d = CryptoPrice.objects.get(name='CHA3') # get the last updated time
d = d.date.replace(tzinfo=None) + timedelta(hours=8,
seconds=3) # +8 hours because it's malaysia time and 1 minute is so that if > 1 minute can request again
d1 = datetime.now()
cha3 = CryptoPrice.objects.get(name='CHA3')
if d1 > d:
import time
try:
timestamp = int(time.time() * 1000)
response = requests.get(
f"API_URL",
timeout=2)
if response.status_code == 200:
data = response.json()
cha3.price = data['data'][0]['price']
cha3.date = timezone.now()
cha3.save()
cha3_price = cha3.price
response_data["cha3_price"] = f"{cha3_price}"
except(requests.exceptions.Timeout, requests.exceptions.ConnectionError, KeyError, TypeError):
cha3_price = cha3.price
response_data["ERROR"] = f"{cha3_price}"
else:
cha3_price = cha3.price
response_data["cha3_price"] = f"{cha3_price}"
return Response(data=response_data)
推荐阅读
- python-3.x - 我正在尝试从函数 int_err() 调用函数 Msg() 并从 Msg() 调用 int_err()
- python - 计算椭圆之间相交的面积 - python
- javascript - JavaScript Konami 代码问题。包含代码
- reactjs - 在反应表钩子中使用反引号
- mysql - 为每个组选择第一行和最后一行并取MySQL中的列值差异?
- javascript - 如何使用 jQuery 和 Ajax 拆分来自选择元素的数据
- javascript - 以编程方式将内联 onfocus 和 onblur 添加到输入/div
- python - pandas - 通过模将列表转换为列
- python - 使用 Python 和 OpenCV 的万花筒效果
- flutter - Flutter 从 API 快照中获取数据。hasError