Author: Pedro Lucas Porcellis <pedrolucasporcellis@gmail.com>
Add date and markdown filters and improve overall app structure
core/app.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++++--- core/config.py | 2 +
diff --git a/core/app.py b/core/app.py index 7c7b61f74ac822566ca24e58945ac95b221c9a3c..4dea414b8de7d63ea323884dc788e4a5d259e830 100644 --- a/core/app.py +++ b/core/app.py @@ -1,7 +1,61 @@ -from flask import Flask +from flask import Flask, abort +from jinja2 import Markup +import locale +from core.config import read_from_config, env +from core.database import db, init_database +import mistune +import humanize +from datetime import datetime, timedelta +from dateutil import tz + +class Rascunho(Flask): + def __init__(self, *args, **kwargs): + super().__init__(__name__, *args, **kwargs) + + init_database() + + try: + # TODO: Use the locale config, from my local package it doesn't + # work as the package is out-of-date on Arch's Community Repository + humanize.i18n.activate("en_US") + locale.setlocale(locale.LC_ALL, read_from_config("locale")) + locale.setlocale(locale.LC_TIME, read_from_config("locale")) + except: + pass -app = Flask(__name__) + + from core.blueprints.basic import basic -from core.blueprints.basic import basic + self.register_blueprint(basic) -app.register_blueprint(basic) + @self.template_filter() + def human_date(d): + if not d: + return 'Nunca' + + local_tz = tz.gettz(read_from_config("timezone")) + d = d.replace(tzinfo=tz.gettz('UTC')) + local_date = d.astimezone(local_tz) + + if isinstance(d, timedelta): + return Markup('<span title="{}">{}</span>'.format( + f'{d.seconds} segundos', humanize.naturaldelta(d))) + + return Markup('<span title="{}">{}</span>'.format( + d.strftime('%Y-%m-%d %H:%M:%S UTC'), + humanize.naturaltime( + datetime.now().astimezone(local_tz) - local_date + ))) + + @self.template_filter() + def md(text): + return mistune.markdown(text) + + @self.context_processor + def inject(): + return { + "env": env + } + + +app = Rascunho() diff --git a/core/config.py b/core/config.py index 4dc0e9abcac8f8d9a2424c98a0f7026ca033f7d9..30c507fa0d04934468781a4121749e2a81f8793f 100644 --- a/core/config.py +++ b/core/config.py @@ -4,3 +4,5 @@ config = ConfigParser() config.read_file(open('config.ini')) env = config['meta']['env'] + +read_from_config = lambda key: config.get(env, key)