fmartingr.com-legacy/fmartingrcom/__init__.py

67 lines
1.9 KiB
Python

# -*- coding: utf-8 -*-
from datetime import datetime
import importlib
from flask import Flask, make_response, render_template, url_for
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from . import conf
def get_theme_folder(folder):
return 'themes/{}/{}'.format(conf.THEME, folder)
app = Flask(__name__)
app.debug = conf.DEBUG
app.secret_key = conf.SECRET_KEY
app.static_folder = get_theme_folder(conf.STATIC_FOLDER)
app.template_folder = get_theme_folder(conf.TEMPLATE_FOLDER)
app.config['cdn_domain'] = conf.CDN_DOMAIN
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = conf.DATABASE_PATH
db = SQLAlchemy(app)
# Enable admin if set in the conf
if conf.ENABLE_ADMIN:
admin = Admin(app, name='fmartingrcom', template_mode='bootstrap3')
# Method to register admin models
def register_admin_model(model):
admin.add_view(ModelView(model, db.session))
# Autoload enabled blueprints
for blueprint in conf.BLUEPRINTS:
module = importlib.import_module(
'.apps.{}'.format(blueprint),
package=__name__)
app.register_blueprint(getattr(module, blueprint))
@app.errorhandler(500)
def internal_server_error(error):
app.logger.error(error)
return make_response(render_template('errors/500.html'), 500)
@app.context_processor
def global_context():
return {'current_year': datetime.now().strftime('%Y') }
# Patch url_for to use a CDN_DOMAIN if needed
def patch_url_for(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
cdn_domain = app.config.get('cdn_domain', None)
try:
rewrite_path = result.split('/')[1] in conf.CDN_PATHS
except IndexError:
rewrite_path = False
if cdn_domain and rewrite_path:
return '{}{}'.format(cdn_domain, result)
return result
return wrapper
app.jinja_env.globals['url_for'] = patch_url_for(url_for)