django-rest-framework - 缓存外部 API 调用 - Django
问题描述
import requests
URL = "http://www.test.com/products"
r = requests.get(url = URL)
data = r.json()
我想将此任务集成到 Django REST 应用程序中,并希望将其作为单独的服务调用,并且我想确保在每次页面加载时都不应调用此外部 API,我们如何实现这一点?
只需在我的视图中使用 django 本地内存缓存 settings.py 和缓存装饰器就可以解决这个问题?,我只需要想法,这是更好的方法。
解决方案
使用 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'})
推荐阅读
- angular - Http 请求仅在发布 Android 构建 APK 时失败,但在调试时有效
- python - 检查输入时出错:预期 embedding_1_input 有 2 维,但得到了形状为 () 的数组
- html - 我遇到了悬停效果的问题
- java - Java - 如何将 URL 转换为 Files.lines() 的 PATH
- docker - 从 ssh 退出时,在分离的 docker 容器中运行的命令是否继续运行?
- html - 如何将这些 CSS 网格单元扩展到它们的内容?
- python - 对我来说最重要的问题:有没有更好的方法,如果有,你们能指出我正确的方向吗?
- python - 如何在 paramiko 连接中临时添加 host_key
- python - 如何使用 Spacy NER 模型训练全新的实体而不是预训练的实体?
- python - Azure Python SDK - 列出 VM 并生成自定义 JSON 响应