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 """ """ flask apps initialisation """
import logging import logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask from flask import Flask
from pony.flask import Pony from pony.flask import Pony
from ITPlanning.api import api from ITPlanning.api import api
from ITPlanning.db import init_database, release_database from ITPlanning.db import init_database, release_database
#from ITPlanning.frontend import frontend #from ITPlanning.frontend import frontend
from ITPlanning.config import IniConfig
logger = logging.getLogger("ITPlanning")
logger = logging.getLogger(__name__)
def create_app(): def create_app():
app=Flask(__name__, static_folder= "static",template_folder="view") """Flask app creation"""
app.config.from_object("ITPlanning.config.DefaultConfig") app = Flask(__name__, static_folder="static", template_folder="view")
app.register_blueprint(api, url_prefix="/api/v1") config = IniConfig()
#app.register_blueprint(frontend) 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 # Initialize database
logger.warning(app.config["BASE"]["database_uri"]) logger.warning(app.config["BASE"]["database_uri"])

View File

@ -2,23 +2,68 @@
from os import makedirs, path from os import makedirs, path
import tempfile import tempfile
from configparser import RawConfigParser
current_config = None current_config = None
class DefaultConfig: class DefaultConfig:
DEBUG = False DEBUG = False
SECRET_KEY="toto" SECRET_KEY = "toto"
tempdir= path.join(tempfile.gettempdir(), "ITPlanning") LOG = {
"log_file": None,
"log_level": "WARNING",
}
tempdir = path.join(tempfile.gettempdir(), "ITPlanning")
BASE = { BASE = {
"database_uri": "sqlite:///" + path.join(tempdir, "ITPlanning.db"), "database_uri": "sqlite:///" + path.join(tempdir, "ITPlanning.db"),
} }
def __init__(self): def __init__(self):
if not path.exists(self.tempdir): if not path.exists(self.tempdir):
makedirs(self.tempdir) makedirs(self.tempdir)
current_config = self 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(): def get_current_config():

8
run.py
View File

@ -1,5 +1,7 @@
import os
from ITPlanning.app import create_app 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() app.run()