Ejemplo n.º 1
0
    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>'
        )
Ejemplo n.º 3
0
 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')
Ejemplo n.º 4
0
 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')
Ejemplo n.º 5
0
 def test_html_conversion(self):
     pages = FlatPages(Flask(__name__))
     foo = pages.get("foo")
     print "we get here"
     print foo["description_html"]
     self.assertTrue(True)
     self.assertEquals(foo["description"].strip(), '# hello')
     self.assertEquals(foo["description_html"], '<h1>hello</h1>')
 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)
Ejemplo n.º 7
0
 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)
Ejemplo n.º 8
0
 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'])
Ejemplo n.º 9
0
    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_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)
Ejemplo n.º 11
0
 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'])
Ejemplo n.º 12
0
    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">&#39;Hello, world!&#39;'
            '</span><span class="p">)</span>\n</pre></div>')
 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):
        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">&#39;Hello, world!&#39;'
            '</span><span class="p">)</span>\n</pre></div>'
        )
    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):
     #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_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)
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
def page(path):
    page = pages.get_or_404(path)

    if request.method == "POST" and "user_id" in session:
        page_fullpath = (Path() / app.config["FLASK_APP"] /
                         app.config["FLATPAGES_ROOT"] /
                         secure_filename(page.path + ".md"))
        try:
            page_fullpath.unlink()
            FlatPages.reload(pages)
            flash(f"Blog post {page.path} has been deleted!", "Info")
            return redirect(url_for("index"))
        except OSError:
            abort(404)

    return render_template("page.j2", page=page)
Ejemplo n.º 22
0
class TestFlatPagesPandoc(unittest.TestCase):
    def setUp(self):
        self.tmp = mkdtemp()
        self.content = os.path.join(self.tmp, "content")
        os.makedirs(self.content)

        self.app = Flask(__name__)
        self.app.config.update(
            FLATPAGES_ROOT=self.content,
            FLATPAGES_ENCODING="utf-8",
            FLATPAGES_AUTO_RELOAD=True,
        )
        self.pages = FlatPages(self.app)
        FlatPagesPandoc("markdown", self.app, pre_render=False)

    def tearDown(self):
        rmtree(self.tmp)

    def get(self, body, ext=".md", enc="utf-8"):
        self.app.config.update(FLATPAGES_EXTENSION=ext)
        with open(os.path.join(self.content, "test" + ext), "w", enc) as f:
            f.write(u"title:test\n\n" + body)
        return self.pages.get("test").html

    def test_h1(self):
        self.assertEqual(self.get("# test"), '<h1 id="test">test</h1>\n')

    def test_unicode(self):
        self.assertEqual(self.get(u"萬大事都有得解決"), u"<p>萬大事都有得解決</p>\n")

    def test_unicode2(self):
        self.app.config.update(FLATPAGES_ENCODING="iso-8859-15")
        self.assertEqual(self.get(u"äöü", enc="iso-8859-15"), u"<p>äöü</p>\n")
Ejemplo n.º 23
0
 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'])
     )
Ejemplo n.º 24
0
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_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
Ejemplo n.º 26
0
 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'
         ]))
Ejemplo n.º 27
0
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
Ejemplo n.º 28
0
class CategorizedFlatPages(object):
    def __init__(self):
        self.flat_pages = FlatPages()
        self.root_category = Category(None, '<root>')

    def init_app(self, app):
        self.flat_pages.init_app(app)
        self._set_categories()

    def __iter__(self):
        return iter(sorted(self.root_category.categories.values(),
            cmp=compare))


    def get(self, category_id, article_id):
        category = self.root_category.categories.get(category_id)
        if category is None:
            return None
        return category.articles.get(article_id)

    def get_articles_of_category(self, category_id):
        barticles = []
        for a in self.root_category.categories.get(category_id).articles.values():
            if a.id != 'index':
                barticles.append(a)
        return barticles

    def get_or_404(self, category_id, article_id):
        page = self.get(category_id, article_id)
        if page is None:
            abort(404)
        return page

    def _set_categories(self):
        for page in self.flat_pages:
            components = page.path.split('/')
            parent = self.root_category
            for category_id in components[:-1]:
                parent = parent.add_category(category_id)
            page_name = components[-1]
            parent.add_article(page_name, page)

    def reload(self):
        self.flat_pages.reload()
        self._set_categories()
