diff --git a/mixins/templatemixin.py b/mixins/templatemixin.py index 11f2131..6c8538e 100644 --- a/mixins/templatemixin.py +++ b/mixins/templatemixin.py @@ -3,6 +3,7 @@ import os import codecs import copy +import markdown from dateutil import parser @@ -41,23 +42,42 @@ class TemplateMixin(object): def read_content_file(self, path): content_file = codecs.open(path, 'r', 'utf-8') + meta = self.read_content_file_metadata(content_file) + result = {} + try: + result['title'] = meta['title'] + result['creation_time'] = parser.parse(meta['creation_time'].decode('ascii')) + result['edit_time'] = parser.parse(meta['edit_time'].decode('ascii')) - first_line = content_file.readline() - second_line = content_file.readline() - - third_line = content_file.readline().strip() - while third_line == '': - third_line = content_file.readline().strip() - - result['title'] = third_line - - result['content'] = content_file.read().decode('utf-8') - - result['creation_time'] = parser.parse(first_line) - result['edit_time'] = parser.parse(second_line) + result['content'] = content_file.read() + except KeyError as error: + raise RuntimeError("Incomplete metadata, missing %s in file: %s" % (error, path)) content_file.close() - return result + + + def read_content_file_metadata(self, content_file): + # Abuse the markdown meta data extension + # https://pythonhosted.org/Markdown/extensions/meta_data.html + # It can't be used on the full file since our content can be something else than markdown. + + markdown_converter = markdown.Markdown(extensions = ['markdown.extensions.meta']) + + lines = "" + line = content_file.readline() + while line.strip() != '': + lines += line + line = content_file.readline() + lines += "\n" + + markdown_converter.convert(lines) + + meta = markdown_converter.Meta + for key in meta.keys(): + if len(meta[key]) == 1: + meta[key] = meta[key][0] + + return meta