Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 25 additions & 22 deletions blask/blaskapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from werkzeug.utils import safe_join
from flask import Flask, render_template, request, abort, Response
from flask import Flask, Response, abort, render_template, request
from flask_wtf import CSRFProtect
from werkzeug.utils import safe_join

from blask.blasksettings import BlaskSettings
from blask.blogrenderer import BlogRenderer
from blask.errors import PageNotExistError
Expand Down Expand Up @@ -47,28 +48,28 @@ def __init__(self, **kwargs):
template_folder=self.settings["templateDir"],
static_folder=self.settings["staticDir"],
)

self.csrf = CSRFProtect()
self.csrf.init_app(self.app)

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(
"/tag/<tag>", view_func=self._gettag, methods=["GET"])
"/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(
"/search", view_func=self.searchpages, methods=["POST"])
"/<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"])
"/category/<category>", view_func=self._getcategory, methods=["GET"]
)
self.app.add_url_rule(
"/author/<author>", view_func=self._getauthor, methods=["GET"])
"/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 @@ -83,7 +84,8 @@ def _index(self):
if template is None:
template = self.settings["defaultLayout"]
return render_template(
template, title=self.settings["title"], content=entry.content)
template, title=self.settings["title"], content=entry.content
)

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

Expand All @@ -144,7 +147,7 @@ def _gettag(self, tag):
return render_template(
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
content=content,
)

def searchpages(self):
Expand All @@ -157,7 +160,7 @@ def searchpages(self):
return render_template(
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
content=content,
)

def _getcategory(self, category):
Expand All @@ -171,7 +174,7 @@ def _getcategory(self, category):
return render_template(
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
content=content,
)

def _getauthor(self, author):
Expand All @@ -185,7 +188,7 @@ def _getauthor(self, author):
return render_template(
self.settings["defaultLayout"],
title=self.settings["title"],
content=content
content=content,
)

def _handle_http_errors(self, error_message):
Expand Down
52 changes: 29 additions & 23 deletions blask/blaskcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from os import makedirs, path, getcwd
from pathlib import Path
import shutil
from pkg_resources import get_distribution, DistributionNotFound
from os import getcwd, makedirs, path
from pathlib import Path

import typer
from pkg_resources import DistributionNotFound, get_distribution

from blask import BlaskApp, blasksettings

Expand All @@ -33,15 +33,15 @@ class CLIController:
Class that controls all the Command Line interface application
"""

default_template_file = str(LIB_DIR / 'index_template.html')
default_template_file = str(LIB_DIR / "index_template.html")

default_index = str(LIB_DIR / 'markdown_template.md')
default_index = str(LIB_DIR / "markdown_template.md")

settings = str(LIB_DIR / 'default_env.env')
settings = str(LIB_DIR / "default_env.env")

not_found = str(LIB_DIR / 'default_404.md')
not_found = str(LIB_DIR / "default_404.md")

docker_template = str(LIB_DIR / 'Dockerfile_template')
docker_template = str(LIB_DIR / "Dockerfile_template")

def createdefaultindexfile(self, filepath):
"""
Expand All @@ -61,7 +61,7 @@ def createsettingsfile(self):
"""
Create a new settings file
"""
shutil.copy(self.settings, '.env')
shutil.copy(self.settings, ".env")

