Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 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='xxxxx' user='xxxxx'" \
  15.                             " host='ps.xxxxx.com' password='xxxxxxxx'")
  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_parent_id(a_id):
  32.     for dct in data_dict:
  33.         if dct['account_id'] == a_id:
  34.             return dct['parent_id']
  35.  
  36.  
  37. def get_ib_level(level, account_id, parent_id):
  38.     if isinstance(parent_id, int):
  39.         next_account_id = parent_id
  40.         next_parent_id = get_parent_id(next_account_id)
  41.         print('%s;%s;%s' % (level, next_account_id, next_parent_id))
  42.         level += 1
  43.         level = get_ib_level(level, account_id, next_parent_id)
  44.         return level
  45.     elif parent_id == 'None':
  46.         return 0
  47.  
  48. start_count = 0
  49.  
  50. for data_dict[start_count] in data_dict:
  51.     if data_dict[start_count].get('parent_id') is None:
  52.         ib_level = 0
  53.         data_dict[start_count].update({'IB_level': ib_level})
  54.         print('IB level: 0 - %s \n' % data_dict[start_count].get('ib_number'))
  55.     elif isinstance(data_dict[start_count].get('parent_id'), int):
  56.         ib_level = get_ib_level(
  57.             0,
  58.             data_dict[start_count].get('account_id'),
  59.             data_dict[start_count].get('parent_id')
  60.         )
  61.         data_dict[start_count].update({'IB_level': ib_level})
  62.         print('IB level : %s1 \n' % ib_level)
  63.     start_count = start_count + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement