def test_other_html_renderer(self): def body_renderer(body): return body.upper() def page_renderer(body, pages, page): return page.body.upper() def pages_renderer(body, pages): return pages.get('hello').body.upper() renderers = filter(None, ( operator.methodcaller('upper'), 'string.upper' if not compat.IS_PY3 else None, body_renderer, page_renderer, pages_renderer )) for renderer in (renderers): pages = FlatPages(Flask(__name__)) pages.app.config['FLATPAGES_HTML_RENDERER'] = renderer hello = pages.get('hello') self.assertEqual(hello.body, u'Hello, *世界*!\n') # Upper-case, markdown not interpreted self.assertEqual(hello.html, u'HELLO, *世界*!\n')
def test_basic(self): pages = FlatPages(Flask(__name__)) hello = pages.get('headerid') self.assertEqual( hello.html, u'<h1>Page Header</h1>\n<h2>Paragraph Header</h2>\n<p>Text</p>') pages.app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [] pages.reload() pages._file_cache = {} hello = pages.get('headerid') self.assertEqual( hello.html, u'<h1>Page Header</h1>\n<h2>Paragraph Header</h2>\n<p>Text</p>') pages.app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [ 'codehilite', 'headerid' ] pages.reload() pages._file_cache = {} hello = pages.get('headerid') self.assertEqual( hello.html, '<h1 id="page-header">Page Header</h1>\n' '<h2 id="paragraph-header">Paragraph Header</h2>\n' '<p>Text</p>')
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) pages = FlatPages(app) freezer = Freezer(app) jsglue = JSGlue(app) bootstrap.init_app(app) from app.core import bp as core_bp app.register_blueprint(core_bp) if not app.debug: if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/endless_farming.log', maxBytes=10240, backupCount=10) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Endless farming startup') return app, freezer, pages
def test_other_html_renderer(self): for renderer in (unicode.upper, 'string.upper'): pages = FlatPages(Flask(__name__)) pages.app.config['FLATPAGES_HTML_RENDERER'] = renderer hello = pages.get('hello') self.assertEquals(hello.body, u'Hello, *世界*!\n') # Upper-case, markdown not interpreted self.assertEquals(hello.html, u'HELLO, *世界*!\n')
def test_other_extension(self): app = Flask(__name__) app.config['FLATPAGES_EXTENSION'] = '.txt' pages = FlatPages(app) self.assertEqual( set(page.path for page in pages), set(['not_a_page', 'foo/42/not_a_page']) )
def create_app(config_name): app = Flask(__name__) app.config.from_pyfile('config.py') global flatpages flatpages = FlatPages(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def test_iter(self): pages = FlatPages(Flask(__name__)) self.assertEqual( set(page.path for page in pages), set([ 'codehilite', 'extra', 'foo', 'foo/bar', 'foo/lorem/ipsum', 'headerid', 'hello', 'toc' ]))
def create_app(config): def _initialize(app): """Load the external website settings and assets configurations into current application :param app: :return: """ if app.initialized: return app cwd = app.path config_file = path.join(cwd, '_config.yml') asset_file = path.join(cwd, "_assets.yml") if path.exists(config_file): settings = yaml.load(open(config_file).read()) app.site = Site(**settings) app.config['BABEL_DEFAULT_LOCALE'] = getattr( app.site, 'lang', 'en') else: raise IOError( 'System initialize fail: the `_config.yml` can not be found in the root of current website.' ) path.exists(asset_file) and app.assets_env.register( YAMLLoader(asset_file).load_bundles()) app.url_map.converters['regex'] = RegexConverter app.initialized = True return app app = Flask(__name__, static_url_path='/static/vendors') app.config.from_object(config) Bootstrap(app) babel = Babel(app) app.pages = FlatPages(app) app.assets_env = Environment(app) app.path = config.APP_PATH app.init = lambda: _initialize(app) app.initialized = False app.url_map.converters['regex'] = RegexConverter @babel.localeselector def get_local(): if hasattr(g, 'lang'): _lang = getattr(g, 'lang', 'en') else: _lang = getattr(app.site, 'lang', 'en') if _lang != '': return _lang else: return 'en' return app
def register_pages(app): """Initializes and register flat pages in g.pages""" pages = FlatPages(app) def before(): """Before request event to attach g.pages""" g.pages = PagesRepository(pages) app.before_request(before)
def test_extension_sequence(self, extension=None): app = Flask(__name__) app.config['FLATPAGES_EXTENSION'] = extension or ['.html', '.txt'] pages = FlatPages(app) self.assertEqual( set(page.path for page in pages), set([ 'codehilite', 'extra', 'foo', 'foo/42/not_a_page', 'foo/bar', 'foo/lorem/ipsum', 'headerid', 'hello', 'not_a_page', 'toc' ]))
def test_instance_relative(self): with temp_directory() as temp: source = os.path.join(os.path.dirname(__file__), 'pages') dest = os.path.join(temp, 'instance', 'pages') shutil.copytree(source, dest) app = Flask(__name__, instance_path=os.path.join(temp, 'instance')) app.config['FLATPAGES_INSTANCE_RELATIVE'] = True pages = FlatPages(app) bar = pages.get('foo/bar') self.assertTrue(bar is not None)
def test_codehilite_linenums_enabled(self): app = Flask(__name__) app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['codehilite'] app.config['FLATPAGES_EXTENSION_CONFIGS'] = { 'codehilite': { 'linenums': 'True' } } pages = FlatPages(app) self.check_codehilite_with_linenums(pages)
def test_extra(self): app = Flask(__name__) app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['extra'] pages = FlatPages(app) extra_sep = '\n' if sys.version_info[:2] > (2, 6) else '\n\n' extra = pages.get('extra') self.assertEqual( extra.html, '<p>This is <em>true</em> markdown text.</p>\n' '<div>{0}' '<p>This is <em>true</em> markdown text.</p>\n' '</div>'.format(extra_sep))
def test_codehilite_linenums_disabled(self): app = Flask(__name__) app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [ 'codehilite(linenums=False)' ] pages = FlatPages(app) codehilite = pages.get('codehilite') self.assertEqual( codehilite.html, '<div class="codehilite"><pre><span class="k">print</span>' '<span class="p">(</span><span class="s">'Hello, world!'' '</span><span class="p">)</span>\n</pre></div>')
def test_yaml_meta(self): pages = FlatPages(Flask(__name__)) foo = pages.get('foo') self.assertEquals( foo.meta, { 'title': 'Foo > bar', 'created': datetime.date(2010, 12, 11), 'versions': [3.14, 42] }) self.assertEquals(foo['title'], 'Foo > bar') self.assertEquals(foo['created'], datetime.date(2010, 12, 11)) self.assertEquals(foo['versions'], [3.14, 42]) self.assertRaises(KeyError, lambda: foo['nonexistent'])
def test_extension_object(self): app = Flask(__name__) from markdown.extensions.codehilite import CodeHiliteExtension codehilite = CodeHiliteExtension() app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [codehilite] pages = FlatPages(app) self.check_default_codehilite_page(pages) codehilite = CodeHiliteExtension( linenums='True') #Check config applies app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [codehilite] pages.reload() pages._file_cache = {} self.check_codehilite_with_linenums(pages)
def test_codehilite_linenums_disabled(self): #Test explicity disabled app = Flask(__name__) app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['codehilite'] pages = FlatPages(app) self.check_default_codehilite_page(pages) #Test explicity disabled pages.app.config['FLATPAGES_EXTENSION_CONFIGS'] = { 'codehilite': { 'linenums': 'False' } } pages.reload() pages._file_cache = {} self.check_default_codehilite_page(pages)
def test_extension_importpath(self): app = Flask(__name__) app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [ 'markdown.extensions.codehilite:CodeHiliteExtension' ] pages = FlatPages(app) self.check_default_codehilite_page(pages) app.config['FLATPAGES_EXTENSION_CONFIGS'] = { #Markdown 3 style config 'markdown.extensions.codehilite:CodeHiliteExtension': { 'linenums': True } } pages.reload() pages._file_cache = {} self.check_codehilite_with_linenums(pages)
def test_headerid_with_toc(self): app = Flask(__name__) pages = FlatPages(app) pages.app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [ 'codehilite', 'toc' #headerid is deprecated in Markdown 3.0 ] pages.reload() pages._file_cache = {} hello = pages.get('headerid') self.assertEqual( hello.html, '<h1 id="page-header">Page Header</h1>\n' '<h2 id="paragraph-header">Paragraph Header</h2>\n' '<p>Text</p>') self.check_default_codehilite_page(pages) #test codehilite also loaded
def temp_pages(app=None): """This context manager gives a FlatPages object configured in a temporary directory with a copy of the test pages. Using a temporary copy allows us to safely write and remove stuff without worrying about undoing our changes. """ with temp_directory() as temp: source = os.path.join(os.path.dirname(__file__), 'pages') # Remove the destination dir as copytree wants it not to exist. # Doing so kind of defeats the purpose of tempfile as it introduces # a race condition, but should be good enough for our purpose. os.rmdir(temp) shutil.copytree(source, temp) app = app or Flask(__name__) app.config['FLATPAGES_ROOT'] = temp yield FlatPages(app)
def __init__(self): ### make temporary directory to store frozen build temp_dir = tempfile.mkdtemp() app = Flask(__name__) flatpages = FlatPages(app) app.config['FLATPAGES_EXTENSION'] = '.md' app.config['FLATPAGES_ROOT'] = 'cover-letters' app.config['FREEZER_DESTINATION'] = temp_dir freezer = Freezer(app) ### initialize the sqlite database DB = database() self.DB = DB self.app = app self.flatpages = flatpages self.freezer = freezer self.temp_dir = temp_dir
def test_mixed_extension_types(self): app = Flask(__name__) from markdown.extensions.toc import TocExtension toc = TocExtension() app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [ toc, 'codehilite', 'markdown.extensions.extra:ExtraExtension' ] pages = FlatPages(app) self.check_toc_page(pages) self.check_default_codehilite_page(pages) self.check_extra(pages) app.config['FLATPAGES_EXTENSION_CONFIGS'] = { 'codehilite': { 'linenums': 'True' } } pages.reload() pages._file_cache = {} self.check_toc_page(pages) self.check_extra(pages) self.check_codehilite_with_linenums(pages)
def create_app(config=config): app = Flask(__name__) app.config.update( DEBUG=True, FLATPAGES_AUTO_RELOAD=True, FLATPAGES_EXTENSION=".md", FLATPAGES_ROOT=config.POSTS_PATH, FREEZER_RELATIVE_URLS=True, FREEZER_DESTINATION=config.BUILD_PATH, POSTS_PER_PAGE=config.POSTS_PER_PAGE, MEDIA_PATH=config.MEDIA_PATH ) app.register_blueprint(posts_bp) raw_posts = FlatPages(app) def load_pages(): all_posts = PageCollection(raw_posts) all_posts.compute_embedded_media() g.all_posts = all_posts app.before_request(load_pages) return app
from flask import request, send_from_directory, render_template, render_template_string from werkzeug.routing import BaseConverter class RegexConverter(BaseConverter): def __init__(self, url_map, *items): super(RegexConverter, self).__init__(url_map) self.regex = items[0] app = Flask(__name__) app.config.from_pyfile('config.py') app.url_map.converters['regex'] = RegexConverter from flask_flatpages import FlatPages pages = FlatPages(app) import misaka import operator import os import houdini import datetime from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter ROOT = os.path.dirname(os.path.realpath(__file__)) STATIC_URL = app.config['STATIC_URL'] POSTS_PER_PAGE = app.config['POSTS_PER_PAGE'] FLATPAGES_EXTENSION = app.config['FLATPAGES_EXTENSION']
logging.basicConfig(level=logging.DEBUG) # specific loggers logging.getLogger('cubes').setLevel(logging.WARNING) logging.getLogger('markdown').setLevel(logging.WARNING) logging.getLogger('boto').setLevel(logging.WARNING) logging.getLogger('spendb.core.cors').setLevel(logging.WARNING) db = SQLAlchemy() babel = Babel() login_manager = LoginManager() cache = Cache() mail = Mail() migrate = Migrate() pages = FlatPages() data_manager = DataManager() cors = CORS() def create_app(**config): app = Flask(__name__) app.config.from_object(default_settings) app.config.from_envvar('SPENDB_SETTINGS', silent=True) app.config.update(config) db.init_app(app) babel.init_app(app) cache.init_app(app) mail.init_app(app)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals # unicode by default import datetime from flask import render_template, redirect, url_for from flask_flatpages import FlatPages from .app import app from .util import add_l10n_prefix, remove_l10n_prefix from .blog import authors, sorted_authors, posts, sorted_posts, get_post_url, posts_by_tag, tags, categories, historias_posts, sorted_historias_posts, historia_get_post_url, historias_posts_by_tag, historias_tags, historias_categories # Add the FlatPages extension pages = FlatPages(app, 'pages') @app.route('/<path:path>/') def page(path): ''' All pages from markdown files ''' # Get the page page = pages.get_or_404(add_l10n_prefix(path)) # Get custom template template = page.meta.get('template', 'page.html') # Verify if need redirect redirect_ = page.meta.get('redirect', None) if redirect_: return redirect(url_for('page', path=redirect_))
# Paths FREEZER_DESTINATION = config.get('serve-and-build', 'paths', 'build-destination') ASSETS_LOCATION = config.get('serve-and-build', 'paths', 'assets') POST_ASSETS_LOCATION = config.get('serve-and-build', 'paths', 'post-assets') # Site specific SITE = config.get('site') REDIRECTS = config.get('redirects') HOME_TILES = config.get('home-tiles') # App instances app = Flask(__name__) app.config.from_object(__name__) posts = FlatPages(app) freezer = Freezer(app) # Helpers def get_posts(hidden=False, force_post=None): """ Get all posts in order of date. Posts can be hidden. """ all_posts = [ p for p in posts if hidden or 'hidden' not in p.meta or force_post == p.path ] all_posts.sort(key=lambda x: x.meta['date'], reverse=True) return all_posts
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals # unicode by default import datetime import unicodedata from collections import defaultdict from flask import render_template, redirect, url_for from flask_flatpages import FlatPages from .app import app from .util import add_l10n_prefix, remove_l10n_prefix posts = FlatPages(app, 'blog') authors = FlatPages(app, 'authors') def get_post_url(post): path = remove_l10n_prefix(post.path) date = post.meta['date'] name = path[9:] return '/blog/{}/{}/{}/{}/'.format(date.year, date.month, date.day, name) def get_post_date(post): path = remove_l10n_prefix(post.path) year = int(path[0:4]) month = int(path[4:6]) day = int(path[6:8]) return datetime.date(year, month, day)
def test_unicode(self): pages = FlatPages(Flask(__name__)) self.assert_unicode(pages)
def test_other_encoding(self): app = Flask(__name__) app.config['FLATPAGES_ENCODING'] = 'shift_jis' app.config['FLATPAGES_ROOT'] = 'pages_shift_jis' pages = FlatPages(app) self.assert_unicode(pages)