flaschengeist/flaschengeist/app.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

100 lines
3.1 KiB
Python
Raw Normal View History

import pkg_resources
from flask import Flask, current_app
from flask_cors import CORS
from datetime import datetime
from flask.json import JSONEncoder, jsonify
from werkzeug.exceptions import HTTPException
from . import logger
from .plugins import AuthPlugin
from flaschengeist.config import config, configure_app
from flaschengeist.controller import roleController
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()
2020-10-20 15:53:29 +00:00
# Check if iterable
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
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))
plugin = None
if entry_point.name in config and config[entry_point.name].get("enabled", False):
plugin = entry_point.load()(config[entry_point.name])
if plugin.blueprint:
app.register_blueprint(plugin.blueprint)
logger.info("Load plugin >{}<".format(entry_point.name))
if isinstance(plugin, AuthPlugin):
logger.debug("Found authentication plugin: %s", entry_point.name)
if entry_point.name == config["FLASCHENGEIST"]["auth"]:
app.config["FG_AUTH_BACKEND"] = plugin
else:
del plugin
else:
app.config["FG_PLUGINS"][entry_point.name] = plugin
if "FG_AUTH_BACKEND" not in app.config:
logger.error("No authentication plugin configured or authentication plugin not found")
def install_all():
from flaschengeist.database import db
db.create_all()
db.session.commit()
for name, plugin in current_app.config["FG_PLUGINS"].items():
if not plugin:
logger.debug("Skip disabled plugin {}".format(name))
continue
logger.info("Install plugin {}".format(name))
plugin.install()
if plugin.permissions:
2020-10-20 17:34:14 +00:00
roleController.create_permissions(plugin.permissions)
def create_app():
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
CORS(app)
with app.app_context():
from flaschengeist.database import db
configure_app(app)
db.init_app(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