flask-flatpages documentation · flask-flatpages documentation, release 0.7.2 flask-flatpages...

27
Flask-FlatPages Documentation Release 0.7.2 Simon Sapin Apr 19, 2020

Upload: others

Post on 14-Jul-2020

78 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages DocumentationRelease 0.7.2

Simon Sapin

Apr 19, 2020

Page 2: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”
Page 3: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Contents

1 Installation 3

2 Configuration 5

3 How it works 73.1 Using custom Markdown extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.2 Using custom HTML renderers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4 Laziness and caching 11

5 API 13

6 Changelog 176.1 Version 0.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176.2 Version 0.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176.3 Version 0.7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176.4 Version 0.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.5 Version 0.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.6 Version 0.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.7 Version 0.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.8 Version 0.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.9 Version 0.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196.10 Version 0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Python Module Index 21

Index 23

i

Page 4: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

ii

Page 5: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

Flask-FlatPages provides a collection of pages to your Flask application. Pages are built from “flat” text files asopposed to a relational database.

• Works on Python 2.7 and 3.4+

• BSD licensed

• Latest documentation on Read the Docs

• Source, issues and pull requests on Github

• Releases on PyPI

Contents 1

Page 6: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

2 Contents

Page 7: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

CHAPTER 1

Installation

Install the extension with pip:

$ pip install Flask-FlatPages

or you can get the source code from github.

3

Page 8: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

4 Chapter 1. Installation

Page 9: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

CHAPTER 2

Configuration

To get started all you need to do is to instantiate a FlatPages object after configuring the application:

from flask import Flaskfrom 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_ROOT Path to the directory where to look for page files. If relative, interpreted as relative to theapplication 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. Defaults to False.

FLATPAGES_EXTENSION Filename extension for pages. Files in the FLATPAGES_ROOT directory without thissuffix are ignored. Defaults to .html.

Changed in version 0.6: Support multiple file extensions via sequences, e.g.: ['.htm', '.html'] or viacomma-separated strings: .htm,.html.

FLATPAGES_CASE_INSENSITIVE New in version 0.7.

5

Page 10: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

If True, the path property of each Page instance will be all lower case. Flask-Flatpages will throw a ValueErrorif 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 apage, and return its HTML rendering as a unicode string. Defaults to pygmented_markdown().

Changed in version 0.5: Support for passing the FlatPages instance as second argument.

Changed in version 0.6: Support for passing the Page instance as third argument.

Renderer functions need to have at least one argument, the unicode body. The use of either FlatPages assecond argument or FlatPages and Page as second respective third argument is optional, and allows formore 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 ormarkdown.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, config-uring an extension by passing keyword arguments along with the import string is now deprecated. Instead, theseoptions need to be passed in a dict. For more information, see FLATPAGES_EXTENSION_CONFIG.

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_CONFIG = {'codehilite': {

'linenums': 'True'}

}

See the Markdown 3 documentation for more details

FLATPAGES_AUTO_RELOAD Wether to reload pages at each request. See 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 initial-izaton time:

flatpages = FlatPages(name="blog")

To configure this instance, you must use modified configuration keys, by adding the uppercase name to the configura-tion variable names: FLATPAGES_BLOG_*

6 Chapter 2. Configuration

Page 11: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

CHAPTER 3

How it works

When first needed (see Laziness and caching for more about this), the extension loads all pages from the filesystem: aPage 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 loadedfrom, relative to the pages root, and excluding the extension. For example, for an app in C:\myapp with the defaultconfiguration, 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: Hellopublished: 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 theFLATPAGES_HTML_RENDERER configuration value.

To use Pygments, you need to include the style declarations separately. You can get them withpygments_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') }}">

3.1 Using custom Markdown extensions

New in version 0.4.

7

Page 12: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

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 possibleby passing special config.

For example, using another extension:

FLATPAGES_MARKDOWN_EXTENSIONS = ['codehilite', 'headerid']

Or disabling default approach:

FLATPAGES_MARKDOWN_EXTENSIONS = []

3.2 Using custom HTML renderers

As pointed above, by default Flask-FlatPages expects that flatpage body contains Markdown markup, so usesmarkdown.markdown function to render its content. But due to FLATPAGES_HTML_RENDERER setting youcan specify different approach for rendering flatpage body.

The most common necessity of using custom HTML renderer is modifyings default Markdown approach (e.g. bypre-rendering Markdown flatpages with Jinja), or using different markup for rendering flatpage body (e.g. ReStruc-turedText). Examples below introduce how to use custom renderers for those needs.

3.2.1 Pre-rendering Markdown flatpages with Jinja

from flask import Flask, render_template_stringfrom flask_flatpages import FlatPagesfrom 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_rendererpages = FlatPages(app)

3.2.2 ReStructuredText flatpages

Note: For rendering ReStructuredText you need to add docutils to your project requirements.

from docuitls.core import publish_partsfrom flask import Flaskfrom flask_flatpages import FlatPages

def rst_renderer(text):parts = publish_parts(source=text, writer_name='html')return parts['fragment']

(continues on next page)

8 Chapter 3. How it works

Page 13: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

(continued from previous page)

app = Flask(__name__)app.config['FLATPAGES_HTML_RENDERER'] = rst_rendererpages = FlatPages(app)

