Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
Refactor configuration-related code
Browse files Browse the repository at this point in the history
  • Loading branch information
tdemin committed Dec 27, 2019
1 parent 3119a77 commit fd22103
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 33 deletions.
7 changes: 4 additions & 3 deletions project_amber/app.py
Expand Up @@ -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):
Expand Down
43 changes: 24 additions & 19 deletions project_amber/config.py
@@ -1,23 +1,28 @@
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
configFileName = testedFileName
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:
Expand All @@ -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:
Expand All @@ -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)
5 changes: 1 addition & 4 deletions project_amber/handlers/misc.py
Expand Up @@ -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})
2 changes: 1 addition & 1 deletion project_amber/handlers/session.py
Expand Up @@ -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:
Expand Down
5 changes: 1 addition & 4 deletions project_amber/handlers/users.py
Expand Up @@ -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():
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions project_amber/logging.py
Expand Up @@ -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")
Expand Down

0 comments on commit fd22103

Please sign in to comment.