Debian Codegraph @

flask_flatpages/page.py

raw
1 """Define flatpage instance."""
2
3 from __future__ import annotations
4 from functools import cached_property
5 from io import StringIO
6 from typing import Any
7
8 import yaml
9
10 from .utils import WrappedRenderer
11
12
13 class Page:
14 """Simple class to store all necessary information about a flatpage.
15
16 Main purpose is to render the page's content with a ``html_renderer``
17 function.
18 """
19
20 def __init__(
21 self,
22 path: str,
23 meta: str,
24 body: str,
25 html_renderer: WrappedRenderer["Page"],
26 folder: str,
27 ):
28 """Initialize Page instance.
29
30 :param path: Page path.
31 :param meta: Page meta data in YAML format.
32 :param body: Page body.
33 :param html_renderer: HTML renderer function.
34 :param folder: The folder the page is contained in.
35 """
36 #: Path this page was obtained from, as in ``pages.get(path)``
37 self.path = path
38 #: Content of the page
39 self._meta = meta
40 self.body = body
41 #: Renderer function
42 self.html_renderer = html_renderer
43 #: The name of the folder the page is contained in.
44 self.folder = folder
45
46 def __getitem__(self, name: str):
47 """Shortcut for accessing metadata.
48
49 ``page['title']`` or, in a template, ``{{ page.title }}`` are
50 equivalent to ``page.meta['title']``.
51 """
52 return self.meta[name]
53
54 def __html__(self) -> str:
55 """
56 Return HTML for use in Jinja templates.
57
58 In a template, ``{{ page }}`` is equivalent to
59 ``{{ page.html|safe }}``.
60 """
61 return self.html
62
63 def __repr__(self) -> str:
64 """Machine representation of :class:`Page` instance."""
65 return f"<Page {self.path}>"
66
67 @cached_property
68 def html(self) -> str:
69 """Content of the page, rendered as HTML by the configured renderer."""
70 return self.html_renderer(self)
71
72 @cached_property
73 def meta(self) -> dict[str, Any]:
74 """Store a dict of metadata parsed from the YAML header of the file."""
75 meta = {}
76 for doc in yaml.safe_load_all(StringIO(self._meta)):
77 if doc is not None:
78 meta.update(doc)
79 # YAML documents can be any type but we want a dict
80 # eg. yaml.safe_load('') -> None
81 # yaml.safe_load('- 1\n- a') -> [1, 'a']
82 if not meta:
83 return {}
84 if not isinstance(meta, dict):
85 raise ValueError(
86 "Expected a dict in metadata for '{0}', got {1}".format(
87 self.path, type(meta).__name__
88 )
89 )
90 return meta