生成并使用静态页面
import os from django.shortcuts import render from django.template.loader import render_to_string def my_view(request): context = {'some_key': 'some_value'} static_html = '/path/to/static.html' if not os.path.exists(static_html): content = render_to_string('template.html', context, request) with open(static_html, 'w') as static_file: static_file.write(content) return render(request, static_html)
查看render代码发现,依然是执行了render_to_string读模板
def render(request, template_name, context=None, content_type=None, status=None, using=None): content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status)
因此此可进一步优化为直接返回HttpResponse
import os from django.http import HttpResponse from django.shortcuts import render from django.template.loader import render_to_string def my_view(request): static_html = '/path/to/static.html' if os.path.exists(static_html): return render(request, static_html) else: context = {'some_key': 'some_value'} content = render_to_string('template.html', context, request) with open(static_html, 'w') as static_file: static_file.write(content) return HttpResponse(content)
使用Django Cache
但是一般情况下动态内容都不需要生成静态页面,频繁读写硬提升有限,因为Django 有更快的缓存功能
详细配置看官方文档
https://docs.djangoproject.com/zh-hans/3.2/topics/cache/#the-per-view-cache
settings
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', # 使用本地内存作为缓存 'LOCATION': 'unique-snowflake', 'TIMEOUT': 3600, # 过期时间,None永不过期 } }
视图缓存
from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): return render(request, 'index.html')
URL缓存
from django.views.decorators.cache import cache_page urlpatterns = [ path('foo/<int:code>/', cache_page(60 * 15)(my_view)), ]
以上都可以自定义过期时间,但都有一个缺点,不能主动灵活删除。
底层缓存 API
def index(request): response = cache.get('index') if response is not None: return response context = {'some_key': 'some_value'} response = render(request, 'index.html', context) cache.set('index', response, 60*60) return response # 主动删除缓存 def delete_index(): cache.delete('index')
标签:缓存,render,cache,request,Django,content,html,static,页面 From: https://www.cnblogs.com/viete/p/16851842.html