public
Last active

diff_settings.py

  • Download Gist
diff_settings.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
import os
import sys
import difflib
from pprint import pformat
 
settings1 = sys.argv[1]
settings2 = sys.argv[2]
 
def get_diff_msg(first, second, fromfile='First', tofile='Second'):
"""Return a unified diff between first and second."""
# Force inputs to iterables for diffing.
# use pformat instead of str or repr to output dicts and such
# in a stable order for comparison.
if isinstance(first, (tuple, list)):
first = [pformat(d) for d in first]
elif isinstance(first, dict):
first = ["%s:%s" % (pformat(key), pformat(val)) for key,val in first.iteritems()]
else:
first = [pformat(first)]
 
if isinstance(second, (tuple, list)):
second = [pformat(d) for d in second]
elif isinstance(second, dict):
second = ["%s:%s" % (pformat(key), pformat(val)) for key,val in second.iteritems()]
else:
second = [pformat(second)]
 
diff = difflib.ndiff(first, second)
# Add line endings.
return '\n' + ''.join([d + '\n' for d in diff])
 
KEYNOTFOUND = '<KEYNOTFOUND>' # KeyNotFound for dictDiff
 
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is
not found in one fo the configs, it will be represented by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: Dict of Key => (first.val, second.val)
"""
diff = {}
# Check all keys in first dict
for key in first.keys():
if (not second.has_key(key)):
diff[key] = (first[key], KEYNOTFOUND)
elif (first[key] != second[key]):
diff[key] = (first[key], second[key])
# Check all keys in second dict to find missing
for key in second.keys():
if (not first.has_key(key)):
diff[key] = (KEYNOTFOUND, second[key])
return diff
 
 
def get_settings(conf):
settings_dict = {}
for setting in conf.settings.get_all_members():
if setting.upper() == setting and 'APPS' not in setting:
settings_dict[setting] = getattr(conf.settings, setting)
return settings_dict
 
os.environ['DJANGO_SETTINGS_MODULE'] = settings1
from django import conf
old_settings = get_settings(conf)
os.environ['DJANGO_SETTINGS_MODULE'] = settings2
reload(conf)
new_settings = get_settings(conf)
 
d = dict_diff(new_settings, old_settings)
for key, val in d.items():
print key, get_diff_msg(val[0], val[1])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.