| 1 |
"""Flatpages extension.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
import os |
| 5 |
import warnings |
| 6 |
from collections.abc import Iterator |
| 7 |
from functools import cached_property |
| 8 |
from inspect import getfullargspec |
| 9 |
|
| 10 |
from flask import abort, current_app, Flask |
| 11 |
from werkzeug.utils import import_string |
| 12 |
|
| 13 |
from .page import Page |
| 14 |
from .parsers import legacy_parser, libyaml_parser |
| 15 |
from .utils import ( |
| 16 |
WrappedRenderer, |
| 17 |
force_unicode, |
| 18 |
pygmented_markdown, |
| 19 |
) |
| 20 |
|
| 21 |
|
| 22 |
class FlatPages: |
| 23 |
"""A collection of :class:`Page` objects.""" |
| 24 |
|
| 25 |
#: Default configuration for FlatPages extension |
| 26 |
default_config = ( |
| 27 |
("root", "pages"), |
| 28 |
("extension", ".html"), |
| 29 |
("encoding", "utf-8"), |
| 30 |
("html_renderer", pygmented_markdown), |
| 31 |
("markdown_extensions", ["codehilite"]), |
| 32 |
("extension_configs", {}), |
| 33 |
("auto_reload", "if debug"), |
| 34 |
("case_insensitive", False), |
| 35 |
("instance_relative", False), |
| 36 |
("legacy_meta_parser", False), |
| 37 |
) |
| 38 |
|
| 39 |
def __init__(self, app: Flask | None = None, name: str | None = None): |
| 40 |
"""Initialize FlatPages extension. |
| 41 |
|
| 42 |
:param app: Your application. Can be omitted if you call |
| 43 |
:meth:`init_app` later. |
| 44 |
:type app: A :class:`~flask.Flask` instance |
| 45 |
:param name: The name for this FlatPages instance. Used for looking |
| 46 |
up config values using |
| 47 |
'FLATPAGES_%s_%s' % (name.upper(), key) |
| 48 |
By default, no name is used, so configuration is |
| 49 |
done by specifying config values using |
| 50 |
'FLATPAGES_%s' % (key) |
| 51 |
Typically, you only need to set this parameter if you |
| 52 |
want to use multiple :class:`FlatPages instances within the |
| 53 |
same Flask application. |
| 54 |
:type name: string |
| 55 |
|
| 56 |
.. versionchanged:: 0.6 |
| 57 |
|
| 58 |
New parameter `name` to support multiple FlatPages instances. |
| 59 |
""" |
| 60 |
self.name = name |
| 61 |
|
| 62 |
if name is None: |
| 63 |
self.config_prefix = "FLATPAGES" |
| 64 |
else: |
| 65 |
self.config_prefix = "_".join(("FLATPAGES", name.upper())) |
| 66 |
|
| 67 |
#: dict of filename: (page object, mtime when loaded) |
| 68 |
self._file_cache = {} |
| 69 |
self._root = None |
| 70 |
|
| 71 |
if app: |
| 72 |
self.init_app(app) |
| 73 |
|
| 74 |
def __iter__(self) -> Iterator[Page]: |
| 75 |
"""Iterate on all :class:`Page` objects.""" |
| 76 |
return iter(self._pages.values()) |
| 77 |
|
| 78 |
def config(self, key: str): |
| 79 |
"""Read actual configuration from Flask application config. |
| 80 |
|
| 81 |
:param key: Lowercase config key from :attr:`default_config` tuple |
| 82 |
""" |
| 83 |
return current_app.config["_".join((self.config_prefix, key.upper()))] |
| 84 |
|
| 85 |
def get(self, path: str, default: Page | None = None) -> Page: |
| 86 |
""" |
| 87 |
Return the :class:`Page` object at ``path``. |
| 88 |
|
| 89 |
Returns ``default`` if there is no such page. |
| 90 |
""" |
| 91 |
# This may trigger the property. Do it outside of the try block. |
| 92 |
pages = self._pages |
| 93 |
try: |
| 94 |
return pages[path] |
| 95 |
except KeyError: |
| 96 |
return default |
| 97 |
|
| 98 |
def get_or_404(self, path: str) -> Page: |
| 99 |
""" |
| 100 |
Return the :class:`Page` object at ``path``. |
| 101 |
|
| 102 |
Raise Flask's 404 error if there is no such page. |
| 103 |
""" |
| 104 |
page = self.get(path) |
| 105 |
if not page: |
| 106 |
abort(404) |
| 107 |
return page |
| 108 |
|
| 109 |
def init_app(self, app: Flask): |
| 110 |
""" |
| 111 |
Use to initialize an application. |
| 112 |
|
| 113 |
Ueful for passing an app later and app factory patterns. |
| 114 |
|
| 115 |
:param app: your application |
| 116 |
:type app: a :class:`~flask.Flask` instance |
| 117 |
""" |
| 118 |
# Store default config to application |
| 119 |
for key, value in self.default_config: |
| 120 |
config_key = "_".join((self.config_prefix, key.upper())) |
| 121 |
app.config.setdefault(config_key, value) |
| 122 |
|
| 123 |
# Register function to forget all pages if necessary |
| 124 |
app.before_request(self._conditional_auto_reset) |
| 125 |
|
| 126 |
# And finally store application to current instance and current |
| 127 |
# instance to application |
| 128 |
if "flatpages" not in app.extensions: |
| 129 |
app.extensions["flatpages"] = {} |
| 130 |
app.extensions["flatpages"][self.name] = self |
| 131 |
self._app = app |
| 132 |
|
| 133 |
@property |
| 134 |
def app(self) -> Flask: |
| 135 |
""" |
| 136 |
The Flask Application associated with this extension. |
| 137 |
|
| 138 |
Accessing the application instance this way is not advised. This |
| 139 |
property exists to ensure backwards compatability, and in future |
| 140 |
will wrap `flask.current_app`, the recommended way to access |
| 141 |
the app instance. |
| 142 |
""" |
| 143 |
warnings.warn( |
| 144 |
"Flask recommends accessing the app instance via " |
| 145 |
"`flask.current_app`. In future releases, this will wrap " |
| 146 |
"current_app, and raise a RuntimeError if there is no " |
| 147 |
"application context present.", |
| 148 |
DeprecationWarning, |
| 149 |
) |
| 150 |
return self._app |
| 151 |
|
| 152 |
@app.setter |
| 153 |
def app(self, app_instance: Flask): |
| 154 |
warnings.warn( |
| 155 |
"This attribute should be managed by self.init_app instead. " |
| 156 |
"This will raise an AttributeError from version 1.0 onwards.", |
| 157 |
DeprecationWarning, |
| 158 |
) |
| 159 |
self._app = app_instance |
| 160 |
|
| 161 |
def reload(self): |
| 162 |
"""Forget all pages. |
| 163 |
|
| 164 |
All pages will be reloaded next time they're accessed. |
| 165 |
""" |
| 166 |
try: |
| 167 |
# This will "unshadow" the cached_property. |
| 168 |
# The property will be re-executed on next access. |
| 169 |
del self.__dict__["_pages"] |
| 170 |
except KeyError: |
| 171 |
pass |
| 172 |
|
| 173 |
@property |
| 174 |
def root(self) -> str: |
| 175 |
"""Full path to the directory where pages are looked for. |
| 176 |
|
| 177 |
This corresponds to the `FLATPAGES_%(name)s_ROOT` config value, |
| 178 |
interpreted as relative to the app's root directory, or as relative |
| 179 |
to the app's instance folder if `FLATPAGES_%(name)s_INSTANCE_RELATIVE` |
| 180 |
is set to `True`. |
| 181 |
|
| 182 |
""" |
| 183 |
if self.config("instance_relative"): |
| 184 |
root_dir = os.path.join( |
| 185 |
current_app.instance_path, self.config("root") |
| 186 |
) |
| 187 |
else: |
| 188 |
root_dir = os.path.join(current_app.root_path, self.config("root")) |
| 189 |
return force_unicode(root_dir) |
| 190 |
|
| 191 |
def _conditional_auto_reset(self): |
| 192 |
"""Reset if configured to do so on new requests.""" |
| 193 |
auto = self.config("auto_reload") |
| 194 |
if auto == "if debug": |
| 195 |
auto = self.app.debug |
| 196 |
if auto: |
| 197 |
self.reload() |
| 198 |
|
| 199 |
def _load_file(self, path: str, filename: str, rel_path: str): |
| 200 |
""" |
| 201 |
Load file from file system and cache it. |
| 202 |
|
| 203 |
We store the result as a tuple of :class:`Path` and the file `mtime`. |
| 204 |
""" |
| 205 |
mtime = os.path.getmtime(filename) |
| 206 |
cached = self._file_cache.get(filename) |
| 207 |
|
| 208 |
if cached and cached[1] == mtime: |
| 209 |
page = cached[0] |
| 210 |
else: |
| 211 |
encoding = self.config("encoding") |
| 212 |
|
| 213 |
with open(filename, encoding=encoding) as handler: |
| 214 |
content = handler.read() |
| 215 |
|
| 216 |
page = self._parse(content, path, rel_path) |
| 217 |
self._file_cache[filename] = (page, mtime) |
| 218 |
|
| 219 |
return page |
| 220 |
|
| 221 |
@cached_property |
| 222 |
def _pages(self) -> dict[str, Page]: |
| 223 |
""" |
| 224 |
Walk the page root directory and return a dict of pages. |
| 225 |
|
| 226 |
Returns a dictionary of pages keyed by their path. |
| 227 |
""" |
| 228 |
|
| 229 |
def _walker(): |
| 230 |
""" |
| 231 |
Walk over directory and find all possible flatpages. |
| 232 |
|
| 233 |
Returns files which end with the string or sequence given by |
| 234 |
``FLATPAGES_%(name)s_EXTENSION``. |
| 235 |
""" |
| 236 |
for cur_path, _, filenames in os.walk(self.root): |
| 237 |
rel_path = cur_path.replace(self.root, "").lstrip(os.sep) |
| 238 |
path_prefix = tuple(rel_path.split(os.sep)) if rel_path else () |
| 239 |
|
| 240 |
for name in filenames: |
| 241 |
if not name.endswith(extension): |
| 242 |
continue |
| 243 |
|
| 244 |
full_name = os.path.join(cur_path, name) |
| 245 |
name_without_extension = [ |
| 246 |
name[: -len(item)] |
| 247 |
for item in extension |
| 248 |
if name.endswith(item) |
| 249 |
][0] |
| 250 |
path = "/".join(path_prefix + (name_without_extension,)) |
| 251 |
if self.config("case_insensitive"): |
| 252 |
path = path.lower() |
| 253 |
yield (path, full_name, rel_path) |
| 254 |
|
| 255 |
# Read extension from config |
| 256 |
extension = self.config("extension") |
| 257 |
|
| 258 |
# Support for multiple extensions |
| 259 |
if isinstance(extension, str): |
| 260 |
if "," in extension: |
| 261 |
extension = tuple(extension.split(",")) |
| 262 |
else: |
| 263 |
extension = (extension,) |
| 264 |
elif isinstance(extension, (list, set)): |
| 265 |
extension = tuple(extension) |
| 266 |
|
| 267 |
# FlatPage extension should be a string or a sequence |
| 268 |
if not isinstance(extension, tuple): |
| 269 |
raise ValueError( |
| 270 |
"Invalid value for FlatPages extension. Should be a string or " |
| 271 |
"a sequence, got {0} instead: {1}".format( |
| 272 |
type(extension).__name__, extension |
| 273 |
) |
| 274 |
) |
| 275 |
pages = {} |
| 276 |
for path, full_name, rel_path in _walker(): |
| 277 |
if path in pages: |
| 278 |
raise ValueError( |
| 279 |
"Multiple pages found which correspond to the same path. " |
| 280 |
"This error can arise when using multiple extensions." |
| 281 |
) |
| 282 |
pages[path] = self._load_file(path, full_name, rel_path) |
| 283 |
return pages |
| 284 |
|
| 285 |
def _parse(self, content, path, rel_path): |
| 286 |
"""Parse a flatpage file, i.e. read and parse its meta data and body. |
| 287 |
|
| 288 |
:return: initialized :class:`Page` instance. |
| 289 |
""" |
| 290 |
if self.config("legacy_meta_parser"): |
| 291 |
meta, content = legacy_parser(content) |
| 292 |
else: |
| 293 |
meta, content = libyaml_parser(content, path) |
| 294 |
|
| 295 |
# Now we ready to get HTML renderer function |
| 296 |
html_renderer = self.config("html_renderer") |
| 297 |
|
| 298 |
# If function is not callable yet, import it |
| 299 |
if not callable(html_renderer): |
| 300 |
html_renderer = import_string(html_renderer) |
| 301 |
|
| 302 |
# Make able to pass custom arguments to renderer function |
| 303 |
html_renderer = self._smart_html_renderer(html_renderer) |
| 304 |
|
| 305 |
# Assign the relative path (to root) for use in the page object |
| 306 |
folder = rel_path |
| 307 |
|
| 308 |
# Initialize and return Page instance |
| 309 |
return Page(path, meta, content, html_renderer, folder) |
| 310 |
|
| 311 |
def _smart_html_renderer(self, html_renderer) -> WrappedRenderer[Page]: |
| 312 |
""" |
| 313 |
Wrappper to enable rendering functions with differing signatures. |
| 314 |
|
| 315 |
We stay backwards compatible by using reflection, i.e. we inspect the |
| 316 |
given rendering function's signature in order to find out how many |
| 317 |
arguments the function takes. |
| 318 |
|
| 319 |
.. versionchanged:: 0.6 |
| 320 |
|
| 321 |
Support for HTML renderer functions with signature |
| 322 |
``f(body, flatpages, page)``, where ``page`` is an instance of |
| 323 |
:class:`Page`. |
| 324 |
|
| 325 |
.. versionchanged:: 0.5 |
| 326 |
|
| 327 |
Support for HTML renderer functions with signature |
| 328 |
``f(body, flatpages)``, where ``flatpages`` is an instance of |
| 329 |
:class:`FlatPages`. |
| 330 |
|
| 331 |
""" |
| 332 |
|
| 333 |
def wrapper(page: Page) -> str: |
| 334 |
"""Wrap HTML renderer function. |
| 335 |
|
| 336 |
Pass arguments to the renderer based on the number of arguments. |
| 337 |
|
| 338 |
* 1 argument -> page body |
| 339 |
* 2 arguments -> page body, flatpages instance |
| 340 |
* 3 arguments -> page body, flatpages instance, page instance |
| 341 |
""" |
| 342 |
body = page.body |
| 343 |
|
| 344 |
try: |
| 345 |
args_length = len(getfullargspec(html_renderer).args) |
| 346 |
except TypeError: |
| 347 |
return html_renderer(body) |
| 348 |
|
| 349 |
if args_length == 1: |
| 350 |
return html_renderer(body) |
| 351 |
elif args_length == 2: |
| 352 |
return html_renderer(body, self) |
| 353 |
elif args_length == 3: |
| 354 |
return html_renderer(body, self, page) |
| 355 |
|
| 356 |
raise ValueError( |
| 357 |
"HTML renderer function {0!r} not supported by " |
| 358 |
"Flask-FlatPages, wrong number of arguments: {1}.".format( |
| 359 |
html_renderer, args_length |
| 360 |
) |
| 361 |
) |
| 362 |
|
| 363 |
return wrapper |