diff --git a/template.py b/template.py index 8916e80..a992c08 100644 --- a/template.py +++ b/template.py @@ -9,15 +9,21 @@ class RemoteTemplate(object): self.cache_key = simplify(urlparse.urlunparse(urlparse.urlparse(self.source)[:3] + ('', '', ''))) self.cache_dirpath = os.path.join(publisher.app_dir, 'skeleton-cache') self.cache_filepath = os.path.join(self.cache_dirpath, self.cache_key) + self.theme_skeleton_url = publisher.get_site_option('theme_skeleton_url') + self.skip_cache = (request.response.status_code != 200) def get_template_content(self): import time, os, threading + if self.skip_cache: + return self.update_content() from quixote import get_response, get_publisher CACHE_REFRESH_TIMEOUT = 300 self.response = get_response() self.static_path = get_publisher().get_application_static_files_root_url() try: - cache_filepath_mtime = os.stat(self.cache_filepath).st_mtime + cache_filepath_mtime = min(( + os.stat(self.cache_filepath).st_mtime, + os.lstat(self.cache_filepath).st_mtime)) except OSError: # missing file return self.update_content() else: @@ -28,9 +34,9 @@ class RemoteTemplate(object): def update_content(self): import requests - theme_skeleton_url = publisher.get_site_option('theme_skeleton_url') - r = requests.get(theme_skeleton_url, params={'source': self.source, 'format': 'ezt'}) + r = requests.get(self.theme_skeleton_url, params={'source': self.source, 'format': 'ezt'}) + r.raise_for_status() body = """ [if-any bigdiv]
[end] @@ -106,14 +112,25 @@ class RemoteTemplate(object): template_content = template_content.replace( '
', '
') - self.cache(template_content) + if not self.skip_cache: + self.cache(template_content, page_id=r.headers.get('X-Combo-Page-Id')) return template_content - def cache(self, template_body): + def cache(self, template_body, page_id=None): import os from qommon.storage import atomic_write if not os.path.exists(self.cache_dirpath): os.mkdir(self.cache_dirpath) - atomic_write(self.cache_filepath, template_body) + if page_id: + # if there's a page id we store the content under the page id + # filename and create a symlink from the cache key + cache_filepath = os.path.join(self.cache_dirpath, page_id) + atomic_write(cache_filepath, template_body) + # always recreate symlink to get an updated mtime + if os.path.exists(self.cache_filepath): + os.unlink(self.cache_filepath) + os.symlink(page_id, self.cache_filepath) + else: + atomic_write(self.cache_filepath, template_body) template_content = RemoteTemplate(request.get_url()).get_template_content()