Django的cache_page()函数是用于缓存页面的高阶装饰器。它可以将网站页面的响应内容在服务器端缓存一段时间,在缓存时间内如果有相同的请求,则直接返回缓存的响应内容,减少了数据库等后端服务的响应请求,提高网站的访问速度和性能。
cache_page()函数的使用方法如下:
- 在views.py文件中引入cache_page函数:
from django.views.decorators.cache import cache_page
- 在需要缓存的视图函数上面添加装饰器@cache_page(缓存时间),如:
@cache_page(60 * 15) # 缓存15分钟
def my_view(request):
# ...
- 缓存时间的单位为秒,可以设置为一个整数或是一个带单位的时间字符串,如’10s’、’5m’等等,缓存时间必须是大于0的整数。
下面提供两个使用实例:
例1:缓存网站页面
我们可以在项目的views.py文件中编写视图函数,如下:
from django.views.decorators.cache import cache_page
from django.shortcuts import render
# 缓存10分钟
@cache_page(60 * 10)
def home(request):
latest_articles = Article.objects.order_by('-pub_date')[:5]
context = {'latest_articles': latest_articles}
return render(request, 'home.html', context)
这个视图函数将会缓存首页的响应内容,缓存时间为10分钟。如果有相同的请求,则直接从缓存中获取响应内容。
例2:缓存API响应
有时候我们还需要缓存API响应。比如,我们需要通过API接口获取某个商品的信息,然后将结果返回给客户端。如果这个结果比较稳定,我们可以缓存它,让后续的请求直接从缓存中获取数据,从而提高API的访问速度和性能。
在Django中,我们可以使用cache_page()函数来缓存API响应。具体实现方法如下:
from django.views.decorators.cache import cache_page
from rest_framework.views import APIView
from rest_framework.response import Response
#缓存10分钟
CACHE_TTL = 600
class ProductView(APIView):
# API响应缓存
@cache_page(CACHE_TTL)
def get(self, request, pk):
product = Product.objects.get(pk=pk)
serializer = ProductSerializer(product)
return Response(serializer.data)
这个例子中的ProductView是一个API接口,GET请求获取某个商品的信息。我们使用cache_page()函数来缓存这个API响应,缓存时间为10分钟。
以上是关于Django的cache_page()函数使用方法的介绍,希望对你有所帮助。