Debian Codegraph @

docs/index.rst

raw
1 Flask-FlatPages
2 ===============
3
4 Flask-FlatPages provides a collection of pages to your `Flask`_ application.
5 Pages are built from “flat” text files as opposed to a relational database.
6
7 * Works on Python 3.8+
8 * BSD licensed
9 * Latest documentation on `Read the Docs`_
10 * Source, issues and pull requests `Github`_
11 * Releases on `PyPI`_
12
13 .. _Flask: http://flask.pocoo.org/
14 .. _Read the Docs: http://flask-flatpages.readthedocs.org/
15 .. _Github: https://github.com/SimonSapin/Flask-FlatPages/
16 .. _PyPI: http://pypi.python.org/pypi/Flask-FlatPages
17
18
19 Installation
20 ------------
21
22 Install the extension with `pip <http://pip.pypa.org/>`_::
23
24 $ pip install Flask-FlatPages
25
26 or you can get the `source code from github
27 <https://github.com/SimonSapin/Flask-FlatPages>`_.
28
29 Configuration
30 -------------
31
32 To get started all you need to do is to instantiate a :class:`FlatPages` object
33 after configuring the application::
34
35 from flask import Flask
36 from flask_flatpages import FlatPages
37
38 app = Flask(__name__)
39 app.config.from_pyfile('mysettings.cfg')
40 pages = FlatPages(app)
41
42 you can also pass the Flask application object later, by calling
43 :meth:`~.FlatPages.init_app`::
44
45 pages = FlatPages()
46
47 def create_app(config='mysettings.cfg'):
48 app = Flask(__name__)
49 app.config.from_pyfile(config)
50 pages.init_app(app)
51 return app
52
53
54 Flask-FlatPages accepts the following configuration values. All of them
55 are optional.
56
57 ``FLATPAGES_ROOT``
58 Path to the directory where to look for page files. If relative,
59 interpreted as relative to the application root, next to the ``static`` and
60 ``templates`` directories. Defaults to ``pages``.
61
62 ``FLATPAGES_INSTANCE_RELATIVE``
63 .. versionadded:: 0.7
64
65 If `True`, Flask-Flatpages will interpret the root as relative to the
66 application's
67 `instance folder <http://flask.pocoo.org/docs/1.0/config/#instance-folders>`_.
68 Defaults to `False`.
69
70 ``FLATPAGES_EXTENSION``
71 Filename extension for pages. Files in the ``FLATPAGES_ROOT`` directory
72 without this suffix are ignored. Defaults to ``.html``.
73
74 .. versionchanged:: 0.6
75
76 Support multiple file extensions via sequences, e.g.:
77 ``['.htm', '.html']`` or via comma-separated strings: ``.htm,.html``.
78
79 ``FLATPAGES_CASE_INSENSITIVE``
80 .. versionadded:: 0.7
81
82 If `True`, the path property of each :class:`Page` instance will be all
83 lower case. Flask-Flatpages will throw a `ValueError` if multiple pages
84 would correspond to the same path.
85
86 ``FLATPAGES_ENCODING``
87 Encoding of the pages files. Defaults to ``utf8``.
88
89 ``FLATPAGES_HTML_RENDERER``
90 Callable or import string for a callable that takes at least the unicode
91 body of a page, and return its HTML rendering as a unicode string. Defaults
92 to :func:`~.pygmented_markdown`.
93
94 .. versionchanged:: 0.5
95
96 Support for passing the :class:`~.FlatPages` instance as second
97 argument.
98
99 .. versionchanged:: 0.6
100
101 Support for passing the :class:`~.Page` instance as third argument.
102
103 Renderer functions need to have at least one argument, the unicode body.
104 The use of either :class:`~FlatPages` as second argument or
105 :class:`~FlatPages` and :class:`Page` as second respective third argument
106 is optional, and allows for more advanced renderers.
107
108
109 ``FLATPAGES_MARKDOWN_EXTENSIONS``
110 .. versionadded:: 0.4
111
112 List of Markdown extensions to use with default HTML renderer, given as
113 either 'entrypoint' strings or ``markdown.Extension`` objects. Defaults to
114 ``['codehilite']``.
115
116 .. versionchanged:: 0.7
117
118 Markdown 2.5 changed the syntax for passing extensions, and for configuring
119 extensions.
120 In particular, configuring an extension by passing keyword arguments along
121 with the import string is now deprecated. Instead, these options need to be
122 passed in a dict. For more information, see ``FLATPAGES_EXTENSION_CONFIGS``.
123
124 ``FLATPAGES_EXTENSION_CONFIGS``
125 .. versionadded:: 0.7
126
127 Extension config dictionary for configuring extensions passed by their import
128 string. For each extension, ``FLATPAGES_EXTENSION_CONFIGS`` contains a dict
129 of configuration settings passed as strings.
130 For example, to enable linenums in ``codehilite``:
131
132 .. code-block:: python
133
134 FLATPAGES_EXTENSION_CONFIGS = {
135 'codehilite': {
136 'linenums': 'True'
137 }
138 }
139
140 `See the Markdown 3 documentation for more details <https://python-markdown.github.io/reference/#extension_configs>`_
141
142 ``FLATPAGES_AUTO_RELOAD``
143 Whether to reload pages at each request. See :ref:`laziness-and-caching`
144 for more details. The default is to reload in ``DEBUG`` mode only.
145
146 ``FLATPAGES_LEGACY_META_PARSER``
147 .. versionadded:: 0.8
148
149 Controls whether to use the newer parser based on tokenising metadata
150 with libyaml.
151
152 Setting this to true reverts to the simpler method of parsing metadata
153 used in versions <0.8, which requires the metadata block be terminated
154 by a newline, or else if there's no metadata that a leading newline be
155 present. Intended to provide a fallback in case of bugs with the newer
156 parser.
157
158 Please note that multiple FlatPages instances can be configured by using a
159 name for the FlatPages instance at initializaton time:
160
161 .. code-block:: python
162
163 flatpages = FlatPages(name="blog")
164
165 To configure this instance, you must use modified configuration keys, by adding
166 the uppercase name to the configuration variable names: ``FLATPAGES_BLOG_*``
167
168 How it works
169 ------------
170
171 When first needed (see :ref:`laziness-and-caching` for more about this),
172 the extension loads all pages from the filesystem: a :class:`Page` object is
173 created for all files in ``FLATPAGES_ROOT`` whose name ends with
174 ``FLATPAGES_EXTENSION``.
175
176 Each of these objects is associated to a path:
177 the slash-separated (whatever the OS) name of the file it was loaded from,
178 relative to the pages root, and excluding the extension. For example, for
179 an app in ``C:\myapp`` with the default configuration, the path for the
180 ``C:\myapp\pages\lorem\ipsum.html`` is ``lorem/ipsum``.
181
182 Each file is made of a `YAML`_ mapping of metadata, and the
183 page body::
184
185 title: Hello
186 published: 2010-12-22
187 ---
188 Hello, *World*!
189
190 Lorem ipsum dolor sit amet, …
191
192 The body format defaults to `Markdown`_ with `Pygments`_ baked in if available,
193 but depends on the ``FLATPAGES_HTML_RENDERER`` configuration value.
194
195 .. _YAML: http://www.yaml.org/
196 .. _Markdown: http://daringfireball.net/projects/markdown/
197 .. _Pygments: http://pygments.org/
198
199 To use Pygments, you need to include the style declarations separately.
200 You can get them with :func:`.pygments_style_defs`::
201
202 @app.route('/pygments.css')
203 def pygments_css():
204 return pygments_style_defs('tango'), 200, {'Content-Type': 'text/css'}
205
206 and in templates:
207
208 .. code-block:: html+jinja
209
210 <link rel="stylesheet" href="{{ url_for('pygments_css') }}">
211
212 .. highlight:: YAML
213
214 Delimiting YAML Metadata
215 ~~~~~~~~~~~~~~~~~~~~~~~~
216
217 .. versionadded:: 0.8
218
219 .. note::
220 The ``FLATPAGES_LEGACY_META_PARSER`` flag can be used to re-enable
221 the legacy metadata behaviour.
222
223 In previous versions, YAML metadata was terminated by a newline. This meant it
224 was impossible to use e.g. multi-line strings in the metadata, to import files
225 from other markdown tools like Obsidian, or worse that if
226 your page had no metadata at all it needed to start with an empty line.
227
228 Starting with v0.8, YAML can now be delimited by wrapping
229 it with ``---``::
230
231 ---
232 title: Hello World
233 author: J.L Coolman
234 ---
235 Hello, world!
236
237 Or using YAML 'end document' specifiers like::
238
239 ---
240 title: Hello Again
241 author: J.L Coolman
242 ...
243 Hello, world!
244
245 In all cases, the leading ``---`` is optional.
246
247 With this change, it's now possible to have pages with no-metadata
248 by starting them with::
249
250 ---
251 ---
252 Hello, this is my page
253
254 Or::
255
256 ---
257 ...
258 Hello, this is a page too
259
260 Or even just launching in to the body::
261
262 Hello, this is also a page!
263
264 .. warning::
265 In previous versions, metadata was terminated with a new line. The updated
266 metadata parser attempts to preserve backwards compatability as much as
267 possible, but unexpected behaviour can occur if the page starts with text
268 that looks ambiguously 'YAML-like'. For example::
269
270 hello: world
271
272 This is my blog:
273
274 We strongly advise using an explicit delimiter. In addition, if
275 your metadata features multi-line blocks, you **must** specify
276 an start and end delimiter, or else the parser may cut the metadata
277 at the first blank line.
278
279 .. highlight:: python
280
281 Using custom Markdown extensions
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283
284 .. versionadded:: 0.4
285
286 By default, Flask-FlatPages renders flatpage body using `Markdown`_ with
287 `Pygments`_ format. This means passing ``['codehilite']`` extensions list to
288 ``markdown.markdown`` function.
289
290 But sometimes you need to customize things, like using another extension or
291 disable default approach, this possible by passing special config.
292
293 For example, using another extension::
294
295 FLATPAGES_MARKDOWN_EXTENSIONS = ['codehilite', 'headerid']
296
297 Or disabling default approach::
298
299 FLATPAGES_MARKDOWN_EXTENSIONS = []
300
301 Using custom HTML renderers
302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
303
304 As pointed above, by default Flask-FlatPages expects that flatpage body
305 contains `Markdown`_ markup, so uses ``markdown.markdown`` function to render
306 its content. But due to ``FLATPAGES_HTML_RENDERER`` setting you can specify
307 different approach for rendering flatpage body.
308
309 The most common necessity of using custom HTML renderer is modifyings default
310 Markdown approach (e.g. by pre-rendering Markdown flatpages with Jinja), or
311 using different markup for rendering flatpage body (e.g. ReStructuredText).
312 Examples below introduce how to use custom renderers for those needs.
313
314 Pre-rendering Markdown flatpages with Jinja
315 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
316
317 ::
318
319 from flask import Flask, render_template_string
320 from flask_flatpages import FlatPages
321 from flask_flatpages.utils import pygmented_markdown
322
323 def my_renderer(text):
324 prerendered_body = render_template_string(text)
325 return pygmented_markdown(prerendered_body)
326 # Or, if you wish to render using the markdown extensions
327 # listed in FLATPAGES_MARKDOWN_EXTENSIONS:
328 #return pygmented_markdown(prerendered_body, flatpages=pages)
329
330 app = Flask(__name__)
331 app.config['FLATPAGES_HTML_RENDERER'] = my_renderer
332 pages = FlatPages(app)
333
334 ReStructuredText flatpages
335 ^^^^^^^^^^^^^^^^^^^^^^^^^^
336
337 .. note:: For rendering ReStructuredText you need to add `docutils
338 <http://pypi.python.org/pypi/docutils>`_ to your project requirements.
339
340 ::
341
342 from docuitls.core import publish_parts
343 from flask import Flask
344 from flask_flatpages import FlatPages
345
346 def rst_renderer(text):
347 parts = publish_parts(source=text, writer_name='html')
348 return parts['fragment']
349
350 app = Flask(__name__)
351 app.config['FLATPAGES_HTML_RENDERER'] = rst_renderer
352 pages = FlatPages(app)
353
354 .. _laziness-and-caching:
355
356 Laziness and caching
357 --------------------
358
359 :class:`.FlatPages` does not hit the filesystem until needed but when it does,
360 it reads all pages from the disk at once.
361
362 Then, pages are not loaded again unless you explicitly ask for it with
363 :meth:`.FlatPages.reload`, or on new requests depending on the configuration.
364 (See ``FLATPAGES_AUTO_RELOAD``.)
365
366 This design was decided with `Frozen-Flask`_ in mind but should work even if
367 you don’t use it: you already restart your production server on code changes,
368 you just have to do it on page content change too. This can make sense if
369 the pages are deployed alongside the code in version control.
370
371 .. _Frozen-Flask: http://packages.python.org/Frozen-Flask/
372
373 If you have many pages and loading takes a long time, you can force it at
374 initialization time so that it’s done by the time the first request is served::
375
376 pages = FlatPages(app)
377 pages.get('foo') # Force loading now. foo.html may not even exist.
378
379 Loading everything every time may seem wasteful, but the impact is mitigated
380 by caching: if a file’s modification time hasn’t changed, it is not read again
381 and the previous :class:`.Page` object is re-used.
382
383 Likewise, the YAML and Markdown parsing is both lazy and cached: not done
384 until needed, and not done again if the file did not change.
385
386 API
387 ---
388
389 .. module:: flask_flatpages
390
391 .. autoclass:: FlatPages
392 :members: init_app, get, get_or_404, __iter__, reload
393
394 Example usage::
395
396 pages = FlatPages(app)
397
398 @app.route('/')
399 def index():
400 # Articles are pages with a publication date
401 articles = (p for p in pages if 'published' in p.meta)
402 # Show the 10 most recent articles, most recent first.
403 latest = sorted(articles, reverse=True,
404 key=lambda p: p.meta['published'])
405 return render_template('articles.html', articles=latest[:10])
406
407 @app.route('/<path:path>/')
408 def page(path):
409 page = pages.get_or_404(path)
410 template = page.meta.get('template', 'flatpage.html')
411 return render_template(template, page=page)
412
413 .. autoclass:: Page()
414 :members:
415
416 With the ``hello.html`` page defined earlier
417
418 .. code-block:: YAML
419
420 # hello.html
421 title: Hello
422 published: 2010-12-22
423
424 Hello, *World*!
425
426 Lorem ipsum dolor sit amet, …
427
428 ::
429
430 >>> page = pages.get('hello')
431 >>> page.meta # PyYAML converts YYYY-MM-DD to a date object
432 {'title': 'Hello', 'published': datetime.date(2010, 12, 22)}
433 >>> page['title']
434 'Hello'
435 >>> page.body
436 'Hello, *World*!\n\nLorem ipsum dolor sit amet, \u2026'
437 >>> page.html
438 '<p>Hello, <em>World</em>!</p>\n<p>Lorem ipsum dolor sit amet, \u2026</p>'
439
440 .. automethod:: __getitem__
441 .. automethod:: __html__
442
443 .. autofunction:: pygmented_markdown
444
445 .. autofunction:: pygments_style_defs
446
447 Changelog
448 ---------
449
450 .. release-notes::
451
452 v0.7.2
453 ~~~~~~~~~~~~~
454 Release Date: 2020-04-19
455
456 Bug Fixes
457 ^^^^^^^^^
458
459 - Fixed a bug arising when the user overrides the default markdown extensions, but does not use Pygments. Apologies to anyone who didn't want codehiliting!
460 (`#73 <https://github.com/Flask-FlatPages/Flask-FlatPages/issues/73>`_)
461
462 Documentation Changes
463 ^^^^^^^^^^^^^^^^^^^^^
464
465 - Update documentation to use the latest version of the Flask template.
466
467 - Add towncrier config for auto-generating release notes
468
469
470 Other Notes
471 ^^^^^^^^^^^
472
473 - This project currently supports Python 3.8 and newer.
474
475
476 v0.7.1
477 ~~~~~~~~~~~~~
478
479 * Small bump to dependency versions to resolve security alerts.
480
481 v0.7.0
482 ~~~~~~~~~~~~~
483
484 * Update to Markdown 3.0 with new extension loading syntax.
485 * Added `FLATPAGES_EXTENSION_CONFIGS` for configuring extensions specified by import string.
486 * Add support for loading pages from Flask instance folder
487 * Add a case insensitive loading option
488
489 v0.6.1
490 ~~~~~~~~~~~~~
491
492 * Update dependencies to `Flask>=1.0` (as Flask 0.12.1 has known vulnerabilities).
493 * Pin `Markdown<=3.0` as the Markdown extension API has changed.
494
495 v0.6
496 ~~~~~~~~~~~
497
498 Release Date: 2015-02-09
499
500 * Python 3 support.
501 * Allow multiple file extensions for FlatPages.
502 * The renderer function now optionally takes a third argument, namely
503 the :class:`Page` instance.
504 * It is now possible to instantiate multiple instances of :class:`FlatPages`
505 with different configurations. This is done by specifying an additional
506 parameter ``name`` to the initializer and adding the same name in uppercase
507 to the respective Flask configuration settings.
508
509
510 v0.5
511 ~~~~~~~~~~~
512
513 Release Date: 2013-04-02
514
515 * Change behavior of passing ``FLATPAGES_MARKDOWN_EXTENSIONS`` to renderer
516 function, now the :class:`FlatPages` instance is optionally passed as second
517 argument. This allows more robust renderer functions.
518
519
520 v0.4
521 ~~~~~~~~~~~
522
523 Release Date: 2013-04-01
524
525 * Add ``FLATPAGES_MARKDOWN_EXTENSIONS`` config to setup list of Markdown
526 extensions to use with default HTML renderer.
527 * Fix a bug with non-ASCII filenames.
528
529
530 v0.3
531 ~~~~~~~~~~~
532
533 Release Date: 2012-07-03
534
535 * Add :meth:`.FlatPages.init_app`
536 * Do not use namespace packages anymore: rename the package from
537 ``flaskext.flatpages`` to ``flask_flatpages``
538 * Add configuration files for testing with tox and Travis.
539
540
541 v0.2
542 ~~~~~~~~~~~
543
544 Release Date: 2011-06-02
545
546 Bugfix and cosmetic release. Tests are now installed alongside the code.
547
548
549 v0.1
550 ~~~~~~~~~~~
551
552 Release Date: 2011-02-06.
553
554 First public release.