Advertisement
kAldown

Untitled

Jun 19th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.75 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from datetime import date, datetime
  4. from collections import defaultdict
  5. import re
  6. from json import dumps as json_dumps
  7.  
  8. from dateutil.relativedelta import relativedelta
  9. from sqlalchemy import create_engine
  10. from sqlalchemy.sql import text
  11. from psycopg2.extras import execute_values
  12.  
  13.  
  14. ITEMS_VALUES = 'items'
  15. COMPLEX_NUM = 'complex_num'
  16. NODES_HEALTH = 'nodes_health'
  17. CONNECTORS_VALUES = 'connectors_values'
  18. TIMESTAMP = 'date_create'
  19.  
  20. LINE = (r'^(?P<date_create>0\d{10})'
  21.        '(?P<complex_num>\d{2})'
  22.        '(?P<items>\d{6})'
  23.        '(?P<nodes_health>\d{5})'
  24.        '.{10}'
  25.        '(?P<connectors_values>\d{11})$'
  26. )
  27. matcher = re.compile(LINE)
  28.  
  29.  
  30. def timestamp_to_date(timestamp):
  31.     return datetime.fromtimestamp(
  32.                 int(timestamp)
  33.             ).strftime('%Y-%m-%d')
  34.  
  35.    
  36. def get_3_months_back_in_days():
  37.     """ returns 3s month back days count according today
  38.    """
  39.     today = date.today()
  40.     back_then = today + relativedelta(months=-3)
  41.     return (today - back_then).days
  42.  
  43.  
  44. def parse_line():
  45.     """ parse income line
  46.    позиции 1 - 11 - unix timestamp (первый символ ноль)
  47.    позиции 12 - 13 - номер комплекса
  48.    позиции 14 - 19 - состояние оборудования, каждая цифра отвечает за
  49.    отдельное
  50.    устройство (значения 0 - 9)
  51.    позиции 20 - 24 - характеристики основных узлов комплекса (не является
  52.    целевым
  53.    устройством) (значения 0, 1)
  54.    позиции 35 - 45 - состояние коннекторов (не является целевым устройством)
  55.    """
  56.     pass
  57.  
  58.  
  59. def unpack_values(data, key):
  60.     d = defaultdict(set)
  61.  
  62.     for item_ind, item_val in enumerate(data[key]):
  63.         d[item_ind].add(int(item_val))
  64.  
  65.     return d
  66.  
  67.  
  68. def parse(afile):
  69.     """ main entrypoint to parse whole file
  70.    """
  71.     d = defaultdict(dict)
  72.     timestamp = None
  73.  
  74.     with open(afile, 'r') as thefile:
  75.         for line in thefile:
  76.             found = matcher.match(line)
  77.             if found:
  78.                 data = found.groupdict()
  79.  
  80.                 complex_num = data[COMPLEX_NUM]
  81.                 if timestamp is None:
  82.                     timestamp = timestamp_to_date(data[TIMESTAMP])
  83.  
  84.                 for k in (NODES_HEALTH, CONNECTORS_VALUES, ITEMS_VALUES):
  85.                     d[complex_num].update({k: unpack_values(data, k)})
  86.                
  87.  
  88.     result = []
  89.     for complex_num, data in d.items():
  90.        
  91.         data.update({COMPLEX_NUM: int(complex_num)})
  92.         data.update({TIMESTAMP: timestamp})
  93.         result.append(data)
  94.     return result
  95.  
  96.  
  97. def dump_to_db(data):
  98.     conn = psycopg2.connect(dbname="omd", host="localhost",
  99.                             user="user", password="password")
  100.  
  101.     print data
  102.     with conn.cursor() as cur:
  103.        
  104.         for to_insert in data:
  105.  
  106.             cur.execute("""
  107.            INSERT INTO complex_data
  108.            (date_create, complex_num, items, nodes_health, connectors_values)
  109.            VALUES (%(date_create)s, %(complex_num)s, %(items)s,
  110.                    %(nodes_health)s, %(connectors_values)s);
  111.            """, to_insert,)
  112.  
  113.  
  114. def dump_to_db(data):
  115.     engine = create_engine('postgresql://user:password@localhost/omd')
  116.     con = engine.connect()
  117.  
  118.     SQL = text("""
  119.            INSERT INTO complex_data
  120.            (date_create, complex_num, items, nodes_health, connectors_values)
  121.            VALUES :date_create, :complex_num, :items,
  122.                   :nodes_health, :connectors_values;
  123.            """)
  124.     con.execute(SQL, **data[0])
  125.    
  126. dump_to_db(parse('test.txt'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement