Advertisement
Guest User

Untitled

a guest
Aug 7th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. import copy
  2.  
  3. import types
  4.  
  5.  
  6. def shield_sensitive(obj, *args):
  7. """
  8. replace all sensitive value to `******`, according to instance attribute or dict key.
  9. """
  10. try:
  11. obj_ = copy.deepcopy(obj)
  12. return _shield_sensitive(obj_, *args)
  13. except:
  14. return obj
  15.  
  16.  
  17. def _shield_sensitive(obj, *args):
  18. if isinstance(obj, dict):
  19. origin_type = type(obj)
  20. obj = dict(obj)
  21. for key in obj:
  22. if key in args:
  23. obj[key] = u'******'
  24. else:
  25. obj[key] = _shield_sensitive(obj[key], *args)
  26. obj = origin_type(obj)
  27. else:
  28. for type_ in dir(types):
  29. # shouldn't use `type(obj) == type_` because type_ is a string,
  30. # it will equal false.
  31. if type(obj) == getattr(types, type_):
  32. return obj
  33. for attr in dir(obj):
  34. if attr.startswith('_'):
  35. continue
  36. if attr in args:
  37. setattr(obj, attr, u'******')
  38. else:
  39. setattr(obj, attr, _shield_sensitive(getattr(obj, attr), *args))
  40. return obj
  41.  
  42.  
  43. if __name__ == '__main__':
  44. a = {
  45. 'username': '123',
  46. 'password': 'abc',
  47. }
  48. print shield_sensitive(a, 'password')
  49. # {'username': '123', 'password': u'******'}
  50.  
  51. class A(object):
  52. def __init__(self):
  53. self.password = ''
  54. self.username = ''
  55.  
  56. def __str__(self):
  57. return str(self.__dict__)
  58.  
  59.  
  60. print shield_sensitive(A(), 'password')
  61. # {'username': '', 'password': u'******'}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement