Last active
August 29, 2015 14:27
-
-
Save Markbnj/84c5d9a4c311f228a9a1 to your computer and use it in GitHub Desktop.
Environment-specific settings for python 2 modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Environment-specific settings for python 2 modules | |
# This code placed in __init__.py will allow a module to maintain | |
# environment-specific settings in files located in a settings folder | |
# within the module. | |
# | |
# Example: | |
# | |
# ├── mymodule.py | |
# ├── __init__.py | |
# └── settings | |
# ├── __init__.py <== code below goes here | |
# ├── mymodule.default.py | |
# ├── mymodule.test.py | |
# └── mymodule.prod.py | |
# | |
# Use: | |
# | |
# mymodule.default.py | |
# | |
# MY_SETTING = "Hello" | |
# | |
# mymodule.test.py | |
# | |
# MY_SETTING = "Goodbye" | |
# | |
# mymodule.py | |
# | |
# import settings | |
# print settings.MY_SETTING | |
# | |
# The above will print "Hello" when the environment is set to | |
# 'test' and "Goodbye" when it is set to 'dev' or is not set. | |
import os | |
import inspect | |
# The code expects the environment name in an environment var | |
# named 'ENV' which can be changed here. The value of this | |
# var will be used to complete settings file names below. It | |
# can be any string, and the default is 'dev' | |
ENV = os.environ.get('ENV', 'dev') | |
# Determine the file that imported us | |
caller = inspect.currentframe().f_back.f_code.co_filename | |
caller = os.path.basename(caller).replace('.py','') | |
# Collect objects here | |
__namespace = {} | |
# Load the defaults for the caller. The defaults are expected | |
# to be in settings/<mod name>.default.py | |
__mod_dir = os.path.dirname(__file__) | |
__mod_name = '{}.default.py'.format(caller) | |
__mod_file = '{}/{}'.format(__mod_dir, __mod_name) | |
try: | |
execfile(__mod_file, __namespace) | |
except Exception as e: | |
raise Exception("Failed to load default settings from: '{}'.".format(__mod_file), e) | |
# Now load the env-specific settings for the caller if present | |
__mod_name = '{}.{}.py'.format(caller, ENV) | |
__mod_file = '{}/{}'.format(__mod_dir, __mod_name) | |
if os.path.isfile(__mod_file): | |
try: | |
execfile(__mod_file, __namespace) | |
except Exception as e: | |
raise Exception("Failed to load settings from: '{}'.".format(__mod_file), e) | |
# Update the namespace | |
globals().update(__namespace) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment