about summary refs log tree commit diff
diff options
context:
space:
mode:
authoruser <user@node5.net>2024-02-26 22:30:39 +0100
committeruser <user@node5.net>2024-02-26 22:30:39 +0100
commita855ebc794f40045a97cd9f2b5ad75e0302c7564 (patch)
treee59c5dab13c6d77c4abca5d7b415a55a36d081cf
parentac71b7ca1de2462e3101c5360842de80079449d2 (diff)
render articles
-rw-r--r--src/article_handler.py22
-rw-r--r--src/blog_node5_net.py23
2 files changed, 28 insertions, 17 deletions
diff --git a/src/article_handler.py b/src/article_handler.py
index 6ee0420..00321a7 100644
--- a/src/article_handler.py
+++ b/src/article_handler.py
@@ -5,8 +5,7 @@ import logging
 import pathlib
 import glob
 import typing
-from typing import Tuple
-
+import markdown
 import yaml
 
 
@@ -40,25 +39,33 @@ class MetaData():
     Created: {self.created}'''
 
 
+def truncate(text: str, max_length: int=50):
+    if len(text) < max_length:
+        return text
+    else:
+        return text[0:max_length - 1]
+
 @dataclasses.dataclass
 class Article(WebPage):
     title: str
-    meta_data: MetaData
+    metadata: MetaData
     web_dir: tuple
     source_path: str | os.PathLike
     source: str
+    html: str
     folder_path: typing.Union[None, str | os.PathLike] = None
 
     @property
     def pretty_print(self) -> str:
         return f'''
 Title:       {self.title}
-Meta data:   {self.meta_data.pretty_print}
+Metadata:   {self.metadata.pretty_print}
 Web dir:     {self.web_dir}
 URL:         {self.url}
 Source path: {self.source_path}
 Folder path: {self.folder_path}
-Source:      {f'{self.source[0:49]}...' if len(self.source) >= 50 else self.source}'''  # Truncate long source text
+HTML:        {truncate(self.html)}
+Source:      {truncate(self.source)}'''
 
 
 @dataclasses.dataclass
@@ -78,7 +85,7 @@ def parse_article_meta_data(source: str) -> typing.Tuple[str, MetaData]:
     if source.startswith('---'):
         meta_data_yml_end_char_index = source.find('---', 3)
         meta_data_yml = source[3:meta_data_yml_end_char_index]
-        # Strip meta data text from source, before feeding it to the markdown reader
+        # Strip metadata text from source, before feeding it to the markdown reader
         source = source[meta_data_yml_end_char_index + 3:]
         meta_data = yaml.safe_load(meta_data_yml)
 
@@ -114,7 +121,8 @@ def get_article(path: str | os.PathLike) -> Article:
 
     with open(path, 'r') as file:
         source = file.read()
-        article_args['source'], article_args['meta_data'] = parse_article_meta_data(source)
+    article_args['source'], article_args['metadata'] = parse_article_meta_data(source)
+    article_args['html'] = markdown.markdown(article_args['source'], extensions=['fenced_code', 'codehilite', 'tables'])
 
     article = Article(**article_args)
     return article
diff --git a/src/blog_node5_net.py b/src/blog_node5_net.py
index fcaf750..af26c76 100644
--- a/src/blog_node5_net.py
+++ b/src/blog_node5_net.py
@@ -6,42 +6,45 @@ import os
 import article_handler
 
 logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
-                    datefmt='%Y-%m-%d:%H:%M:%S',
-                    level=logging.DEBUG)
+                    datefmt='%Y-%m-%d:%H:%M:%S', level=logging.DEBUG)
 logger = logging.getLogger(__name__)
 
-app = flask.Flask(__name__)
-
 site_root_folder_path = 'blog.node5.net'
+app = flask.Flask(__name__, template_folder=os.path.join('..', site_root_folder_path, 'templates'),
+                  static_folder=os.path.join('..', site_root_folder_path, 'static'), static_url_path='')
 
 folders_by_url: typing.Dict[str, article_handler.Folder] = {}
 articles_by_url: typing.Dict[str, article_handler.Article] = {}
 
 
+@app.context_processor  # Always inject title to all render_templates
+def inject_title():
+    return {'title': site_root_folder_path}
+
+
 def strip_trailing_slash(path):
-    '''
-    Strip trailing slashes from path
-    '''
     stripped_path = path if not path[len(path) - 1] == '/' else path[:-1]
     return stripped_path
 
+
 def view_folder():
     path = flask.request.path
     if path is not '/':
-       path = strip_trailing_slash(flask.request.path)
+        path = strip_trailing_slash(flask.request.path)
     a = folders_by_url[path]
     return 'Folder'
 
 
 def view_article():
     path = strip_trailing_slash(flask.request.path)
-    return articles_by_url[path].pretty_print
+    article = articles_by_url[path]
+    return flask.render_template('article.html', article=article)
 
 
 def register_urls(folder: article_handler.Folder):
     # Use recursion to traverse folder tree structure
     app.add_url_rule(folder.url, view_func=view_folder)
-    folders_by_url[strip_trailing_slash(folder.url)] = folder
+    folders_by_url[strip_trailing_slash(folder.url) if folder.url != '/' else folder.url] = folder
     for article in folder.articles:
         logger.debug(f"Registering url: {article.url}, static path: {article.folder_path}")
         blueprint_args = {}