



Flask-FlatPages 0.7.2 documentation

### Navigation

* [Flask-FlatPages 0.7.2 documentation](index.html#document-index) »

**Warning:** This is the development version. The latest stable version is [Version v0.7.2](index.html#document-index/../v0.7.2/index.html#document-index).

Flask-FlatPages[¶](#flask-flatpages "Permalink to this headline")

=================================================================

Flask-FlatPages provides a collection of pages to your [Flask](http://flask.pocoo.org/) application.

Pages are built from “flat” text files as opposed to a relational database.

* Works on Python 2.7 and 3.4+

* BSD licensed

* Latest documentation [on Read the Docs](http://flask-flatpages.readthedocs.org/)

* Source, issues and pull requests [on Github](https://github.com/SimonSapin/Flask-FlatPages/)

* Releases [on PyPI](http://pypi.python.org/pypi/Flask-FlatPages)

Installation[¶](#installation "Permalink to this headline")

-----------------------------------------------------------

Install the extension with [pip](http://pip.pypa.org/):

```

$ pip install Flask-FlatPages

```

or you can get the [source code from github](https://github.com/SimonSapin/Flask-FlatPages).

Configuration[¶](#configuration "Permalink to this headline")

-------------------------------------------------------------

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()`](#flask_flatpages.FlatPages.init_app "flask_flatpages.FlatPages.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\_ROOT`

Path to the directory where to look for page files. If relative,

interpreted as relative to the application root, next to the `static` and

`templates` directories. Defaults to `pages`.

`FLATPAGES\_INSTANCE\_RELATIVE`

New in version 0.7.

If True, Flask-Flatpages will interpret the root as relative to the

application’s

[instance folder](http://flask.pocoo.org/docs/1.0/config/#instance-folders).

Defaults to False.

`FLATPAGES\_EXTENSION`

Filename extension for pages. Files in the `FLATPAGES\_ROOT` directory

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\_CASE\_INSENSITIVE`

New in version 0.7.

If True, the path property of each `Page` instance will be all

lower case. Flask-Flatpages will throw a ValueError if multiple pages

would correspond to the same path.

`FLATPAGES\_ENCODING`

Encoding of the pages files. Defaults to `utf8`.

`FLATPAGES\_HTML\_RENDERER`

Callable 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()`](#flask_flatpages.pygmented_markdown "flask_flatpages.pygmented_markdown").

Changed in version 0.5: Support for passing the [`FlatPages`](#flask_flatpages.FlatPages "flask_flatpages.FlatPages") instance as second

argument.

Changed in version 0.6: Support for passing the [`Page`](#flask_flatpages.Page "flask_flatpages.Page") instance as third argument.

Renderer functions need to have at least one argument, the unicode body.

The use of either `FlatPages` as second argument or

`FlatPages` and `Page` as second respective third argument

is optional, and allows for more advanced renderers.

`FLATPAGES\_MARKDOWN\_EXTENSIONS`

New in version 0.4.

List of Markdown extensions to use with default HTML renderer, given as

either ‘entrypoint’ strings or `markdown.Extension` objects. Defaults to

`['codehilite']`.

Changed in version 0.7.

Markdown 2.5 changed the syntax for passing extensions, and for configuring

extensions.

In particular, configuring an extension by passing keyword arguments along

with the import string is now deprecated. Instead, these options need to be

passed in a dict. For more information, see `FLATPAGES\_EXTENSION\_CONFIGS`.

`FLATPAGES\_EXTENSION\_CONFIGS`

New in version 0.7.

Extension config dictionary for configuring extensions passed by their import

string. For each extension, `FLATPAGES\_EXTENSION\_CONFIGS` contains a dict

of configuration settings passed as strings.

For example, to enable linenums in `codehilite`:

```

FLATPAGES\_EXTENSION\_CONFIGS = {

    'codehilite': {

        'linenums': 'True'

    }

}

```

[See the Markdown 3 documentation for more details](https://python-markdown.github.io/reference/#extension_configs)

`FLATPAGES\_AUTO\_RELOAD`

Wether to reload pages at each request. See [Laziness and caching](#laziness-and-caching)

for more details. The default is to reload in `DEBUG` mode 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[¶](#how-it-works "Permalink to this headline")

-----------------------------------------------------------

When first needed (see [Laziness and caching](#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](http://www.yaml.org/) 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](http://daringfireball.net/projects/markdown/) with [Pygments](http://pygments.org/) 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()`](#flask_flatpages.pygments_style_defs "flask_flatpages.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[¶](#using-custom-markdown-extensions "Permalink to this headline")

New in version 0.4.

By default, Flask-FlatPages renders flatpage body using [Markdown](http://daringfireball.net/projects/markdown/) with

[Pygments](http://pygments.org/) 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[¶](#using-custom-html-renderers "Permalink to this headline")

As pointed above, by default Flask-FlatPages expects that flatpage body

contains [Markdown](http://daringfireball.net/projects/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[¶](#pre-rendering-markdown-flatpages-with-jinja "Permalink to this headline")

```

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[¶](#restructuredtext-flatpages "Permalink to this headline")

Note

For rendering ReStructuredText you need to add [docutils](http://pypi.python.org/pypi/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[¶](#laziness-and-caching "Permalink to this headline")

---------------------------------------------------------------------------

[`FlatPages`](#flask_flatpages.FlatPages "flask_flatpages.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()`](#flask_flatpages.FlatPages.reload "flask_flatpages.FlatPages.reload"), or on new requests depending on the configuration.

(See `FLATPAGES\_AUTO\_RELOAD`.)

This design was decided with [Frozen-Flask](http://packages.python.org/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`](#flask_flatpages.Page "flask_flatpages.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[¶](#module-flask_flatpages "Permalink to this headline")

------------------------------------------------------------

*class* `flask_flatpages.``FlatPages`(*app=None*, *name=None*)[¶](#flask_flatpages.FlatPages "Permalink to this definition")

A collection of [`Page`](#flask_flatpages.Page "flask_flatpages.Page") objects.

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)

```

`__iter__`()[¶](#flask_flatpages.FlatPages.__iter__ "Permalink to this definition")

Iterate on all [`Page`](#flask_flatpages.Page "flask_flatpages.Page") objects.

`get`(*path*, *default=None*)[¶](#flask_flatpages.FlatPages.get "Permalink to this definition")

Return the [`Page`](#flask_flatpages.Page "flask_flatpages.Page") object at `path`.

Returns `default` if there is no such page.

`get_or_404`(*path*)[¶](#flask_flatpages.FlatPages.get_or_404 "Permalink to this definition")

Return the [`Page`](#flask_flatpages.Page "flask_flatpages.Page") object at `path`.

Raise Flask’s 404 error if there is no such page.

`init_app`(*app*)[¶](#flask_flatpages.FlatPages.init_app "Permalink to this definition")

Use to initialize an application.

Ueful for passing an app later and app factory patterns.

| Parameters: | **app** (a [`Flask`](https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask "(in Flask v1.1.x)") instance) – your application |

`reload`()[¶](#flask_flatpages.FlatPages.reload "Permalink to this definition")

Forget all pages.

All pages will be reloaded next time they’re accessed.

*class* `flask_flatpages.``Page`[¶](#flask_flatpages.Page "Permalink to this definition")

Simple class to store all necessary information about a flatpage.

Main purpose is to render the page’s content with a `html\_renderer`

function.

With the `hello.html` page 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*)[¶](#flask_flatpages.Page.__getitem__ "Permalink to this definition")

Shortcut for accessing metadata.

`page['title']` or, in a template, `{{ page.title }}` are

equivalent to `page.meta['title']`.

`__html__`()[¶](#flask_flatpages.Page.__html__ "Permalink to this definition")

Return HTML for use in Jinja templates.

In a template, `{{ page }}` is equivalent to

`{{ page.html|safe }}`.

`html`[¶](#flask_flatpages.Page.html "Permalink to this definition")

Content of the page, rendered as HTML by the configured renderer.

`html_renderer` *= None*[¶](#flask_flatpages.Page.html_renderer "Permalink to this definition")

Renderer function

`meta`[¶](#flask_flatpages.Page.meta "Permalink to this definition")

Store a dict of metadata parsed from the YAML header of the file.

`path` *= None*[¶](#flask_flatpages.Page.path "Permalink to this definition")

Path this page was obtained from, as in `pages.get(path)`

`flask_flatpages.``pygmented_markdown`(*text*, *flatpages=None*)[¶](#flask_flatpages.pygmented_markdown "Permalink to this definition")

Render Markdown text to HTML.

Uses the [CodeHilite](http://www.freewisdom.org/projects/python-markdown/CodeHilite) extension only if [Pygments](http://pygments.org/) is available. If

[Pygments](http://pygments.org/) is not available, “codehilite” is removed from list of

extensions.

If you need other extensions, set them up using the

`FLATPAGES\_MARKDOWN\_EXTENSIONS` setting, which should be a sequence

of strings or Markdown Extension objects.

Extensions specified with entrypoint strings should be configured using

`FLATPAGES\_EXTENSION\_CONFIGS`.

`flask_flatpages.``pygments_style_defs`(*style='default'*)[¶](#flask_flatpages.pygments_style_defs "Permalink to this definition")

| Returns: | the CSS definitions for the [CodeHilite](http://www.freewisdom.org/projects/python-markdown/CodeHilite) Markdown plugin. |

| Parameters: | **style** – The Pygments [style](http://pygments.org/docs/styles/) to use. |

Only available if [Pygments](http://pygments.org/) is.

Changelog[¶](#changelog "Permalink to this headline")

-----------------------------------------------------

### v0.7.3[¶](#v0-7-3 "Permalink to this headline")

Release Date: 2021-04-14

#### Prelude[¶](#prelude "Permalink to this headline")

Small release to remove support for older Python versions, and to do some housekeeping on the project repository and contributor experience.

Changes include:

> 

> * Moving CI from Travis to Github Actions

> This decision was made following Travis CIs recent change in policies

> around open source projects.

> * Moving to Github Actions gave us the ability to define slightly more

> granular workflows, which give more insight into why tests failed and put

> CI results directly in Github.

> * `Tox` as a single entrypoint for all main developer tasks, specifically

> linting, testing and building docs.

> * Updated contribution guidelines

> 

> 

> 

#### Deprecation Notes[¶](#deprecation-notes "Permalink to this headline")

* This release drops support for Python versions 3.4 and 3.5. Support for python

3.4 was dropped from Pip in July 2019, and support for 3.5 in January of this

year. According to [PyPI Stats](https://pypistats.org/packages/flask-flatpages).

these versions account for a handful of downloads a month. Version 0.7.2 has

identical funcitonality to this release and will still work for these versons.

#### Bug Fixes[¶](#bug-fixes "Permalink to this headline")

* This release resolves issue [#79](https://github.com/Flask-Flatpages/Flask-Flatpages/issues/79).

by correcting an inconsistent parameter name in the documentation.

* Building on the fix to Issue [#77](https://github.com/Flask-FlatPages/Flask-FlatPages/issues/77), we

replace the custom compact module with `six`.

### v0.7.2[¶](#v0-7-2 "Permalink to this headline")

Release Date: 2020-04-19

#### Bug Fixes[¶](#id7 "Permalink to this headline")

* 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!

([#73](https://github.com/Flask-FlatPages/Flask-FlatPages/issues/73))

#### Documentation Changes[¶](#documentation-changes "Permalink to this headline")

* Update documentation to use the latest version of the Flask template.

* Add towncrier config for auto-generating release notes

#### Other Notes[¶](#other-notes "Permalink to this headline")

* This project currently supports Python versions 2.7, and 3.4+.

Some dependencies, particularly PyYAML, do not support Python 3.4 in the most recent versions. Thus, for security reasons,

we strongly advise using Python 2.7 if no newer version of Python 3 is available.

Support for Python 3.4 will be dropped in June 2020.

### v0.7.1[¶](#v0-7-1 "Permalink to this headline")

* Small bump to dependency versions to resolve security alerts.

### v0.7.0[¶](#v0-7-0 "Permalink to this headline")

* Update to Markdown 3.0 with new extension loading syntax.

* Added FLATPAGES\_EXTENSION\_CONFIGS for configuring extensions specified by import string.

* Add support for loading pages from Flask instance folder

* Add a case insensitive loading option

### v0.6.1[¶](#v0-6-1 "Permalink to this headline")

* Update dependencies to Flask>=1.0 (as Flask 0.12.1 has known vulnerabilities).

* Pin Markdown<=3.0 as the Markdown extension API has changed.

### v0.6[¶](#v0-6 "Permalink to this headline")

Release Date: 2015-02-09

* Python 3 support.

* Allow multiple file extensions for FlatPages.

* The renderer function now optionally takes a third argument, namely

the [`Page`](#flask_flatpages.Page "flask_flatpages.Page") instance.

* It is now possible to instantiate multiple instances of [`FlatPages`](#flask_flatpages.FlatPages "flask_flatpages.FlatPages")

with different configurations. This is done by specifying an additional

parameter `name` to the initializer and adding the same name in uppercase

to the respective Flask configuration settings.

### v0.5[¶](#v0-5 "Permalink to this headline")

Release Date: 2013-04-02

* Change behavior of passing `FLATPAGES\_MARKDOWN\_EXTENSIONS` to renderer

function, now the [`FlatPages`](#flask_flatpages.FlatPages "flask_flatpages.FlatPages") instance is optionally passed as second

argument. This allows more robust renderer functions.

### v0.4[¶](#v0-4 "Permalink to this headline")

Release Date: 2013-04-01

* Add `FLATPAGES\_MARKDOWN\_EXTENSIONS` config to setup list of Markdown

extensions to use with default HTML renderer.

* Fix a bug with non-ASCII filenames.

### v0.3[¶](#v0-3 "Permalink to this headline")

Release Date: 2012-07-03

* Add [`FlatPages.init\_app()`](#flask_flatpages.FlatPages.init_app "flask_flatpages.FlatPages.init_app")

* Do not use namespace packages anymore: rename the package from

`flaskext.flatpages` to `flask\_flatpages`

* Add configuration files for testing with tox and Travis.

### v0.2[¶](#v0-2 "Permalink to this headline")

Release Date: 2011-06-02

Bugfix and cosmetic release. Tests are now installed alongside the code.

### v0.1[¶](#v0-1 "Permalink to this headline")

Release Date: 2011-02-06.

First public release.

### Navigation

* [Overview](index.html#document-index)

### Quick search

 © Copyright 2010-2015, Simon Sapin. 2013-2015, Igor Davydenko.

 Created using [Sphinx](http://sphinx-doc.org/) 1.8.5.

 

