fix: Add cache_html decorator to cache HTML

This commit is contained in:
Suraj Shetty 2021-05-18 15:41:23 +05:30
parent 0c575f02ea
commit c217b32fa9
3 changed files with 25 additions and 12 deletions

View file

@ -6,8 +6,8 @@ from frappe.website.page_controllers.base_template_page import BaseTemplatePage
from frappe.website.utils import get_sidebar_items
from frappe.website.render import build_response
from frappe.website.router import get_base_template
from frappe.website.utils import (extract_comment_tag,
extract_title, get_next_link, get_toc, get_frontmatter)
from frappe.website.utils import (extract_comment_tag, extract_title,
get_next_link, get_toc, get_frontmatter, cache_html)
WEBPAGE_PY_MODULE_PROPERTIES = ("base_template_path", "template", "no_cache", "sitemap", "condition_field")
@ -45,6 +45,7 @@ class TemplatePage(BaseTemplatePage):
def render(self):
return build_response(self.path, self.get_html(), self.http_status_code, self.headers)
@cache_html
def get_html(self):
# context object should be separate from self for security
# because it will be accessed via the user defined template

View file

@ -4,22 +4,12 @@ from frappe.website.page_controllers.not_permitted_page import NotPermittedPage
from frappe.website.page_controllers.redirect_page import RedirectPage
from frappe.website.path_resolver import PathResolver
#from frappe.website.utils import can_cache
def get_response(path=None, http_status_code=200):
"""Resolves path and renders page"""
response = None
path = path or frappe.local.request.path
endpoint = path
# if can_cache():
# # return rendered page
# page_cache = frappe.cache().hget("website_page", path)
# if page_cache and frappe.local.lang in page_cache:
# out = page_cache[frappe.local.lang]
# if out:
# frappe.local.response.from_cache = True
# return out
try:
path_resolver = PathResolver(path, http_status_code)

View file

@ -7,6 +7,7 @@ import functools
import json
import os
import re
from functools import wraps
import yaml
from past.builtins import cmp
@ -526,3 +527,24 @@ def get_sidebar_json_path(path, look_for=False):
return get_sidebar_json_path(os.path.split(path)[0], look_for)
else:
return ''
def cache_html(func):
@wraps(func)
def cache_html_decorator(*args, **kwargs):
if can_cache():
html = None
page_cache = frappe.cache().hget("website_page", args[0].path)
if page_cache and frappe.local.lang in page_cache:
html = page_cache[frappe.local.lang]
if html:
frappe.local.response.from_cache = True
return html
html = func(*args, **kwargs)
if can_cache():
page_cache = frappe.cache().hget("website_page", args[0].path) or {}
page_cache[frappe.local.lang] = html
frappe.cache().hset("website_page", args[0].path, page_cache)
return html
return cache_html_decorator