首页 > 解决方案 > 缓存外部 API 调用 - Django

问题描述

import requests 
   
URL = "http://www.test.com/products"
  
r = requests.get(url = URL) 
  
data = r.json() 

我想将此任务集成到 Django REST 应用程序中,并希望将其作为单独的服务调用,并且我想确保在每次页面加载时都不应调用此外部 API,我们如何实现这一点?

只需在我的视图中使用 django 本地内存缓存 settings.py 和缓存装饰器就可以解决这个问题?,我只需要想法,这是更好的方法。

标签: django-rest-framework

解决方案


使用 method_decorator 和 cache_page 装饰器。文档

cache_page 装饰器缓存视图输出,因此不会有对第三方 API 的不必要请求。

不要忘记预先配置您的缓存系统

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.response import Response
from rest_framework import viewsets

class TestViewSet(viewsets.ViewSet):
    @method_decorator(cache_page(60*60*2))
    def list(self, request, format=None):
        return Response({'detail': 'success'})

推荐阅读