improve config

This commit is contained in:
vincent 2021-05-26 13:55:22 +02:00
parent b500711540
commit d91d0b398c
3 changed files with 73 additions and 12 deletions

View File

@ -1,18 +1,32 @@
""" flask apps initialisation """
import logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask
from pony.flask import Pony
from ITPlanning.api import api
from ITPlanning.db import init_database, release_database
#from ITPlanning.frontend import frontend
from ITPlanning.config import IniConfig
logger = logging.getLogger("ITPlanning")
logger = logging.getLogger(__name__)
def create_app():
app=Flask(__name__, static_folder= "static",template_folder="view")
app.config.from_object("ITPlanning.config.DefaultConfig")
app.register_blueprint(api, url_prefix="/api/v1")
#app.register_blueprint(frontend)
"""Flask app creation"""
app = Flask(__name__, static_folder="static", template_folder="view")
config = IniConfig()
app.config.from_object(config)
# set logger
logfile = app.config["LOG"]["log_file"]
if logfile:
handler = TimedRotatingFileHandler(logfile, when="midnight")
handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
)
logger.addHandler(handler)
loglevel = app.config["LOG"]["log_level"]
if loglevel:
logger.setLevel(getattr(logging, loglevel.upper(), logging.NOTSET))
# Initialize database
logger.warning(app.config["BASE"]["database_uri"])

View File

@ -2,26 +2,71 @@
from os import makedirs, path
import tempfile
from configparser import RawConfigParser
current_config = None
class DefaultConfig:
DEBUG = False
SECRET_KEY="toto"
tempdir= path.join(tempfile.gettempdir(), "ITPlanning")
SECRET_KEY = "toto"
LOG = {
"log_file": None,
"log_level": "WARNING",
}
tempdir = path.join(tempfile.gettempdir(), "ITPlanning")
BASE = {
"database_uri": "sqlite:///" + path.join(tempdir, "ITPlanning.db"),
}
}
def __init__(self):
if not path.exists(self.tempdir):
makedirs(self.tempdir)
current_config = self
class IniConfig(DefaultConfig):
common_paths = [
"/etc/ITPlanning",
"c:/programData/ITplanning/ITplanning.conf",
path.expanduser("~/.ITPlanning"),
path.expanduser("~/.config/ITPlanning/ITPlanning.conf"),
"ITPlanning.conf",
]
def __init__(self, paths=None):
super()
if not paths:
paths = self.common_paths
parser = RawConfigParser()
parser.read(paths)
for section in parser.sections():
options = {k: self.__try_parse(v) for k, v in parser.items(section)}
section = section.upper()
if hasattr(self, section):
getattr(self, section).update(options)
else:
setattr(self, section, options)
def __try_parse(self, value):
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
lv = value.lower()
if lv in ("yes", "true", "on"):
return True
if lv in ("no", "false", "off"):
return False
return value
def get_current_config():
if current_config is None:
DefaultConfig()
return current_config
return current_config

8
run.py
View File

@ -1,5 +1,7 @@
import os
from ITPlanning.app import create_app
app= create_app()
if __name__ == '__main__':
app = create_app()
if __name__ == "__main__":
os.environ["FLASK_ENV"] = "development"
app.run()