move dirpath to meta
This commit is contained in:
29
__init__.py
29
__init__.py
@@ -1,3 +1,8 @@
|
|||||||
|
"""
|
||||||
|
This module is based on flask_flatpages and creates a website structure based on a file structure.
|
||||||
|
By default the .md extension creates a html website
|
||||||
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
from flask import Flask, Blueprint,render_template, send_from_directory,jsonify, url_for
|
from flask import Flask, Blueprint,render_template, send_from_directory,jsonify, url_for
|
||||||
from flask_flatpages import FlatPages, pygments_style_defs
|
from flask_flatpages import FlatPages, pygments_style_defs
|
||||||
@@ -33,26 +38,32 @@ freezer = Freezer(app)
|
|||||||
page_blueprint = Blueprint('intern', __name__)
|
page_blueprint = Blueprint('intern', __name__)
|
||||||
|
|
||||||
# completes the meta hash if a configuration is not set
|
# completes the meta hash if a configuration is not set
|
||||||
def page_defaults(page, path):
|
def page_defaults(page, dirpath, is_index=False):
|
||||||
page.meta["title"]=page.meta.get("title", path.split('/')[-1])
|
if is_index:
|
||||||
|
page.meta["title"]=page.meta.get("title", dirpath.split('/')[-1])
|
||||||
|
else:
|
||||||
|
page.meta["title"]=page.meta.get("title", page.path.split('/')[-1])
|
||||||
page.meta["template"]=page.meta.get("template", cfg.default_template)
|
page.meta["template"]=page.meta.get("template", cfg.default_template)
|
||||||
return page
|
return page
|
||||||
|
|
||||||
@page_blueprint.route('/<path:name>/')
|
@page_blueprint.route('/<path:name>/')
|
||||||
@page_blueprint.route('/')
|
@page_blueprint.route('/')
|
||||||
def post(name='index'):
|
def post(name='index'):
|
||||||
is_index, path, page = flatpages.get_flatpage(name)
|
page = flatpages.get(name)
|
||||||
|
is_index=page.meta["is_index"]
|
||||||
|
dirpath=page.meta["dirpath"]
|
||||||
|
|
||||||
if not page is None:
|
if not page is None:
|
||||||
page = page_defaults(page, path)
|
# page = page_defaults(page, dirpath, is_index)
|
||||||
fl = linklist_dict_lists(flatpages.load_linklists_for_templates(page.path,path, is_index, page.meta,partial(url_for,'intern.post')))
|
fl = linklist_dict_lists(flatpages.load_linklists_for_templates(page.path, dirpath, is_index, page.meta,partial(url_for,'intern.post')))
|
||||||
|
|
||||||
return render_template(page.meta["template"], post=page,
|
return render_template(page.meta["template"], post=page,
|
||||||
pth=path, filelists=fl)
|
pth=dirpath, filelists=fl)
|
||||||
|
|
||||||
if os.path.exists(os.path.join(FLATPAGES_ROOT,path)):
|
if os.path.exists(os.path.join(FLATPAGES_ROOT,name)):
|
||||||
return send_from_directory(FLATPAGES_ROOT,path)
|
return send_from_directory(FLATPAGES_ROOT,name)
|
||||||
else:
|
else:
|
||||||
return send_from_directory('static',path)
|
return send_from_directory('static',name)
|
||||||
|
|
||||||
|
|
||||||
def json_url_for(paths):
|
def json_url_for(paths):
|
||||||
|
|||||||
152
flatpages.py
152
flatpages.py
@@ -4,7 +4,7 @@ from flask import url_for
|
|||||||
import re
|
import re
|
||||||
from utils import path_depth,pjoin2,pjoin,list_dir, page_to_link, file_to_link
|
from utils import path_depth,pjoin2,pjoin,list_dir, page_to_link, file_to_link
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
from werkzeug.utils import cached_property
|
||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
|
|
||||||
FileLists=namedtuple("FileLists", ["list_files", "list_images", "sub_pages", "sub_index_pages", "breadcrumbs"])
|
FileLists=namedtuple("FileLists", ["list_files", "list_images", "sub_pages", "sub_index_pages", "breadcrumbs"])
|
||||||
@@ -20,6 +20,10 @@ list_dir_img=partial(list_dir, ext=["jpg", "jpeg","JPG"])
|
|||||||
|
|
||||||
class FlatPagesIndex(FlatPages):
|
class FlatPagesIndex(FlatPages):
|
||||||
FLATPAGES_ROOT="."
|
FLATPAGES_ROOT="."
|
||||||
|
def __init__(self,app=None,name=None):
|
||||||
|
self.default_template="page.html"
|
||||||
|
super(FlatPagesIndex, self).__init__(app=app, name=name)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_breadcrumb_paths(path):
|
def get_breadcrumb_paths(path):
|
||||||
"""
|
"""
|
||||||
@@ -27,12 +31,12 @@ class FlatPagesIndex(FlatPages):
|
|||||||
a/b/index -> [a/index a/b/index]
|
a/b/index -> [a/index a/b/index]
|
||||||
"""
|
"""
|
||||||
elements = path.split('/')
|
elements = path.split('/')
|
||||||
print "i: %s" % elements
|
# print "i: %s" % elements
|
||||||
|
|
||||||
elements2 = ['index']
|
elements2 = ['index']
|
||||||
if len(elements)>2:
|
if len(elements)>2:
|
||||||
for i in range(1,len(elements)):
|
for i in range(1,len(elements)):
|
||||||
print "i: %s" % elements[0:i]
|
# print "i: %s" % elements[0:i]
|
||||||
elements2.append(pjoin2(elements[0:i])+u'/index')
|
elements2.append(pjoin2(elements[0:i])+u'/index')
|
||||||
return elements2
|
return elements2
|
||||||
|
|
||||||
@@ -44,70 +48,91 @@ class FlatPagesIndex(FlatPages):
|
|||||||
else:
|
else:
|
||||||
return self.get_pages(FlatPagesIndex.get_breadcrumb_paths(page))
|
return self.get_pages(FlatPagesIndex.get_breadcrumb_paths(page))
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def get_paths(pages):
|
|
||||||
return (p.path for p in pages)
|
|
||||||
|
|
||||||
def get_pages(self, paths):
|
def get_pages(self, paths):
|
||||||
|
"get pages for a list of paths"
|
||||||
if paths is None:
|
if paths is None:
|
||||||
raise AttributeError("paths for get_pages can't be None")
|
raise AttributeError("paths for get_pages can't be None")
|
||||||
return (self.get(p) for p in paths)
|
return (self.get(p) for p in paths)
|
||||||
|
|
||||||
def get_sub_pages(self, path):
|
|
||||||
def is_subpage(path, root):
|
@staticmethod
|
||||||
|
def get_paths(pages):
|
||||||
|
return (p.path for p in pages)
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return (FlatPagesIndex.page_defaults(p,"",False) for p in super(self.__class__,self).__iter__())
|
||||||
|
@cached_property
|
||||||
|
def _pages(self):
|
||||||
|
d=super(FlatPagesIndex,self)._pages
|
||||||
|
for path in d:
|
||||||
|
d[path]=FlatPagesIndex.page_defaults(d[path],"")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def page_defaults(self, page, dirpath, is_index=False):
|
||||||
|
is_index = (page.path.split('/')[-1]=='index')
|
||||||
|
page.meta["is_index"]=is_index
|
||||||
|
dirpath='/'.join(path.split('/')[0:-1]) # remove index from path
|
||||||
|
page.meta["dirpath"]=dirpath
|
||||||
|
if is_index:
|
||||||
|
page.meta["title"]=page.meta.get("title", dirpath.split('/')[-1])
|
||||||
|
else:
|
||||||
|
page.meta["title"]=page.meta.get("title", page.path.split('/')[-1])
|
||||||
|
page.meta["template"]=page.meta.get("template", self.default_template)
|
||||||
|
return page
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_subpage(path,root,page_root=""):
|
||||||
return (path.startswith(root) and # is a subpage
|
return (path.startswith(root) and # is a subpage
|
||||||
( re.match('.*index',path) is None) and # is no index
|
path_depth(path)<path_depth(root)+2 and # only one level
|
||||||
path_depth(path)<path_depth(root)+2
|
( page_root != path)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_index_path(path):
|
||||||
|
return not ( re.match('.*index',path) is None)
|
||||||
|
|
||||||
|
def get_sub_pages(self, dirpath,page_path=""):
|
||||||
return (p for p in self
|
return (p for p in self
|
||||||
if is_subpage(str(p.path),path))
|
if FlatPagesIndex.is_subpage(str(p.path),dirpath, page_path)
|
||||||
|
and not FlatPagesIndex.is_index_path(p.path)
|
||||||
|
)
|
||||||
|
|
||||||
# List all index subpages of the current page i.e. all pages in subdirectories
|
# List all index subpages of the current page i.e. all pages in subdirectories
|
||||||
def get_sub_ipages(self, path):
|
def get_sub_ipages(self, page ):
|
||||||
cc=path_depth(path)
|
dirpath=page.meta["dirpath"]
|
||||||
ppath="index" if path=="" else pjoin2([path,"index"])
|
page_path=page.path
|
||||||
ps=(p for p in self
|
return (p for p in self
|
||||||
if (p.path.startswith(path) and # subpages of this page
|
if FlatPagesIndex.is_subpage(str(p.path), dirpath, page_path)
|
||||||
not ( re.match('.*index',p.path) is None) and # only index
|
and FlatPagesIndex.is_index_path(p.path)
|
||||||
( ppath != p.path) and # not identical page
|
)
|
||||||
len(p.path.split('/'))<=cc+2) ) # only one level
|
|
||||||
return ps
|
|
||||||
|
|
||||||
|
def __getitem__(self,key):
|
||||||
|
self.get(key)
|
||||||
|
|
||||||
# load a page from a path information
|
# load a page from a path information
|
||||||
def get_flatpage(self,path):
|
def get(self,path):
|
||||||
is_index = path=='' or path.split('/')[-1]=='index'
|
if path == '': path='index'
|
||||||
if path == 'index' or path=='':
|
page = super(FlatPagesIndex,self).get(self,path) # try to load index page
|
||||||
is_index=True
|
if page ==None:
|
||||||
path=''
|
path=pjoin(path,"index")
|
||||||
pathi='index'
|
page = super(FlatPagesIndex,self).get(self,path) # try to load index page
|
||||||
else:
|
return page
|
||||||
if path.split('/')[-1]=='index': # last element is "index" ?
|
|
||||||
is_index=True
|
|
||||||
path='/'.join(path.split('/')[0:-1]) # remove index from path
|
|
||||||
pathi = u'{}/{}'.format(path, 'index') # try to add index to the path
|
|
||||||
page = FlatPages.get(self,pathi) # try to load index page
|
|
||||||
if not page is None: # if successful it is a index
|
|
||||||
is_index=True
|
|
||||||
else:
|
|
||||||
page=FlatPages.get(self,path)
|
|
||||||
return (is_index, path, page)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def load_linklists_for_templates(self,page_path, rel_path, is_index=True, cfg={}, page_url_for=partial(url_for,'intern.postjson')):
|
|
||||||
abspath = pjoin(FlatPagesIndex.FLATPAGES_ROOT,rel_path)
|
|
||||||
# if not is_index:
|
|
||||||
dirpath= pjoin(FlatPagesIndex.FLATPAGES_ROOT,"/".join(page_path.split('/')[:-1]))
|
|
||||||
|
|
||||||
|
def load_linklists_for_templates(self, page_path, dirpath,
|
||||||
|
is_index=True, cfg={},
|
||||||
|
page_url_for=partial(url_for,'intern.postjson')):
|
||||||
|
abspath = pjoin(FlatPagesIndex.FLATPAGES_ROOT,dirpath)
|
||||||
bc = page_to_link( self.breadcrumbs(page_path), page_url_for)
|
bc = page_to_link( self.breadcrumbs(page_path), page_url_for)
|
||||||
il=[]
|
il=[]
|
||||||
if (cfg.get("has_img",False) ):
|
if (cfg.get("has_img",False) ):
|
||||||
il=file_to_link(list_dir_img(dirpath), page_url_for)
|
il=file_to_link(list_dir_img(abspath), page_url_for)
|
||||||
if is_index == True:
|
if is_index == True:
|
||||||
ld,sp,spi=(file_to_link(list_dir_md(abspath),page_url_for),
|
ld,sp,spi=(file_to_link(list_dir_md(abspath), partial(url_for,'intern.post')),
|
||||||
page_to_link(self.get_sub_pages(rel_path),page_url_for),
|
page_to_link(self.get_sub_pages(dirpath,page_path), page_url_for),
|
||||||
page_to_link(self.get_sub_ipages(rel_path),page_url_for))
|
page_to_link(self.get_sub_ipages(dirpath,page_path), page_url_for))
|
||||||
else:
|
else:
|
||||||
ld,sp,spi=([],[],[])
|
ld,sp,spi=([],[],[])
|
||||||
|
|
||||||
@@ -115,32 +140,3 @@ class FlatPagesIndex(FlatPages):
|
|||||||
return fl
|
return fl
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def load_lists_for_templates(self,path,is_index=True, cfg={}):
|
|
||||||
path2 = pjoin(FlatPagesIndex.FLATPAGES_ROOT,path)
|
|
||||||
if not is_index:
|
|
||||||
path="/".join(path2.split('/')[:-1])
|
|
||||||
|
|
||||||
# List all subpages of the current page
|
|
||||||
# get_sub_pages = partial(FlatPagesIndex.get_sub_pages, self)
|
|
||||||
# get_sub_ipages = partial(FlatPagesIndex.get_sub_ipages, self)
|
|
||||||
bc= self.breadcrumbs(path)
|
|
||||||
il=[]
|
|
||||||
if (cfg.get("has_img",False) ):
|
|
||||||
print "path2: %s" % path2
|
|
||||||
il=list_dir_img(mpath)
|
|
||||||
if is_index == True:
|
|
||||||
ld=list_dir_md(path2)
|
|
||||||
sp=self.get_sub_pages(path)
|
|
||||||
spi=self.get_sub_ipages(path)
|
|
||||||
else:
|
|
||||||
ld=[]
|
|
||||||
sp=[]
|
|
||||||
spi=[]
|
|
||||||
|
|
||||||
fl=FileLists(list_files=ld, list_images=il, sub_pages=sp, sub_index_pages=spi, breadcrumbs=bc)
|
|
||||||
return fl
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,45 @@
|
|||||||
import unittest
|
import unittest
|
||||||
import flatpages as fp
|
from flatpages import FlatPagesIndex
|
||||||
from mock import patch
|
from flask_flatpages import FlatPages
|
||||||
|
from mock import patch, Mock
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
class TestFlatpages(unittest.TestCase):
|
class TestFlatpages(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
app = Flask(__name__)
|
||||||
|
self.fp=FlatPagesIndex(app)
|
||||||
|
d={}
|
||||||
|
for p in ["test/index", "page1", "index", "test/test2/index", "test/test2/page4", "test2/page0","test/page2", "test/page3"]:
|
||||||
|
m=Mock()
|
||||||
|
m.path=p
|
||||||
|
m.meta={}
|
||||||
|
d[p]=m
|
||||||
|
self.pages=d
|
||||||
def test_p(self):
|
def test_p(self):
|
||||||
self.assertEquals(fp.FlatPagesIndex.get_breadcrumb_paths(""),['index'])
|
self.assertEquals(FlatPagesIndex.get_breadcrumb_paths(""),['index'])
|
||||||
self.assertEquals(fp.FlatPagesIndex.get_breadcrumb_paths("index"),['index'])
|
self.assertEquals(FlatPagesIndex.get_breadcrumb_paths("index"),['index'])
|
||||||
|
def test_subpages(self):
|
||||||
|
with patch.object(FlatPages,"_pages", self.pages):
|
||||||
|
spgs=self.fp.get_sub_pages("","index")
|
||||||
|
self.assertEquals([p.path for p in spgs],["page1"])
|
||||||
|
def test_subipages(self):
|
||||||
|
with patch.object(FlatPages,"_pages", self.pages):
|
||||||
|
spgs=list(self.fp.get_sub_ipages("","index"))
|
||||||
|
self.assertEquals([p.path for p in spgs],["test/index"])
|
||||||
|
self.assertEquals([p.meta["title"] for p in spgs],["test"])
|
||||||
|
|
||||||
|
|
||||||
|
# with patch("flask_flatpages.FlatPages._pages") as mock_pagelist:
|
||||||
|
# mock_pagelist=iter(["test/index", "page1", "index", "test/page2"])
|
||||||
|
# print self.fp.get_sub_pages("","index")
|
||||||
|
# self.assertEquals(list(self.fp.get_sub_pages("index")), [])
|
||||||
|
|
||||||
|
# def test_getflatpage(self):
|
||||||
|
# p=self.fp.get_flatpage("")
|
||||||
|
# with patch("flask_flatpages.FlatPages.get") as mock_page:
|
||||||
|
# mock_page.meta={"title": "Hello"}
|
||||||
|
# print p
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user