Ejemplo n.º 29
0
class CategorizedFlatPages(object):
    def __init__(self):
        self.flat_pages = FlatPages()
        self.root_category = Category(None, '<root>')

    def init_app(self, app):
        self.flat_pages.init_app(app)
        self._set_categories()

    def __iter__(self):
        return iter(sorted(self.root_category.categories.values(),
                           cmp=compare))

    def get(self, category_id, article_id):
        category = self.root_category.categories.get(category_id)
        if category is None:
            return None
        return category.articles.get(article_id)

    def get_articles_of_category(self, category_id):
        barticles = []
        for a in self.root_category.categories.get(
                category_id).articles.values():
            if a.id != 'index':
                barticles.append(a)
        return barticles

    def get_or_404(self, category_id, article_id):
        page = self.get(category_id, article_id)
        if page is None:
            abort(404)
        return page

    def _set_categories(self):
        for page in self.flat_pages:
            components = page.path.split('/')
            parent = self.root_category
            for category_id in components[:-1]:
                parent = parent.add_category(category_id)
            page_name = components[-1]
            parent.add_article(page_name, page)

    def reload(self):
        self.flat_pages.reload()
        self._set_categories()
Ejemplo n.º 30
0
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)
Ejemplo n.º 31
0
class TestPages(TestCase):
    def setUp(self):
        app.config['FLATPAGES_ROOT'] = 'test/test_pages'
        self.pages = FlatPages(app)

    def test_get_fenced_blocks(self):
        page = self.pages.get('test-install-python')
        code = fenced_code(page.html)
        assert_not_in('Verified on MacOSX', code)
        assert_in('brew install python3', code)
Ejemplo n.º 32
0
class TestPages(TestCase):
    def setUp(self):
        app.config["FLATPAGES_ROOT"] = "test/test_pages"
        self.pages = FlatPages(app)

    def test_get_fenced_blocks(self):
        page = self.pages.get("test-install-python")
        code = fenced_code(page.html)
        assert_not_in("Verified on MacOSX", code)
        assert_in("brew install python3", code)
Ejemplo n.º 33
0
 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_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_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)
Ejemplo n.º 36
0
    def setUp(self):
        self.tmp = mkdtemp()
        self.content = os.path.join(self.tmp, "content")
        os.makedirs(self.content)

        self.app = Flask(__name__)
        self.app.config.update(
            FLATPAGES_ROOT=self.content,
            FLATPAGES_ENCODING="utf-8",
            FLATPAGES_AUTO_RELOAD=True,
        )
        self.pages = FlatPages(self.app)
        FlatPagesPandoc("markdown", self.app, pre_render=False)
Ejemplo n.º 37
0
    def setUp(self):
        self.tmp = mkdtemp()
        self.content = os.path.join(self.tmp, "content")
        os.makedirs(self.content)

        self.app = Flask(__name__, static_folder=os.path.join(self.tmp, "static"))
        self.app.config.update(
            FLATPAGES_ROOT=self.content,
            FLATPAGES_AUTO_RELOAD=True,
            FLATPAGES_ENCODING="utf-8",
            FLATPAGES_MARKDOWN_EXTENSIONS=["fenced_code"],
        )
        self.pages = FlatPages(self.app)
        FlatPagesKnitr(self.app)
 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)
Ejemplo n.º 39
0
def admin():
    # Handle forwarding if redirected here after login
    if session.get("next_url"):
        next_url = session.get("next_url")
        session.pop("next_url", None)
        return redirect(next_url)

    # Process form data
    form = AdminForm()
    form.tag.choices = app.config["BLOG_TAGS"]
    if form.validate_on_submit():
        pages_directory = (Path() / app.config["FLASK_APP"] /
                           app.config["FLATPAGES_ROOT"])
        if not pages_directory.exists():
            abort(500)

        result = form.save(
            template="page_contents.j2",
            directory=pages_directory,
        )
        if result:
            FlatPages.reload(pages)
            flash("Blog entry posted successfully!", "Info")
        else:
            flash("Something went wrong.  Please try again shortly.", "Error")

        return redirect(url_for("admin"))

    else:
        if form.errors:
            flash(
                "Please correct errors detected in your form",
                "Error",
            )

    return render_template("admin.j2", form=form)
Ejemplo n.º 40
0
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 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>')
        self.check_default_codehilite_page(pages)
Ejemplo n.º 42
0
class TestFlatPagesKnitr(unittest.TestCase):
    def setUp(self):
        self.tmp = mkdtemp()
        self.content = os.path.join(self.tmp, "content")
        os.makedirs(self.content)

        self.app = Flask(__name__, static_folder=os.path.join(self.tmp, "static"))
        self.app.config.update(
            FLATPAGES_ROOT=self.content,
            FLATPAGES_AUTO_RELOAD=True,
            FLATPAGES_ENCODING="utf-8",
            FLATPAGES_MARKDOWN_EXTENSIONS=["fenced_code"],
        )
        self.pages = FlatPages(self.app)
        FlatPagesKnitr(self.app)

    def tearDown(self):
        rmtree(self.tmp)

    def get(self, body, ext=".Rmd", enc="utf-8"):
        self.app.config.update(FLATPAGES_EXTENSION=ext)
        with open(os.path.join(self.content, "test" + ext), "w", enc) as f:
            f.write("title:test\n\n" + body)
        return self.pages.get("test").html

    def test_rmd(self):
        self.assertEqual(self.get("#test"), "<h1>test</h1>")

    def test_r(self):
        self.assertTrue("3.14" in self.get("```{r}\npi\n```"))

    def test_plot(self):
        self.get("```{r, test}\nplot(1:4, 1:4)\n```")
        self.assertTrue(os.path.exists(os.path.join(
            self.tmp, "static", "knitr", "test", "figure", "test-1.png")))

    def test_unicode(self):
        self.assertTrue(u"萬大事都有得解決" in self.get(u"```{r}\npaste('萬大事都有得解決')\n```"))

    def test_unicode2(self):
        self.app.config.update(FLATPAGES_ENCODING="iso-8859-15")
        self.assertEqual(self.get(u"äöü", enc="iso-8859-15"), u"<p>äöü</p>")
