utils.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # -*- coding: utf-8 -*-
  2. class BinaryRelationItem(object):
  3. def __init__(self, item1, item2):
  4. self.first = item1
  5. self.second = item2
  6. def get_another(self, item):
  7. if item == self.first:
  8. return self.second
  9. if item == self.second:
  10. return self.first
  11. class BinaryRelationCollection(object):
  12. def __init__(self):
  13. self.__m_Dic = {}
  14. def update(self, item):
  15. if not self.is_exist(item):
  16. key = self.create_key(item)
  17. self.__m_Dic[key] = item
  18. def clear(self):
  19. self.__m_Dic.clear()
  20. @staticmethod
  21. def create_key(item):
  22. lis = [item.first, item.second]
  23. lis.sort()
  24. return '%s@%s' % (lis[0], lis[1])
  25. def is_exist(self, item):
  26. key = self.create_key(item)
  27. return key in self.__m_Dic
  28. def __iter__(self):
  29. return iter(self.__m_Dic)
  30. from relations import test
  31. def dic2obj(d):
  32. """Convert Dict to Object.
  33. """
  34. top = type('new', (object,), d)
  35. seqs = tuple, list, set, frozenset
  36. for i, j in d.items():
  37. j0 = j
  38. try:
  39. j0 = json.loads(j0)
  40. except Exception as e:
  41. pass
  42. if isinstance(j0, dict):
  43. setattr(top, i, dic2obj(j0))
  44. elif isinstance(j0, seqs):
  45. setattr(top, i,
  46. type(j0)(dic2obj(sj) if isinstance(sj, dict) else sj for sj in j0))
  47. else:
  48. setattr(top, i, j0)
  49. return top
  50. def sqldata2objlist(data):
  51. '''Convert Sqldata to Object list.
  52. '''
  53. return list(map(dic2obj,data))
  54. def get_dicdata(data,dic):
  55. """
  56. Request db for data through sql.
  57. Convert data to dict.
  58. :param sql:
  59. :param dic:
  60. :return:
  61. """
  62. dic_data=[dict(zip(dic,item)) for item in data]
  63. return list(dic_data)