flaschengeist/flaschengeist/config.py

69 lines
2.5 KiB
Python

import os
import toml
import logging.config
import collections.abc
from pathlib import Path
from werkzeug.middleware.proxy_fix import ProxyFix
from flaschengeist import _module_path, logger
def __update(d, u):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = __update(d.get(k, {}), v)
else:
d[k] = v
return d
# Default config:
config = {}
__paths = [_module_path, Path.home() / ".config"]
if "FLASCHENGEIST_CONF" in os.environ:
__paths.append(Path(os.environ.get("FLASCHENGEIST_CONF")))
for loc in __paths:
try:
with (loc / "flaschengeist.toml").open() as source:
logger.info("Reading config file from >{}<".format(loc))
__update(config, toml.load(source))
except IOError:
pass
# Always enable this builtin plugins!
__update(config, {"auth": {"enabled": True}, "roles": {"enabled": True}, "users": {"enabled": True}})
def configure_app(app):
logger_config = toml.load(_module_path / "logging.toml")
if "LOGGING" in config:
if "level" in config["LOGGING"]:
logger_config["loggers"]["flaschengeist"] = {"level": config["LOGGING"]["level"]}
if "file" in config["LOGGING"]:
logger_config["root"]["handlers"].append("file")
logger_config["handlers"]["file"]["filename"] = config["LOGGING"]["file"]
path = Path(config["LOGGING"]["file"])
path.parent.mkdir(parents=True, exist_ok=True)
logging.config.dictConfig(logger_config)
if "secret_key" not in config["FLASCHENGEIST"]:
logger.warn("No secret key was configured, please configure one for production systems!")
app.config["SECRET_KEY"] = "0a657b97ef546da90b2db91862ad4e29"
else:
app.config["SECRET_KEY"] = config["FLASCHENGEIST"]["secret_key"]
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://{user}:{passwd}@{host}/{database}".format(
user=config["DATABASE"]["user"],
passwd=config["DATABASE"]["password"],
host=config["DATABASE"]["host"],
database=config["DATABASE"]["database"],
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
if "root" in config["FLASCHENGEIST"]:
logger.debug("Setting application root to >{}<".format(config["FLASCHENGEIST"]["root"]))
app.config["APPLICATION_ROOT"] = config["FLASCHENGEIST"]["root"]
if config["FLASCHENGEIST"].get("proxy", False):
logger.debug("Fixing wsgi_app for using behind a proxy server")
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)