from django.db import models from django.contrib.sitemaps import Sitemap import markdown import os import yaml from django.conf import settings from django.template.loader import render_to_string from django.template import Context def markdown_processor(md): return markdown.markdown(md, ['footnotes'], safe_mode=False) ''' class Page(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() body_html = models.TextField(blank=True) body_markdown = models.TextField() meta_description = models.CharField(max_length=256, null=True, blank=True) def __unicode__(self): return self.title def get_absolute_url(self): return "/%s/" % (self.slug) def save(self): #run markdown self.body_html = markdown_processor(self.body_markdown) super(Page, self).save() ''' class PageSitemap(Sitemap): changefreq = "never" priority = 1.0 protocol = "https" def items(self): p = PageGenerator(settings.PROJ_ROOT + '_pages') return p.objects(include_in_sitemap=True) #return Page.objects.all() class PageGenerator(object): def __init__(self, path, *args, **kwargs): self._objects = [] for (dirpath, dirnames, filenames) in os.walk(path): self.dirpath = dirpath self.file_list = filter(lambda item: not (item.startswith('.') or item.endswith('~') or item.endswith('.md')), filenames) self.get_files() def get_files(self): for f in self.file_list: p = Page(self.dirpath + '/' + f) self._objects.append(p) def objects(self, *args, **kwargs): filtered_list = [] if kwargs: for item in self._objects: found = False for k, v in kwargs.items(): if getattr(item, k) == v and not found: found = True filtered_list.append(item) elif getattr(item, k) != v and found: filtered_list.remove(item) return filtered_list return self._objects def write_files(self): for obj in self.objects(): c = Context({'object': obj, 'SITE_URL': settings.SITE_URL}) t = render_to_string(["details/%s.html" % obj.template], c) s = render_to_string('details/page.txt', c) _FileWriter('', t, ext="html", filename=obj.slug) _FileWriter('', s, ext="txt", filename=obj.slug) class _FileWriter(object): """ Given a path and text object; write the page to disc """ def __init__(self, path, text_object, ext='html', filename='index'): self.path = '%s%s' % (settings.FLATFILES_ROOT, path) if not os.path.isdir(self.path): os.makedirs(self.path) fpath = '%s%s.%s' % (self.path, filename, ext) self.write(fpath, text_object) def write(self, fpath, text_object): file = open(fpath, 'wb') file.write(text_object.encode('utf-8')) file.close() class _FileLoader(object): def __init__(self, filename, *args, **kwargs): self.filename = filename metadata = self.read() for k, v in metadata.items(): setattr(self, k, v) if self.body_markdown: self.body_html = markdown.markdown(self.body_markdown, ['footnotes'], safe_mode=False) def read(self): with open(self.filename, "r", encoding="utf-8") as f: contents = f.read() metayaml, self.body_markdown = contents.split('\n---') return yaml.load(metayaml) class Page(_FileLoader): pass