3.2. Using custom HTML renderers 9

Page 14: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

10 Chapter 3. How it works

Page 15: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

CHAPTER 4

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 requestsdepending 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 yourproduction server on code changes, you just have to do it on page content change too. This can make sense if the pagesare 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 thetime 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 timehasn’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 thefile did not change.

11

Page 16: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

12 Chapter 4. Laziness and caching

Page 17: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

CHAPTER 5

API

class flask_flatpages.FlatPages(app=None, name=None)A collection of Page objects.

Example usage:

pages = FlatPages(app)

@app.route('/')def index():

# Articles are pages with a publication datearticles = (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__()Iterate on all Page objects.

get(path, default=None)Return the Page object at path, or default if there is no such page.

get_or_404(path)Return the Page object at path, or raise Flask’s 404 error if there is no such page.

init_app(app)Use to initialize an application, useful for passing an app later and app factory patterns.

Parameters app (a Flask instance) – your application

13

Page 18: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

reload()Forget all pages.

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

class flask_flatpages.PageSimple 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.htmltitle: Hellopublished: 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.bodyu'Hello, *World*!\n\nLorem ipsum dolor sit amet, \u2026'>>> page.htmlu'<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 to page.meta['title'].

__html__()In a template, {{ page }} is equivalent to {{ page.html|safe }}.

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

html_renderer = NoneRenderer function

metaStore a dict of metadata parsed as YAML from the header of the file.

path = NonePath 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 re-moved from list of extensions.

If you need other extensions, set them up using the FLATPAGES_MARKDOWN_EXTENSIONS setting, whichshould be a sequence of strings or Markdown Extension objects. Extensions specified with entrypoint stringsshould be configured using FLATPAGES_EXTENSION_CONFIGS.

flask_flatpages.pygments_style_defs(style=’default’)

Returns the CSS definitions for the CodeHilite Markdown plugin.

14 Chapter 5. API

Page 19: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

Parameters style – The Pygments style to use.

Only available if Pygments is.

15

Page 20: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

16 Chapter 5. API

Page 21: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

CHAPTER 6

Changelog

6.1 Version 0.7.2

Released on 2020-04-19

Bug Fixes

• 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)

Documentation Changes

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

• Add towncrier config for auto-generating release notes

Other Notes

• 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, forsecurity 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.

6.2 Version 0.7.1

• Small bump to dependency versions to resolve security alerts.

6.3 Version 0.7.0

• Update to Markdown 3.0 with new extension loading syntax.

• Added FLATPAGES_EXTENSION_CONFIGS for configuring extensions specified by import string.

17

Page 22: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

• Add support for loading pages from Flask instance folder

• Add a case insensitive loading option

6.4 Version 0.6.1

• 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.

6.5 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 Page instance.

• It is now possible to instantiate multiple instances of FlatPages with different configurations. This is doneby specifying an additional parameter name to the initializer and adding the same name in uppercase to therespective Flask configuration settings.

6.6 Version 0.5

Released on 2013-04-02

• Change behavior of passing FLATPAGES_MARKDOWN_EXTENSIONS to renderer function, now theFlatPages instance is optionally passed as second argument. This allows more robust renderer functions.

6.7 Version 0.4

Released on 2013-04-01

• Add FLATPAGES_MARKDOWN_EXTENSIONS config to setup list of Markdown extensions to use with defaultHTML renderer.

• Fix a bug with non-ASCII filenames.

6.8 Version 0.3

Released on 2012-07-03

• Add FlatPages.init_app()

• Do not use namespace packages anymore: rename the package from flaskext.flatpages toflask_flatpages

• Add configuration files for testing with tox and Travis.

18 Chapter 6. Changelog

Page 23: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

6.9 Version 0.2

Released on 2011-06-02

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

6.10 Version 0.1

Released on 2011-02-06.

First public release.

6.9. Version 0.2 19

Page 24: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

20 Chapter 6. Changelog

Page 25: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Python Module Index

fflask_flatpages, 13

21

Page 26: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Flask-FlatPages Documentation, Release 0.7.2

22 Python Module Index

Page 27: Flask-FlatPages Documentation · Flask-FlatPages Documentation, Release 0.7.2 Flask-FlatPages provides a collection of pages to yourFlaskapplication. Pages are built from “flat”

Index

Symbols__getitem__() (flask_flatpages.Page method), 14__html__() (flask_flatpages.Page method), 14__iter__() (flask_flatpages.FlatPages method), 13

Fflask_flatpages (module), 13FlatPages (class in flask_flatpages), 13

Gget() (flask_flatpages.FlatPages method), 13get_or_404() (flask_flatpages.FlatPages method), 13

Hhtml (flask_flatpages.Page attribute), 14html_renderer (flask_flatpages.Page attribute), 14

Iinit_app() (flask_flatpages.FlatPages method), 13

Mmeta (flask_flatpages.Page attribute), 14

PPage (class in flask_flatpages), 14path (flask_flatpages.Page attribute), 14pygmented_markdown() (in module

flask_flatpages), 14pygments_style_defs() (in module

flask_flatpages), 14

Rreload() (flask_flatpages.FlatPages method), 13

23