Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. # Prereq.
  2. # sudo apt-get install libpq-dev
  3. # sudo pip3 install psycopg2
  4.  
  5. # -*- coding: utf-8 -*-
  6.  
  7. import psycopg2
  8. import psycopg2.extras
  9.  
  10. sql = "select * from accounts"
  11.  
  12.  
  13. try:
  14.     conn = psycopg2.connect("dbname='хххххххх' user='ххххххххххх'" \
  15.                             " host='хххххххххххх' password='ххххххххххххх'")
  16. except psycopg2.Error as err:
  17.     print("Connection error: {}".format(err))
  18.  
  19. try:
  20.     cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
  21.     cur.execute(sql)
  22.     data = cur.fetchall()
  23. except psycopg2.Error as err:
  24.     print("Query error: {}".format(err))
  25.  
  26. data_dict = []
  27. for row in data:
  28.     data_dict.append(dict(row))
  29.  
  30.  
  31. def get_ib_level(level, account_id, parent_id, count, list):
  32.     if isinstance(list[count].get('parent_id'), int):
  33.         parent_account_id = any((t_dict.get['account_id'] == parent_id and t_dict.get['parent_id'] == account_id) for t_dict in list)
  34.         parent_parent_id = any((t_dict.get['parent_id'] == account_id and t_dict.get['account_id'] == parent_id) for t_dict in list)
  35.         level += 1
  36.         get_ib_level(level, parent_account_id, parent_parent_id, count, list)
  37.     elif list[count].get('parent_id') is None:
  38.         return level
  39.  
  40. start_count = 0
  41.  
  42. for data_dict[start_count] in data_dict:
  43.     if data_dict[start_count].get('parent_id') is None:
  44.         ib_level = 0
  45.         data_dict[start_count].update({'IB_level': ib_level})
  46.         print('IB level 0:\n')
  47.         print(data_dict[start_count])
  48.     elif isinstance(data_dict[start_count].get('parent_id'), int):
  49.         ib_level = get_ib_level(
  50.             0,
  51.             data_dict[start_count].get('account_id'),
  52.             data_dict[start_count].get('parent_id'),
  53.             start_count,
  54.             data_dict
  55.         )
  56.         data_dict[start_count].update({'IB_level': ib_level})
  57.         print('IB level 1:\n')
  58.         print(data_dict[start_count])
  59.     start_count = start_count + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement