Created
August 7, 2017 01:55
-
-
Save toaco/c17e4e5ee7132dbdbabd620b618066a9 to your computer and use it in GitHub Desktop.
Replace all sensitive value to `******`, according to instance attribute or dict key.
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
import copy | |
import types | |
def shield_sensitive(obj, *args): | |
""" | |
replace all sensitive value to `******`, according to instance attribute or dict key. | |
""" | |
try: | |
obj_ = copy.deepcopy(obj) | |
return _shield_sensitive(obj_, *args) | |
except: | |
return obj | |
def _shield_sensitive(obj, *args): | |
if isinstance(obj, dict): | |
origin_type = type(obj) | |
obj = dict(obj) | |
for key in obj: | |
if key in args: | |
obj[key] = u'******' | |
else: | |
obj[key] = _shield_sensitive(obj[key], *args) | |
obj = origin_type(obj) | |
else: | |
for type_ in dir(types): | |
# shouldn't use `type(obj) == type_` because type_ is a string, | |
# it will equal false. | |
if type(obj) == getattr(types, type_): | |
return obj | |
for attr in dir(obj): | |
if attr.startswith('_'): | |
continue | |
if attr in args: | |
setattr(obj, attr, u'******') | |
else: | |
setattr(obj, attr, _shield_sensitive(getattr(obj, attr), *args)) | |
return obj | |
if __name__ == '__main__': | |
a = { | |
'username': '123', | |
'password': 'abc', | |
} | |
print shield_sensitive(a, 'password') | |
# {'username': '123', 'password': u'******'} | |
class A(object): | |
def __init__(self): | |
self.password = '' | |
self.username = '' | |
def __str__(self): | |
return str(self.__dict__) | |
print shield_sensitive(A(), 'password') | |
# {'username': '', 'password': u'******'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment