From 71e7433040c41d17772e7a2f2ad37a9705b94038 Mon Sep 17 00:00:00 2001 From: Rodolphe Breard Date: Sun, 4 Feb 2018 11:15:02 +0100 Subject: [PATCH] Parse environment variables with boolean values Simply using bool() on the string returns True for every non-empty string. Hence, the only way to set a value to False is to set it the an empty string, which is counter-intuitive. This commit will instead compare the string to well-known values for True and return accordingly. Every other non-empty string is evaluated to False. Empty string are evaluated to the default value. --- khaganat/settings.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/khaganat/settings.py b/khaganat/settings.py index 756e55e..e64c3e3 100644 --- a/khaganat/settings.py +++ b/khaganat/settings.py @@ -14,6 +14,14 @@ from django.utils.translation import gettext_lazy as _ from django.urls import reverse_lazy import os + +def get_config_bool(env_name, default=False): + val = os.getenv(env_name, default='').lower() + if val == '': + return default + return val in ('true', '1', 't', 'y', 'yes') + + # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -25,7 +33,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('KHAGANAT_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! -DEBUG = bool(os.getenv('KHAGANAT_DEBUG', default='')) +DEBUG = get_config_bool('KHAGANAT_DEBUG', default=False) ALLOWED_HOSTS = [ _ for _ in os.getenv('KHAGANAT_HOSTNAMES', default='').split(',') @@ -102,7 +110,10 @@ EMAIL_HOST_PASSWORD = os.getenv('KHAGANAT_EMAIL_HOST_PASSWORD', default='') EMAIL_USE_TLS = os.getenv('KHAGANAT_EMAIL_USE_TLS', default='') EMAIL_SUBJECT_PREFIX = os.getenv('KHAGANAT_EMAIL_SUBJECT_PREFIX', default='') -DEFAULT_FROM_EMAIL = os.getenv('KHAGANAT_DEFAULT_FROM_EMAIL', default='no-reply@localhost') +DEFAULT_FROM_EMAIL = os.getenv( + 'KHAGANAT_DEFAULT_FROM_EMAIL', + default='no-reply@localhost' +) # User model @@ -110,8 +121,13 @@ DEFAULT_FROM_EMAIL = os.getenv('KHAGANAT_DEFAULT_FROM_EMAIL', default='no-reply@ AUTH_USER_MODEL = 'neluser.NelUser' LOGIN_URL = os.getenv('KHAGANAT_LOGIN_URL', default='/account/login/') -LOGIN_REDIRECT_URL = reverse_lazy(os.getenv('KHAGANAT_LOGIN_REDIRECT_URL', default='index')) -REGISTER_REQUIRE_VALIDATION = bool(os.getenv('KHAGANAT_REGISTER_REQUIRE_VALIDATION', default='True')) +LOGIN_REDIRECT_URL = reverse_lazy( + os.getenv('KHAGANAT_LOGIN_REDIRECT_URL', default='index') +) +REGISTER_REQUIRE_VALIDATION = get_config_bool( + 'KHAGANAT_REGISTER_REQUIRE_VALIDATION', + default=True +) # Password validation