This repository has been archived on 2024-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
build.py/_src/item.py

43 lines
1.5 KiB
Python

import frontmatter # from package python-frontmatter
import datetime
from files import read_this # from itself
from config import config # from itself
from attrdict import AttrDict # from itself
class Item(AttrDict):
"""This class represents single content file
It extracts all frontmatter fields using python-frontmatter module"""
def __init__(self, path: str, prefix: str = 'content/'):
# initialize parent
super().__init__()
self.path, self.prefix = path, prefix
# initialize common fields
self.title = None
self.tags = []
self.description = None
self.source = None
self.author = None
frontmatter_data, content = frontmatter.parse(read_this(prefix + path))
self.content = content
self.frontmatter_data = frontmatter_data
# fill undefined fields with default values from config
for field in config['defaults']:
if field not in frontmatter_data:
frontmatter_data[field] = config['defaults'][field]
# share frontmatter fields
for field in frontmatter_data:
self[field] = frontmatter_data[field]
# convert ISO datetime strings into datetime objects
if type(self[field]) == str:
try: self[field] = datetime.date.fromisoformat(self[field])
except ValueError:
try: self[field] = datetime.datetime.fromisoformat(self[field])
except ValueError: pass