def createnotfoundpage(self, filepath):
"""
Expand Down Expand Up @@ -92,17 +92,18 @@ def main() -> None:
version = get_distribution("blask").version
except DistributionNotFound:
version = "test_version"
typer.echo("blask (C) version %s" % version)
typer.echo(f"blask (C) version {version}")


@blaskcli.command(help="Run the instance of blask")
def run(
debug: bool = typer.Option(False, "--debug",
help="Init with the debug flag", is_flag=True),
port: int = typer.Option(5000, "--port",
help="Port where the server is listening"),
host: str = typer.Option("127.0.0.1", "--host",
help="Default Network interface listening"),
debug: bool = typer.Option(
False, "--debug", help="Init with the debug flag", is_flag=True
),
port: int = typer.Option(5000, "--port", help="Port where the server is listening"),
host: str = typer.Option(
"127.0.0.1", "--host", help="Default Network interface listening"
),
) -> None:
"""
Run the current blask instance
Expand All @@ -115,31 +116,36 @@ def run(
@blaskcli.command(help="Initialize a new blask Project")
def init(
with_docker: bool = typer.Option(
False, "--with-docker",
False,
"--with-docker",
help="Add a DockerFile to the blask directory",
is_flag=True)) -> None:
is_flag=True,
)
) -> None:
"""
Inits a new blask Instance; with the default options.
:param with_docker: if True, add a Dockerfile in the root directory.
"""
typer.echo("Initializing new blask Project")
typer.echo("Using default Settings")
postdir = path.basename(
path.dirname(str(blasksettings.DEFAULT_SETTINGS["postDir"] + "/")))
path.dirname(str(blasksettings.DEFAULT_SETTINGS["postDir"] + "/"))
)
templatedir = path.basename(
path.dirname(str(blasksettings.DEFAULT_SETTINGS["templateDir"] + "/"))
)
try:
makedirs(postdir)
cliController.createdefaultindexfile(path.join(postdir, "index.md"))
makedirs(templatedir)
cliController.createdefaulttemplatefile(
path.join(templatedir, "template.html"))
cliController.createdefaulttemplatefile(path.join(templatedir, "template.html"))
cliController.createsettingsfile()
cliController.createnotfoundpage(path.join(postdir, '404.md'))
cliController.createnotfoundpage(path.join(postdir, "404.md"))
if with_docker:
cliController.createdockerfile(path.join("Dockerfile"))
typer.echo("Created new blask project on %s" % getcwd())

current_dir = getcwd()
typer.echo(f"Created new blask project on {current_dir}")
typer.echo("Now you can execute: blaskcli run")
except FileExistsError:
typer.echo("There is an existing blask Project")
Expand Down
25 changes: 14 additions & 11 deletions blask/blasksettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
"""

import os
from importlib import import_module
from pathlib import Path
from sys import path
from importlib import import_module

BASE_DIR = Path(".").resolve()

Expand All @@ -31,11 +31,11 @@
"staticDir": str(BASE_DIR / "static"),
"theme": None,
"title": "blask | A Simple Blog Engine Based on Flask",
"errors": {404: "404"} # Dictionary with errors handler
"errors": {404: "404"}, # Dictionary with errors handler
}


class BlaskSettings(): # pylint: disable=too-few-public-methods
class BlaskSettings: # pylint: disable=too-few-public-methods
"""
blask configuration helper class
"""
Expand All @@ -59,18 +59,19 @@ def __init__(self, **kwargs):

# Load settings from the module in environment variable
settings_mod = import_module(
os.environ["BLASK_SETTINGS"], os.environ["BLASK_SETTINGS"])
os.environ["BLASK_SETTINGS"], os.environ["BLASK_SETTINGS"]
)
# settings are stored in settings_mod.BASE_DIR,
# settings_mod.templateDir, etc.

self.settings = {}
for key in DEFAULT_SETTINGS:
for key, value in DEFAULT_SETTINGS.items():
# for each of default attributes, try first to read the value
# in settings_mod and if not defined, use the default
# Note: settings_mod attributes which are not
# DEFAULT_SETTINGS are ignored

value = getattr(settings_mod, key, DEFAULT_SETTINGS[key])
value = getattr(settings_mod, key, value)
self.settings[key] = value
else:
# Copy default settings
Expand All @@ -82,18 +83,20 @@ def __init__(self, **kwargs):
self.settings[key] = os.environ[key]

# arguments always override default and environment settings
for kwarg in kwargs:
for kwarg, value in kwargs.items():
if kwarg in DEFAULT_SETTINGS:
self.settings[kwarg] = kwargs[kwarg]
self.settings[kwarg] = value

# Set theme
if self.settings["theme"] != None:
self.settings["templateDir"] = str(BASE_DIR / "themes" / self.settings['theme'])
if self.settings["theme"] is not None:
self.settings["templateDir"] = str(
BASE_DIR / "themes" / self.settings["theme"]
)

def __getitem__(self, key):
"""
Dictionary like settings access
"""
if key in self.settings:
return self.settings[key]
raise KeyError("There is no blask setting called %s" % key)
raise KeyError(f"There is no blask setting called {key}")
Loading