Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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'******'}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement