From fd22103df87f3d1d90856092638a80f6b53d1bf6 Mon Sep 17 00:00:00 2001 From: Timur Demin Date: Fri, 27 Dec 2019 20:22:47 +0500 Subject: [PATCH] Refactor configuration-related code --- project_amber/app.py | 7 ++--- project_amber/config.py | 43 +++++++++++++++++-------------- project_amber/handlers/misc.py | 5 +--- project_amber/handlers/session.py | 2 +- project_amber/handlers/users.py | 5 +--- project_amber/logging.py | 6 +++-- 6 files changed, 35 insertions(+), 33 deletions(-) diff --git a/project_amber/app.py b/project_amber/app.py index d2076e4..d7068a8 100644 --- a/project_amber/app.py +++ b/project_amber/app.py @@ -15,14 +15,15 @@ from project_amber.handlers.users import user_handlers as user app = Flask(__name__) -app.config["SQLALCHEMY_DATABASE_URI"] = config["database"] +app.config["SQLALCHEMY_DATABASE_URI"] = config.database db.init_app(app) -CORS(app, resources={r"/*": {"origins": config["domain"]}}) +CORS(app, resources={r"/*": {"origins": config.domain}}) @app.before_request def middleware(): - if check_request().authenticated: request.user = handleLogin() + if check_request().authenticated: + request.user = handleLogin() for blueprint in (auth, session, misc, task, user): diff --git a/project_amber/config.py b/project_amber/config.py index 5747313..a00f349 100644 --- a/project_amber/config.py +++ b/project_amber/config.py @@ -1,15 +1,20 @@ import os +import sys from json import load -if os.name == "posix": - configPaths = ["./config.json", "/etc/amber.json"] -else: - configPaths = ["config.json"] +class Config: + database: str = "" + loglevel: int = 0 + allow_signup: bool = False + domain: str = "*" + +config = Config() -config = {"database": "", "loglevel": 0, "allow_signup": False, "domain": "*"} +configPaths = ["config.json"] +if os.name == "posix": + configPaths.append("/etc/amber.json") -# search for every file name and load the config from the first file -# that exists +# search for every file name and load the config from the first file that exists for testedFileName in configPaths: if os.path.isfile(testedFileName): # holds the actual config file name @@ -17,7 +22,7 @@ break if not "configFileName" in globals(): print("No configuration file found, exiting") - exit(1) + sys.exit(1) try: with open(configFileName, encoding="utf8") as configFile: @@ -27,11 +32,11 @@ except OSError as ioerr: print("Could not open config file", configFileName) print(ioerr.strerror) - exit(1) + sys.exit(1) -for entry in config: +for entry in vars(config): if entry in loadedConfig: - config[entry] = loadedConfig[entry] + setattr(config, entry, loadedConfig[entry]) def string_to_bool(val: str) -> bool: @@ -50,16 +55,16 @@ def string_to_bool(val: str) -> bool: # tuple is the environment variable itself, the second is the corresponding # `config` key, and the third one is the function to convert the possible values for mapping in ( - ("AMBER_DATABASE", "database", lambda val: val), # str -> str - # pylint: disable=unnecessary-lambda - ("AMBER_LOGLEVEL", "loglevel", lambda val: int(val)), # str -> int - ("AMBER_ALLOW_SIGNUP", "allow_signup", string_to_bool), # str -> bool - ("AMBER_DOMAIN", "domain", lambda val: val) # str -> str + ("AMBER_DATABASE", "database", lambda val: val), # str -> str + # pylint: disable=unnecessary-lambda + ("AMBER_LOGLEVEL", "loglevel", lambda val: int(val)), # str -> int + ("AMBER_ALLOW_SIGNUP", "allow_signup", string_to_bool), # str -> bool + ("AMBER_DOMAIN", "domain", lambda val: val) # str -> str ): env_value = os.getenv(mapping[0]) if not env_value is None: - config[mapping[1]] = mapping[2](env_value) + setattr(config, mapping[1], mapping[2](env_value)) -if config["database"] == "": +if not config.database: print("No database specified. Exiting.") - exit(1) + sys.exit(1) diff --git a/project_amber/handlers/misc.py b/project_amber/handlers/misc.py index 1db70b1..4f06135 100644 --- a/project_amber/handlers/misc.py +++ b/project_amber/handlers/misc.py @@ -6,12 +6,9 @@ from project_amber.const import VERSION from project_amber.handlers.const import API_VERSION, API_SIGNUP -signup_allowed = False -if config["allow_signup"]: signup_allowed = True - misc_handlers = Blueprint("misc_handlers", __name__) @misc_handlers.route("/version", methods=["GET"]) def version(): - return dumps({API_VERSION: VERSION, API_SIGNUP: signup_allowed}) + return dumps({API_VERSION: VERSION, API_SIGNUP: config.allow_signup}) diff --git a/project_amber/handlers/session.py b/project_amber/handlers/session.py index a2959a1..2bf46f2 100644 --- a/project_amber/handlers/session.py +++ b/project_amber/handlers/session.py @@ -13,7 +13,7 @@ @session_handlers.route("/session", methods=["GET"]) -def session(): +def get_sessions(): """ Request handler for `/api/session`. Only accepts GET requests. Returns a list of sessions like the one below: diff --git a/project_amber/handlers/users.py b/project_amber/handlers/users.py index 5d3eb1a..ee57eda 100644 --- a/project_amber/handlers/users.py +++ b/project_amber/handlers/users.py @@ -8,9 +8,6 @@ user_handlers = Blueprint("user_handlers", __name__) -signup_allowed = False -if config["allow_signup"]: signup_allowed = True - @user_handlers.route("/user", methods=["PATCH"]) def user_data(): @@ -41,7 +38,7 @@ def signup(): Returns HTTP 200 with empty JSON on success, 400 on missing params, 403 if the method is disabled by a config parameter. """ - if not signup_allowed: + if not config.allow_signup: raise Forbidden(MSG_SIGNUP_FORBIDDEN) if not API_USER in request.json or not API_PASSWORD in request.json: raise BadRequest(MSG_MISSING_AUTH_INFO) diff --git a/project_amber/logging.py b/project_amber/logging.py index 9ea40fc..ea98eed 100644 --- a/project_amber/logging.py +++ b/project_amber/logging.py @@ -3,8 +3,10 @@ from project_amber.config import config level = logging.INFO -if config["loglevel"] == 0: level = logging.ERROR -if config["loglevel"] == 1: level = logging.WARN +if config.loglevel == 0: + level = logging.ERROR +if config.loglevel == 1: + level = logging.WARN logging.basicConfig(level=level) logger = logging.getLogger("amber_backend")