Flask-FlatPages¶
Flask-FlatPages provides a collection of pages to your Flask application. Pages are built from “flat” text files as opposed to a relational database.
Works on Python 2.6, 2.7 and 3.3+
BSD licensed
Latest documentation on Read the Docs
Source, issues and pull requests on Github
Releases on PyPI
Installation¶
Install the extension with pip:
$ pip install Flask-FlatPages
or you can get the source code from github.
Configuration¶
To get started all you need to do is to instantiate a FlatPages object
after configuring the application:
from flask import Flask
from flask_flatpages import FlatPages
app = Flask(__name__)
app.config.from_pyfile('mysettings.cfg')
pages = FlatPages(app)
you can also pass the Flask application object later, by calling
init_app():
pages = FlatPages()
def create_app(config='mysettings.cfg'):
app = Flask(__name__)
app.config.from_pyfile(config)
pages.init_app(app)
return app
Flask-FlatPages accepts the following configuration values. All of them are optional.
FLATPAGES_ROOTPath to the directory where to look for page files. If relative, interpreted as relative to the application root, next to the
staticandtemplatesdirectories. Defaults topages.FLATPAGES_EXTENSIONFilename extension for pages. Files in the
FLATPAGES_ROOTdirectory without this suffix are ignored. Defaults to.html.Changed in version 0.6: Support multiple file extensions via sequences, e.g.:
['.htm', '.html']or via comma-separated strings:.htm,.html.FLATPAGES_ENCODINGEncoding of the pages files. Defaults to
utf8.FLATPAGES_HTML_RENDERERCallable or import string for a callable that takes at least the unicode body of a page, and return its HTML rendering as a unicode string. Defaults to
pygmented_markdown().Changed in version 0.5: Support for passing the
FlatPagesinstance as second argument.Changed in version 0.6: Support for passing the
Pageinstance as third argument.Renderer functions need to have at least one argument, the unicode body. The use of either
FlatPagesas second argument orFlatPagesandPageas second respective third argument is optional, and allows for more advanced renderers.FLATPAGES_MARKDOWN_EXTENSIONSNew in version 0.4.
List of Markdown extensions to use with default HTML renderer. Defaults to
['codehilite'].For passing additional arguments to Markdown extension, e.g. in case of using footnotes extension, use next syntax:
['footnotes(UNIQUE_IDS=True)'].To disable line numbers in CodeHilite extension, which are enabled by default, use:
['codehilite(linenums=False)']FLATPAGES_AUTO_RELOADWether to reload pages at each request. See Laziness and caching for more details. The default is to reload in
DEBUGmode only.
Please note that multiple FlatPages instances can be configured by using a name for the FlatPages instance at initializaton time:
flatpages = FlatPages(name="blog")
To configure this instance, you must use modified configuration keys, by adding
the uppercase name to the configuration variable names: FLATPAGES_BLOG_*
How it works¶
When first needed (see Laziness and caching for more about this),
the extension loads all pages from the filesystem: a Page object is
created for all files in FLATPAGES_ROOT whose name ends with
FLATPAGES_EXTENSION.
Each of these objects is associated to a path:
the slash-separated (whatever the OS) name of the file it was loaded from,
relative to the pages root, and excluding the extension. For example, for
an app in C:\myapp with the default configuration, the path for the
C:\myapp\pages\lorem\ipsum.html is lorem/ipsum.
Each file is made of a YAML mapping of metadata, a blank line, and the page body:
title: Hello
published: 2010-12-22
Hello, *World*!
Lorem ipsum dolor sit amet, …
The body format defaults to Markdown with Pygments baked in if available,
but depends on the FLATPAGES_HTML_RENDERER configuration value.
To use Pygments, you need to include the style declarations separately.
You can get them with pygments_style_defs():
@app.route('/pygments.css')
def pygments_css():
return pygments_style_defs('tango'), 200, {'Content-Type': 'text/css'}
and in templates:
<link rel="stylesheet" href="{{ url_for('pygments_css') }}">
Using custom Markdown extensions¶
New in version 0.4.
By default, Flask-FlatPages renders flatpage body using Markdown with
Pygments format. This means passing ['codehilite'] extensions list to
markdown.markdown function.
But sometimes you need to customize things, like using another extension or disable default approach, this possible by passing special config.
For example, using another extension:
FLATPAGES_MARKDOWN_EXTENSIONS = ['codehilite', 'headerid']
Or disabling default approach:
FLATPAGES_MARKDOWN_EXTENSIONS = []
Using custom HTML renderers¶
As pointed above, by default Flask-FlatPages expects that flatpage body
contains Markdown markup, so uses markdown.markdown function to render
its content. But due to FLATPAGES_HTML_RENDERER setting you can specify
different approach for rendering flatpage body.
The most common necessity of using custom HTML renderer is modifyings default Markdown approach (e.g. by pre-rendering Markdown flatpages with Jinja), or using different markup for rendering flatpage body (e.g. ReStructuredText). Examples below introduce how to use custom renderers for those needs.
Pre-rendering Markdown flatpages with Jinja¶
from flask import Flask, render_template_string
from flask_flatpages import FlatPages
from flask_flatpages.utils import pygmented_markdown
def my_renderer(text):
prerendered_body = render_template_string(text)
return pygmented_markdown(prerendered_body)
app = Flask(__name__)
app.config['FLATPAGES_HTML_RENDERER'] = my_renderer
pages = FlatPages(app)
ReStructuredText flatpages¶
Note
For rendering ReStructuredText you need to add docutils to your project requirements.
from docuitls.core import publish_parts
from flask import Flask
from flask_flatpages import FlatPages
def rst_renderer(text):
parts = publish_parts(source=text, writer_name='html')
return parts['fragment']
app = Flask(__name__)
app.config['FLATPAGES_HTML_RENDERER'] = rst_renderer
pages = FlatPages(app)
Laziness and caching¶
FlatPages does not hit the filesystem until needed but when it does,
it reads all pages from the disk at once.
Then, pages are not loaded again unless you explicitly ask for it with
FlatPages.reload(), or on new requests depending on the configuration.
(See FLATPAGES_AUTO_RELOAD.)
This design was decided with Frozen-Flask in mind but should work even if you don’t use it: you already restart your production server on code changes, you just have to do it on page content change too. This can make sense if the pages are deployed alongside the code in version control.
If you have many pages and loading takes a long time, you can force it at initialization time so that it’s done by the time the first request is served:
pages = FlatPages(app)
pages.get('foo') # Force loading now. foo.html may not even exist.
Loading everything every time may seem wasteful, but the impact is mitigated
by caching: if a file’s modification time hasn’t changed, it is not read again
and the previous Page object is re-used.
Likewise, the YAML and Markdown parsing is both lazy and cached: not done until needed, and not done again if the file did not change.
API¶
- class flask_flatpages.FlatPages(app=None, name=None)¶
A collection of
Pageobjects.Example usage:
pages = FlatPages(app) @app.route('/') def index(): # Articles are pages with a publication date articles = (p for p in pages if 'published' in p.meta) # Show the 10 most recent articles, most recent first. latest = sorted(articles, reverse=True, key=lambda p: p.meta['published']) return render_template('articles.html', articles=latest[:10]) @app.route('/<path:path>/') def page(path): page = pages.get_or_404(path) template = page.meta.get('template', 'flatpage.html') return render_template(template, page=page)
- get_or_404(path)¶
Returns the
Pageobject atpath, or raise Flask’s 404 error if there is no such page.
- init_app(app)¶
Used to initialize an application, useful for passing an app later and app factory patterns.
- Parameters:
app (a
Flaskinstance) – your application
- reload()¶
Forget all pages.
All pages will be reloaded next time they’re accessed.
- class flask_flatpages.Page¶
Simple class to store all necessary information about a flatpage.
Main purpose is to render the page’s content with a
html_rendererfunction.With the
hello.htmlpage defined earlier:# hello.html title: Hello published: 2010-12-22 Hello, *World*! Lorem ipsum dolor sit amet, …
>>> page = pages.get('hello') >>> page.meta # PyYAML converts YYYY-MM-DD to a date object {'title': u'Hello', 'published': datetime.date(2010, 12, 22)} >>> page['title'] u'Hello' >>> page.body u'Hello, *World*!\n\nLorem ipsum dolor sit amet, \u2026' >>> page.html u'<p>Hello, <em>World</em>!</p>\n<p>Lorem ipsum dolor sit amet, \u2026</p>'
- __getitem__(name)¶
Shortcut for accessing metadata.
page['title']or, in a template,{{ page.title }}are equivalent topage.meta['title'].
- __html__()¶
In a template,
{{ page }}is equivalent to{{ page.html|safe }}.
- property html¶
The content of the page, rendered as HTML by the configured renderer.
- html_renderer¶
Renderer function
- property meta¶
A dict of metadata parsed as YAML from the header of the file.
- path¶
Path this page was obtained from, as in
pages.get(path)
- flask_flatpages.pygmented_markdown(text, flatpages=None)¶
Render Markdown text to HTML.
Uses the CodeHilite extension only if Pygments is available. If Pygments is not available, “codehilite” is removed from list of extensions.
If you need other extensions, set them up using the
FLATPAGES_MARKDOWN_EXTENSIONSsetting, which should be a sequence of strings.
- flask_flatpages.pygments_style_defs(style='default')¶
- Returns:
the CSS definitions for the CodeHilite Markdown plugin.
- Parameters:
style – The Pygments style to use.
Only available if Pygments is.
Changelog¶
Version 0.6¶
Released on 2015-02-09
Python 3 support.
Allow multiple file extensions for FlatPages.
The renderer function now optionally takes a third argument, namely the
Pageinstance.It is now possible to instantiate multiple instances of
FlatPageswith different configurations. This is done by specifying an additional parameternameto the initializer and adding the same name in uppercase to the respective Flask configuration settings.
Version 0.5¶
Released on 2013-04-02
Change behavior of passing
FLATPAGES_MARKDOWN_EXTENSIONSto renderer function, now theFlatPagesinstance is optionally passed as second argument. This allows more robust renderer functions.
Version 0.4¶
Released on 2013-04-01
Add
FLATPAGES_MARKDOWN_EXTENSIONSconfig to setup list of Markdown extensions to use with default HTML renderer.Fix a bug with non-ASCII filenames.
Version 0.3¶
Released on 2012-07-03
Do not use namespace packages anymore: rename the package from
flaskext.flatpagestoflask_flatpagesAdd configuration files for testing with tox and Travis.
Version 0.2¶
Released on 2011-06-02
Bugfix and cosmetic release. Tests are now installed alongside the code.
Version 0.1¶
Released on 2011-02-06.
First public release.