Skip to content

Commit

Permalink
Merge pull request #199 from zerasul/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
zerasul authored May 8, 2021
2 parents 174d5eb + 5abd33d commit 3f4631f
Show file tree
Hide file tree
Showing 13 changed files with 106 additions and 72 deletions.
2 changes: 2 additions & 0 deletions blask/Dockerfile_template
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ EXPOSE 8000

COPY . /opt/blask

VOLUME blask /opt/blask

CMD ["gunicorn", "-b", "0.0.0.0:8000","--workers", "2", "main"]
49 changes: 34 additions & 15 deletions blask/blaskapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from blask.errors import PageNotExistError



class BlaskApp:
"""
blask Application Main Class
Expand All @@ -47,16 +46,26 @@ def __init__(self, **kwargs):
template_folder=self.settings["templateDir"],
static_folder=self.settings["staticDir"],
)
self.app.add_url_rule("/", endpoint="index", view_func=self._index, methods=["GET"])
self.app.add_url_rule("/sitemap.xml", view_func=self._get_sitemap, methods=["GET"])
self.app.add_url_rule("/<filename>", view_func=self._getpage, methods=["GET"])
self.app.add_url_rule(
"/<path:subpath>/<filename>", view_func=self._get_subpage, methods=["GET"]
"/", endpoint="index", view_func=self._index, methods=["GET"])
self.app.add_url_rule(
"/sitemap.xml", view_func=self._get_sitemap, methods=["GET"])
self.app.add_url_rule(
"/<filename>", view_func=self._getpage, methods=["GET"])
self.app.add_url_rule(
"/<path:subpath>/<filename>",
view_func=self._get_subpage, methods=["GET"]
)
self.app.add_url_rule(
"/tag/<tag>", view_func=self._gettag, methods=["GET"])
self.app.add_url_rule(
"/search", view_func=self.searchpages, methods=["POST"])
self.app.add_url_rule(
"/category/<category>",
view_func=self._getcategory, methods=["GET"]
)
self.app.add_url_rule("/tag/<tag>", view_func=self._gettag, methods=["GET"])
self.app.add_url_rule("/search", view_func=self.searchpages, methods=["POST"])
self.app.add_url_rule("/category/<category>", view_func=self._getcategory, methods=["GET"])
self.app.add_url_rule("/author/<author>", view_func=self._getauthor, methods=["GET"])
self.app.add_url_rule(
"/author/<author>", view_func=self._getauthor, methods=["GET"])
# Register the error handler for each setting
for error in self.settings["errors"].keys():
self.app.register_error_handler(error, f=self._handle_http_errors)
Expand All @@ -70,7 +79,8 @@ def _index(self):
template = entry.template
if template is None:
template = self.settings["defaultLayout"]
return render_template(template, title=self.settings["title"], content=entry.content)
return render_template(
template, title=self.settings["title"], content=entry.content)

def _getpage(self, filename):
"""
Expand Down Expand Up @@ -115,7 +125,8 @@ def _get_sitemap(self):
:returns: prints the sitemapfile
"""
return Response(
self.blogrenderer.generate_sitemap_xml(self.settings["postDir"], request.url_root),
self.blogrenderer.generate_sitemap_xml(
self.settings["postDir"], request.url_root),
content_type="text/xml",
)

Expand All @@ -128,7 +139,9 @@ def _gettag(self, tag):
postlist = self.blogrenderer.list_posts([tag])
content = self.blogrenderer.generatetagpage(postlist)
return render_template(
self.settings["defaultLayout"], title=self.settings["title"], content=content
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
)

def searchpages(self):
Expand All @@ -139,7 +152,9 @@ def searchpages(self):
postlist = self.blogrenderer.list_posts(search=request.form["search"])
content = self.blogrenderer.generatetagpage(postlist)
return render_template(
self.settings["defaultLayout"], title=self.settings["title"], content=content
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
)

def _getcategory(self, category):
Expand All @@ -151,7 +166,9 @@ def _getcategory(self, category):
postlist = self.blogrenderer.list_posts(category=category)
content = self.blogrenderer.generatetagpage(postlist)
return render_template(
self.settings["defaultLayout"], title=self.settings["title"], content=content
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
)

def _getauthor(self, author):
Expand All @@ -163,7 +180,9 @@ def _getauthor(self, author):
postlist = self.blogrenderer.list_posts(author=author)
content = self.blogrenderer.generatetagpage(postlist)
return render_template(
self.settings["defaultLayout"], title=self.settings["title"], content=content
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
)

def _handle_http_errors(self, error_message):
Expand Down
10 changes: 6 additions & 4 deletions blask/blaskcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ def blaskcli():


@blaskcli.command(help="Run the instance of blask")
@click.option("--debug", default=False, help="Init with de debug flag", is_flag=True)
@click.option(
"--debug", default=False, help="Init with de debug flag", is_flag=True)
@click.option(
"--port", default=5000, help="Port where the server is listening")
@click.option(
Expand All @@ -111,11 +112,12 @@ def run(debug, port, host):

@blaskcli.command(help="Initialize a new blask Project")
@click.option(
"--with-docker", default=False, help="Add a DockerFile to the blask directory", is_flag=True)
"--with-docker", default=False,
help="Add a DockerFile to the blask directory", is_flag=True)
def init(with_docker):
"""
Inits a new blask Instance; with the default options.
:param with_docker: if is set to True, add a Dockerfile in the root directory.
:param with_docker: if is True, add a Dockerfile in the root directory.
"""
click.echo("Initializing new blask Project")
click.echo("Using default Settings")
Expand All @@ -133,7 +135,7 @@ def init(with_docker):
cliController.createsettingsfile()
cliController.createnotfoundpage(path.join(postdir, '404.md'))
if with_docker:
CLIController.createdockerfile(path.join("Dockerfile"))
cliController.createdockerfile(path.join("Dockerfile"))
click.echo("Created new blask project on %s" % getcwd())
click.echo("Now you can execute: blaskcli run")
except FileExistsError:
Expand Down
25 changes: 14 additions & 11 deletions blask/blogrenderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def renderfile(self, filename):
:raises PageNotExistError Raise this error if file does not exist or
would fall out of the posts directory.
"""
page_not_exist_exception = PageNotExistError(f"{filename} does not exists in {self.postdir} directory")
page_not_exist_exception = PageNotExistError(
f"{filename} does not exists in {self.postdir} directory")
try:
file = f"{filename}.md"
filepath = safe_join(self.postdir, file)
Expand All @@ -90,11 +91,12 @@ def rendertext(self, filename, text):
:param text: Text write in Markdown.
:return: BlogEntry.
"""
mark_down = Markdown(extensions=["meta", "markdown.extensions.codehilite"])
mark_down = Markdown(
extensions=["meta", "markdown.extensions.codehilite"])
entry = BlogEntry(filename, mark_down, text)
return entry

#pylint: disable=dangerous-default-value
# pylint: disable=dangerous-default-value
def list_posts(
self,
tags=None,
Expand Down Expand Up @@ -125,7 +127,7 @@ def list_posts(
entries = list(map(lambda l: self.renderfile(l), mapfilter))
if tags:
for tag in tags:
entries = list(filter(lambda l ,t=tag: t in l.tags, entries))
entries = list(filter(lambda l, t=tag: t in l.tags, entries))
if category:
entries = list(filter(lambda c: c.category == category, entries))
if author:
Expand All @@ -135,8 +137,10 @@ def list_posts(
if orderbydate:
# create a sublist with only entries with date
dateredentries = list(filter(lambda e: e.date is None, entries))
notdateredentries = list(filter(lambda d: d.date is not None, entries))
entries = list(sorted(dateredentries, key=lambda t: t.date, reverse=True))
notdateredentries = list(
filter(lambda d: d.date is not None, entries))
entries = list(
sorted(dateredentries, key=lambda t: t.date, reverse=True))
entries.extend(notdateredentries)
return entries

Expand All @@ -163,7 +167,9 @@ def generate_sitemap_xml(self, postlist, baseurl="http://localhost:5000"):
:param postlist: list with all the posts for the sitemapxml.
:return: return the xml output for the Sitemap.xml file.
"""
root = ET.Element("urlset", attrib={"xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9"})
root = ET.Element(
"urlset",
attrib={"xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9"})
rpostlist = self._listdirectoriesrecursive(postlist)
rpostlist.remove("index.md")
rpostlist = list(map(lambda l: path.splitext(l)[0], rpostlist))
Expand All @@ -182,7 +188,6 @@ def generate_sitemap_xml(self, postlist, baseurl="http://localhost:5000"):
for post in rpostlist:
if post.name:
title = post.name

