Skip to content

Commit

Permalink
Merge pull request #135 from zerasul/develop
Browse files Browse the repository at this point in the history
Blask v0.2.0
  • Loading branch information
zerasul committed Mar 13, 2020
2 parents 435798c + b3d78c4 commit 120b321
Show file tree
Hide file tree
Showing 22 changed files with 442 additions and 181 deletions.
11 changes: 11 additions & 0 deletions Blask/Dockerfile_template
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Blask example Dockerfile

FROM zerasul/blask:latest

WORKDIR /opt/blask

EXPOSE 8000

COPY . /opt/blask

CMD ["gunicorn", "-b", "0.0.0.0:8000","--workers", "2", "main"]
66 changes: 46 additions & 20 deletions Blask/blaskapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from Blask.blasksettings import BlaskSettings
from Blask.blogrenderer import BlogRenderer
from Blask.errors import PageNotExistError
from os.path import join


class BlaskApp:
Expand All @@ -36,7 +37,8 @@ class BlaskApp:
def __init__(self, **kwargs):
"""
Initialices a new Blask Instance
:param kwargs: Dictionary with all the required settings; for more info see :settings
:param kwargs: Dictionary with all the required settings;
for more info see :settings
"""
self.settings = BlaskSettings(**kwargs)
self.blogrenderer = BlogRenderer(self.settings["postDir"])
Expand All @@ -45,18 +47,25 @@ 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("/<filename>", view_func=self._getpage, 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"])
## Register the error handler for each setting
print(self.settings)
self.app.add_url_rule(
"/", endpoint="index", view_func=self._index, 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(
"/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)


def _index(self):
"""
Render the Index page
Expand All @@ -66,7 +75,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 All @@ -77,7 +87,7 @@ def _getpage(self, filename):
try:
entry = self.blogrenderer.renderfile(filename)
except PageNotExistError:
abort(404)
abort(404)
content = entry.content
date = entry.date
template = entry.template
Expand All @@ -86,16 +96,25 @@ def _getpage(self, filename):
author = entry.author
if template is None:
template = self.settings["defaultLayout"]
if entry.title is None:
title = self.settings["title"]
else:
title = entry.title

return render_template(
template,
title=self.settings["title"],
title=title,
content=content,
date=date,
tags=tags,
category=category,
author=author,
)

def _get_subpage(self, subpath, filename):
subfilename = join(subpath,filename)
return self._getpage(subfilename)

def _gettag(self, tag):
"""
Render the Tags Page.
Expand All @@ -105,7 +124,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 @@ -116,7 +137,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 @@ -128,7 +151,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 @@ -140,19 +165,20 @@ 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, errorMessage):
def _handle_http_errors(self, error_message):
"""
Handle the custom http error code; getting the custom url name.
:param errorMessage: Message error.
:return: rendered custom error page.
"""
page = self.settings['errors'][errorMessage.code]
page = self.settings['errors'][error_message.code]
return self._getpage(page)


def run(self, **kwargs):
"""
Run the current instance of Blask
Expand Down
115 changes: 38 additions & 77 deletions Blask/blaskcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,111 +16,62 @@
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 pkg_resources import get_distribution, DistributionNotFound
from pathlib import Path
import shutil

import click

from Blask import BlaskApp, blasksettings
from os import makedirs, path, getcwd
from pkg_resources import get_distribution, DistributionNotFound

LIB_DIR = Path(__file__).resolve().parents[0]


class CLIController:
"""
Class that controls all the Command Line interface application
"""

default_template_file = """
<html>
<head>
<title>{{title}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello Bulma!</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<style>
h1 {
font-size: 2em;
}
</style>
</head>
<body>
<section class="section">
<div class="container">
{{content|safe}}
</div>
</section>
</body>
</html>
"""

default_index = """# Welcome to Blask!
This is your `index.md` file, located at `posts` directory. Edit this file to add your own index. You can use Markdown to write it!
default_template_file = str(LIB_DIR / 'index_template.html')

Blask is currently under development, and we have a lot of things to do.
default_index = str(LIB_DIR / 'markdown_template.md')

Wanna help us?
Check [this project at GitHub](https://github.com/zerasul/blask) Or see the documentation in the [project web page](https://getblask.com/docs).
"""
settings = str(LIB_DIR / 'default_env.env')

settings = """
# Minimal conf for Blask
FLASK_APP=main.py
not_found = str(LIB_DIR / 'default_404.md')

# Name of the Template Folder.
templateDir="templates"
# Name of the post Folder
postDir="posts"
# default name of the template file.
defaultLayout='template.html'
# Default name of the static Folder
staticDir='static'
# Title of the blog
title='Blask | A Simple Blog Engine Based on Flask'
# error handler configuration
errors = { 404 : '404' }
"""

not_found = "# 404\n Page not found"
docker_template = str(LIB_DIR / 'Dockerfile_template')

def createdefaultindexfile(self, filepath):
"""
create a new default index file.
:param filepath: file path where the new index file is stored
"""
with open(filepath, "w") as indexfile:
indexfile.write(self.default_index)
shutil.copy(self.default_index, filepath)

def createdefaulttemplatefile(self, filepath):
"""
Create a new default template.
:param filepath: file path where the new template file is stored.
"""
with open(filepath, "w") as templatefile:
templatefile.write(self.default_template_file)

return True
shutil.copy(self.default_template_file, filepath)

def createsettingsfile(self):
"""
Create a new settings file
"""
with open(path.join(getcwd(), ".env"), "w") as settingsFile:
settingsFile.write(self.settings)
shutil.copy(self.settings, '.env')

def createnotfoundpage(self, filepath):
"""
Create a new page not found file.
:param filepath: file path where the page not found is stored
"""
with open(path.join(filepath, "404.md"), "w") as page:
page.write(self.not_found)
shutil.copy(self.not_found, filepath)

def createdockerfile(self, filepath):
shutil.copy(self.docker_template, filepath)


blask = BlaskApp()
Expand All @@ -141,35 +92,45 @@ def blaskcli():


@blaskcli.command(help="Run the instance of blask")
@click.option("--debug", default=False, help="Init with de debug flag")
@click.option("--port", default=5000, help="Port where the server is listening")
def run(debug, port):
@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(
"--host", default="127.0.0.1", help="Default Network interface listening")
def run(debug, port, host):
"""
Run the current blask instance
:param debug: initialice with debug options
:param port: port where the port is opened
"""
blask.run(debug=debug, port=port)
blask.run(debug=debug, port=port, host=host)


@blaskcli.command(help="Initialize a new Blask Project")
def init():
@click.option(
"--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.
"""
click.echo("Initializing new Blask Project")
click.echo("Using default Settings")
postdir = path.basename(path.dirname(str(blasksettings.DEFAULT_SETTINGS["postDir"] + "/")))
postdir = path.basename(
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.createsettingsfile() # creates a sample settings file
cliController.createnotfoundpage(postdir) # creates a 404 page
cliController.createdefaulttemplatefile(
path.join(templatedir, "template.html"))
cliController.createsettingsfile()
cliController.createnotfoundpage(path.join(postdir, '404.md'))
if with_docker:
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
14 changes: 7 additions & 7 deletions Blask/blasksettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@
"defaultLayout": str("template.html"),
"staticDir": str(BASE_DIR / "static"),
"title": "Blask | A Simple Blog Engine Based on Flask",
"errors": {
404 : "404"} # Dictionary with errors handler
"errors": {404: "404"} # Dictionary with errors handler
}


Expand All @@ -43,10 +42,10 @@ class BlaskSettings(object):

def __init__(self, *args, **kwargs):
"""
Initialice the Blask Settigns. First, look for the BLASK_SETTINGS enviroment variable
and try to load the module.
If there is not environment variable, try to load the current settings from the
default values.
Initialice the Blask Settigns. First, look for the BLASK_SETTINGS
enviroment variable and try to load the module.
If there is not environment variable, try to load the current settings
from the default values.
:param args:
:param kwargs:
"""
Expand All @@ -55,7 +54,8 @@ def __init__(self, *args, **kwargs):
# add current Dir to Path
path.append(os.getcwd())
# Load settings from the module in environment variable
settings_mod = import_module(os.environ["BLASK_SETTINGS"], os.environ["BLASK_SETTINGS"])
settings_mod = import_module(
os.environ["BLASK_SETTINGS"], os.environ["BLASK_SETTINGS"])

self.settings = {}
for key in DEFAULT_SETTINGS.keys():
Expand Down
Loading

0 comments on commit 120b321

Please sign in to comment.