84 lines
2.7 KiB
Python
84 lines
2.7 KiB
Python
import pkg_resources
|
|
from flask import Flask
|
|
from flask_cors import CORS
|
|
from datetime import datetime
|
|
from flask.json import JSONEncoder, jsonify
|
|
from werkzeug.exceptions import HTTPException
|
|
|
|
from . import logger
|
|
from .system.config import config, configure_app
|
|
|
|
|
|
class CustomJSONEncoder(JSONEncoder):
|
|
def default(self, o):
|
|
# Check if custom model
|
|
try:
|
|
return o.serialize()
|
|
except AttributeError:
|
|
pass
|
|
|
|
if isinstance(o, datetime):
|
|
return o.isoformat()
|
|
# Check if iterable
|
|
try:
|
|
iterable = iter(o)
|
|
except TypeError:
|
|
pass
|
|
else:
|
|
return list(iterable)
|
|
return JSONEncoder.default(self, o)
|
|
|
|
|
|
def __load_auth(app):
|
|
for entry_point in pkg_resources.iter_entry_points('flaschengeist.auth'):
|
|
logger.debug('Found authentication plugin: %s', entry_point.name)
|
|
if entry_point.name == config['FLASCHENGEIST']['AUTH']:
|
|
app.config['FG_AUTH_BACKEND'] = entry_point.load()()
|
|
app.config['FG_AUTH_BACKEND'].configure(
|
|
config[entry_point.name] if config.has_section(entry_point.name) else {})
|
|
logger.info('Loaded authentication plugin > %s <', entry_point.name)
|
|
break
|
|
if not app.config['FG_AUTH_BACKEND']:
|
|
logger.error('No authentication plugin configured or authentication plugin not found')
|
|
|
|
|
|
def __load_plugins(app):
|
|
logger.info('Search for plugins')
|
|
app.config['FG_PLUGINS'] = {}
|
|
for entry_point in pkg_resources.iter_entry_points('flaschengeist.plugin'):
|
|
logger.debug("Found plugin: >{}<".format(entry_point.name))
|
|
if config.get(entry_point.name, 'enabled', fallback=False):
|
|
logger.info("Loaded plugin >{}<".format(entry_point.name))
|
|
app.config["FG_PLUGINS"][entry_point.name] = True
|
|
app.register_blueprint(entry_point.load()())
|
|
else:
|
|
app.config["FG_PLUGINS"][entry_point.name] = False
|
|
|
|
|
|
def create_app():
|
|
app = Flask(__name__)
|
|
app.json_encoder = CustomJSONEncoder
|
|
CORS(app)
|
|
|
|
with app.app_context():
|
|
from .system.database import db
|
|
configure_app(app)
|
|
db.init_app(app)
|
|
__load_auth(app)
|
|
__load_plugins(app)
|
|
|
|
@app.route("/", methods=["GET"])
|
|
def __get_state():
|
|
from . import __version__ as version
|
|
return jsonify({"plugins": app.config["FG_PLUGINS"], "version": version})
|
|
|
|
@app.errorhandler(Exception)
|
|
def handle_exception(e):
|
|
if isinstance(e, HTTPException):
|
|
logger.debug(e.description, exc_info=True)
|
|
return jsonify({"error": e.description}), e.code
|
|
logger.error(str(e), exc_info=True)
|
|
return jsonify({"error": "Internal server error occurred"}), 500
|
|
|
|
return app
|