purlindex = ET.SubElement(root, "url")
plocindex = ET.SubElement(purlindex, "loc")
plocindex.text = baseurl + title
Expand All @@ -194,10 +199,8 @@ def generate_sitemap_xml(self, postlist, baseurl="http://localhost:5000"):
if post.periodicity:
pchangefreq.text = post.periodicity
else:
pchangefreq.text= "monthly"

pchangefreq.text = "monthly"
priority = ET.SubElement(purlindex, "priority")

priority.text = "0.5"
return ET.tostring(root, encoding="UTF-8", method="xml")

Expand Down
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging
from blask import BlaskApp

application=BlaskApp().app
application = BlaskApp().app

if __name__ == '__main__':
# Argument parsing
Expand Down
2 changes: 1 addition & 1 deletion settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
templateDir = str(BASE_DIR / "templates")
postDir = "posts"
defaultLayout = "template.html"
staticDir = str(BASE_DIR /"static")
staticDir = str(BASE_DIR / "static")
title = "blask | A Simple Blog Engine Based on Flask"
errors = {404: "404"}
20 changes: 12 additions & 8 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,21 @@
from setuptools import setup, find_packages
from pathlib import Path

info_file = Path(__file__).resolve().parents[0] / "README.md"
base_dir = Path(__file__).resolve().parents[0]

