首页 > 解决方案 > 如何在 django 中限制对外部 API 的调用

问题描述

我有一个显示 YouTube 频道所有帖子的应用程序。为此,我使用我在 views.py 中调用的 youtube-API v3。然后我将所有数据保存在我的数据库中,这些数据作为上下文传递给我的渲染函数:

return render(request, "blog/home.html", context)

我想知道如果最后一次 API 调用是在 5 分钟前,是否可以只调用 API,否则只使用数据库中的数据。

我的一个想法是在进行 API 调用时将当前日期时间保存到文件中,并且每当调用视图函数时,将当前日期时间与文件中的日期时间进行比较。但是,这似乎效率低下,我想知道是否有更好的方法。

标签: pythondjango

解决方案


我做了类似于你描述的事情,不确定这是否对你有帮助。对我来说,它只能每分钟再次请求

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

推荐阅读