Ejemplo n.º 43
0
    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
Ejemplo n.º 44
0
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
    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
Ejemplo n.º 46
0
from flask import Flask
from flask_flatpages import FlatPages, pygments_style_defs

app = Flask(__name__)
pages = FlatPages()

APP_SETTINGS = "app.cfg"

app.config.from_pyfile(APP_SETTINGS)
pages.init_app(app)

import blog.views
Ejemplo n.º 47
0
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)
Ejemplo n.º 48
0
 def setUp(self):
     app.config["FLATPAGES_ROOT"] = "test/test_pages"
     self.pages = FlatPages(app)
 def test_markdown(self):
     pages = FlatPages(Flask(__name__))
     foo = pages.get('foo')
     self.assertEqual(foo.body, 'Foo *bar*\n')
     self.assertEqual(foo.html, '<p>Foo <em>bar</em></p>')
Ejemplo n.º 50
0
 def __init__(self):
     self.flat_pages = FlatPages()
     self.root_category = Category(None, '<root>')
 def test_get_or_404(self):
     pages = FlatPages(Flask(__name__))
     self.assertEqual(pages.get_or_404('foo/bar').path, 'foo/bar')
     self.assertRaises(NotFound, pages.get_or_404, 'nonexistent')
Ejemplo n.º 52
0
class CategorizedFlatPages:
    """The main interface to gather pages and categories

    * What is it used for?

    - Looping: E.g. In the navbar
    - get news → get_articles_of_category('news')
    - get static page → get_or_404()
    """
    def __init__(self):
        self.flat_pages = FlatPages()
        self.root_category = Category(None, '<root>')

    def init_app(self, app):
        self.flat_pages.init_app(app)
        self._init_categories()

    @property
    def categories(self):
        """Yield all categories as an iterable
        """
        return sorted(self.root_category.categories.values(),
                      key=attrgetter('rank'))

    def get(self, category_id, article_id):
        category = self.root_category.categories.get(category_id)
        if category is None:
            return None
        return category._articles.get(article_id)

    def get_category(self, category_id):
        """Return the `Category` object from a given name (id)
        """
        return self.root_category.categories.get(category_id)

    def get_articles_of_category(self, category_id):
        """Get the articles of a category

        - ONLY used for fetching news
        """
        articles = []
        category = self.get_category(category_id)
        if category:
            for a in category._articles.values():
                if a.id != 'index':
                    articles.append(a)
        return articles

    def get_or_404(self, category_id, article_id):
        """Fetch a static page"""
        page = self.get(category_id, article_id)
        if page is None:
            abort(404)
        return page

    def _init_categories(self):
        # TODO: Store categories, not articles
        for page in self.flat_pages:
            # get category + page name
            # plus, assert that there is nothing more to that.
            components = page.path.split('/')
            parent = self.root_category
            for category_id in components[:-1]:
                parent = parent.add_child_category(category_id)
            basename = components[-1]
            parent.add_article(basename, page)

    def reload(self):
        self.flat_pages.reload()
        self._init_categories()
 def test_get(self):
     pages = FlatPages(Flask(__name__))
     self.assertEqual(pages.get('foo/bar').path, 'foo/bar')
     self.assertEqual(pages.get('nonexistent'), None)
     self.assertEqual(pages.get('nonexistent', 42), 42)
Ejemplo n.º 54
0
#!/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_))
 def test_consistency(self):
     pages = FlatPages(Flask(__name__))
     for page in pages:
         assert pages.get(page.path) is page
Ejemplo n.º 56
0
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']
Ejemplo n.º 57
0
# -*- coding: utf-8 -*-
'''mysite __init__
''' 

from flask import Flask

from flask_flatpages import FlatPages

from flask_mail import Mail

app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
app.config.from_pyfile('config.py')

Email = Mail(app)

app.config['FLATPAGES_EXTENSION'] = '.md'
flatpages = FlatPages()
flatpages.init_app(app)

# 注册蓝图
# 后import blog 是因为防止循环导入。 
#blog中引用了flatpage, 如果放在前面则flatpage还未创建从而引发错误
from .blog import blog
#from .api import api
app.register_blueprint(blog)
#app.register_blueprint(api)