info_file = base_dir / "README.md"
with info_file.open() as f:
long_desc = f.read()
# adding nonpython files to package
mdownfile = Path(__file__).resolve().parents[0] / "blask" / "markdown_template.md"
indextempfile = Path(__file__).resolve().parents[0] / "blask" / "index_template.html"
Dockerfile_template = Path(__file__).resolve().parents[0] / "blask" / "Dockerfile_template"
default404 = Path(__file__).resolve().parents[0] / "blask" / "default_404.md"
default_env = Path(__file__).resolve().parents[0] / "blask" / "default_env.env"
mdownfile = base_dir / "blask" / "markdown_template.md"
indextempfile = base_dir / "blask" / "index_template.html"
Dockerfile_template = base_dir / "blask" / "Dockerfile_template"
default404 = base_dir / "blask" / "default_404.md"
default_env = base_dir / "blask" / "default_env.env"

setup(
name="blask",
version="0.2.2",
version="0.2.3",
packages=find_packages(exclude=["tests"]),
url="https://getblask.com",
license="GPL 3.0",
Expand All @@ -44,6 +46,8 @@
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
package_data={
"blask": [
Expand All @@ -60,7 +64,7 @@
""",
long_description=long_desc,
long_description_content_type="text/markdown",
python_requires=">=3",
python_requires=">=3.6",
install_requires=["flask", "markdown", "Pygments", "click"],
test_requires=["pytest", "pytest-cov", "pylint", "pytest-mock"],
)
6 changes: 3 additions & 3 deletions tests/blaskcli_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@
from blask import blaskcli
from pytest_mock import mocker


class TestCLI:

tempdir = None
runner = CliRunner()


def test_init(self, mocker):
mocker.patch('os.makedirs')
mocker.patch('shutil.copy')
run = self.runner.invoke(blaskcli.blaskcli, ['init'])
assert "Initializing new blask Project" in run.output

def test_init_with_docker(self, mocker):
mocker.patch('os.makedirs')
mocker.patch('shutil.copy')
run = self.runner.invoke(blaskcli.blaskcli, ['init','--with-docker'])
run = self.runner.invoke(blaskcli.blaskcli, ['init', '--with-docker'])
assert "Initializing new blask Project" in run.output

def test_run(self, mocker):
Expand Down
7 changes: 4 additions & 3 deletions tests/blogrender_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
class TestblogRender:

blogrender = None
markdowntest = "---\ntitle: test\ndate: 2018-03-03\ntags: test,test2\n ---\n test"
markdowntest = (
"---\ntitle: test\ndate: 2018-03-03\ntags: test,test2\n ---\n test")

@fixture(autouse=True)
def initialize(self):
Expand Down Expand Up @@ -54,9 +55,9 @@ def test_search(self):

def test_str(self):
entry = self.blogrender.renderfile("index")
str(entry)
str(entry) # TODO: Test incompleted

def test_listDirectories(self):
def test_list_directories(self):
entries = self.blogrender.list_posts(["subdir"])
assert len(entries) == 1
entrieslist = self.blogrender.generatetagpage(entries)
Expand Down
Loading

0 comments on commit 3f4631f

Please sign in to comment.