Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 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='db' user='user'" \
  15.                             " host='ps.xxxxxxx.com' password='xxxxxxxxxxxxxx'")
  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.         get_ib_level(level, parent_account_id, parent_parent_id, count, list)
  36.     elif list[count].get('parent_id') is None:
  37.         return level
  38.  
  39. start_count = 0
  40.  
  41. for data_dict[start_count] in data_dict:
  42.     if data_dict[start_count].get('parent_id') is None:
  43.         ib_level = 0
  44.         data_dict[start_count].update({'IB_level': ib_level})
  45.         print('IB level 0:\n')
  46.         print(data_dict[start_count])
  47.     elif isinstance(data_dict[start_count].get('parent_id'), int):
  48.         ib_level = get_ib_level(
  49.             0,
  50.             data_dict[start_count].get('account_id'),
  51.             data_dict[start_count].get('parent_id'),
  52.             start_count,
  53.             data_dict
  54.         )
  55.         data_dict[start_count].update({'IB_level': ib_level})
  56.         print('IB level 1:\n')
  57.         print(data_dict[start_count])
  58.     start_count = start_count + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement