I am following a guide that specifies how to manage different configurations (DB_URI, LOGGER_NAME, etc...) per development environments.
I create a config
module that is structured like this
\my_project\config\__init__.py
import os
import sys
from . import settings
# create settings object corresponding to specified env
APP_ENV = os.environ.get('APP_ENV', 'Dev')
_current_config = vars(setting).get(f'{APP_ENV}Config')
# copy attributes to the module for convenience
for atr in [f for f in dir(_current_config) if '__' not in f]:
# environment can override anything
val = os.environ.get(atr, getattr(_current_config, atr))
setattr(sys.modules[__name__], atr, val)
\my_project\config\settings.py
class BaseConfig:
DEBUG = True
LOGGER_NAME = 'my_app'
class DevConfig(BaseConfig):
# In actuality calling a function that fetches a secret
SQLALCHEMY_DATABASE_URI = 'sqlite://user.db'
class ProductionConfig(BaseConfig):
DEBUG = False
# In actuality calling a function that fetches a secret
SQLALCHEMY_DATABASE_URI = 'sqlite://user.db'
calling the config
application.py
import config
config.SQLALCHEMY_DATABASE_URI
This approach is kind of a hit and miss for me.
on one hand it allows me to easily specify several environments (dev, stage, prod, dev) without having a complex if else
logic in my settings.py
.
On the other hand I dont like using setattr
on sys.modules[__name__]
, seems a bit wonky to me. what do you think ?
1 Answer 1
Incase you are using Docker for deployment. The required environment variable can be configured as Kuberenetes configuration and it reads based on the deployment configuration environment.
-
2\$\begingroup\$ Welcome to CodeReview@SE. Not all questions should be answered here, see How do I write a Good Answer? \$\endgroup\$greybeard– greybeard2020年02月23日 17:43:36 +00:00Commented Feb 23, 2020 at 17:43
-
1\$\begingroup\$ thanks for the help, but my question is about python configuration. As I dont use docker at the moment \$\endgroup\$moshevi– moshevi2020年02月24日 10:13:54 +00:00Commented Feb 24, 2020 at 10:13
Explore related questions
See similar questions with these tags.