def expand_patterns(urlpatterns):
new_patterns = []
def recursive_expand(patterns):
for p in patterns:
if getattr(p,'url_patterns',False):
recursive_expand(p.url_patterns)
else:
new_patterns.append(p)
recursive_expand(patterns)
return new_patterns
# Example usage, a Sitemap class
class StaticSitemap(Sitemap):
"""Return the static sitemap items"""
priority = 0.4
changefreq = 'yearly'
def __init__(self, patterns):
self.patterns = expand_patterns(patterns)
self._items = {}
self._initialize()
def _initialize(self):
do_not_show = ['logout','admin','login']
for p in self.patterns:
if [url for url in do_not_show if url in p.regex.pattern]:
# do not show urls with this word in them
continue
if p.regex.groups:
# do not show dynamic urls, we handle those in another Sitemap class
continue
if 'template_name' in p.default_args or 'template' in p.default_args :
# only urls with templates, because we get mtime from the file
if getattr(p,'name',False):
# only views with names so reverse() can work on them
self._items[p.name] = self._get_modification_date(p)
def _get_modification_date(self, p):
# We get the modification date from the template itself
if getattr(p,'default_args',None):
if 'template_name' in p.default_args:
template = p.default_args['template_name']
elif 'template' in p.default_args:
template = p.default_args['template']
template_path = self._get_template_path(template)
mtime = os.stat(template_path).st_mtime
return datetime.datetime.fromtimestamp(mtime)
def _get_template_path(self, template_path):
for template_dir in settings.TEMPLATE_DIRS:
path = os.path.join(template_dir, template_path)
if os.path.exists(path):
return path
return None
def items(self):
return self._items.keys()
def changefreq(self, obj):
return 'monthly' #Todo unhardcode this, somehow
def lastmod(self, obj):
return self._items[obj]
def location(self, obj):
return urlresolvers.reverse(obj)
Comments