Advertisement
Guest User

Untitled

a guest
Mar 18th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.35 KB | None | 0 0
  1. import os # for deleting old files
  2. import time # for sleeps
  3. import json # for configuration
  4. import dbfread # for DBF files
  5. import datetime # for getting time
  6. import psycopg2 # for database
  7. import portalocker # for file locking
  8.  
  9. # for watching changes in target directory
  10. from watchdog import observers, events
  11.  
  12.  
  13. # class for saving configuration - done
  14. class Configuration:
  15. def __init__(self):
  16. self.data_path = './data/'
  17. self.log_path = './log/'
  18. self.username = 'postgres'
  19. self.password = 'postgres'
  20. self.dbname = 'postgres'
  21. self.host = '127.0.0.1'
  22. self.count = 200
  23. self.interval = '7 days'
  24.  
  25. def read(self):
  26. try:
  27. config = json.load(open('./settings.json'))
  28. if 'data_path' in config:
  29. self.data_path = config['data_path']
  30. if 'log_path' in config:
  31. self.log_path = config['log_path']
  32. if 'username' in config:
  33. self.username = config['username']
  34. if 'password' in config:
  35. self.password = config['password']
  36. if 'host' in config:
  37. self.host = config['host']
  38. if 'dbname' in config:
  39. self.dbname = config['dbname']
  40. if 'count' in config:
  41. self.count = config['count']
  42. if 'interval' in config:
  43. self.interval = config['interval']
  44. except IOError:
  45. print "<ERROR> Can't read configuration file!"
  46.  
  47.  
  48. # class for reading and sending records - done
  49. class Data:
  50. def __init__(self, config=Configuration()):
  51. self.data = []
  52. self.config = config
  53.  
  54. def read_data(self, filename):
  55. global logger
  56. try:
  57. print "<FILE> Started a new file ..."
  58. for record in dbfread.DBF(self.config.data_path + filename):
  59. self.data.append(record)
  60. del_recs = dbfread.DBF(self.config.data_path + filename)
  61. del_recs.load()
  62. print "<FILE> Contains {} deleted records!".format(len(del_recs.deleted))
  63. logger.log("<FILE> Contains {} deleted records!".format(len(del_recs.deleted)))
  64. except:
  65. print "<ERROR> Error happened during reading file!"
  66. logger.log("<ERROR> Error happened during reading file!")
  67.  
  68. def send_data(self):
  69. global logger
  70. try:
  71. buff = []
  72. for record in self.data: # surely can change it in python 3
  73. buff.append([record["_ID"].encode('utf-8'), record["_IN"].encode('utf-8'),
  74. record["_PID"].encode('utf-8'), record["_KEY"].encode('utf-8')
  75. , record["_VAL"].encode('utf-8')])
  76. connection_settings = "dbname='{}' user='{}' host='{}' password='{}'".format(self.config.dbname,
  77. self.config.username,
  78. self.config.host,
  79. self.config.password)
  80. connection = psycopg2.connect(connection_settings)
  81. cursor = connection.cursor()
  82. args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s)", rec) for rec in buff)
  83. cursor.execute("INSERT INTO store(id, in_s, pid_s, key_s, value_s) VALUES " + args_str)
  84. connection.commit()
  85. cursor.close()
  86. connection.close()
  87. print "<FILE> {} records were inserted!".format(len(buff))
  88. logger.log("<FILE> {} records were inserted!".format(len(buff)))
  89. except:
  90. print "<ERROR> Error happened during sending data!"
  91. logger.log("<ERROR> Error happened during sending data!")
  92.  
  93.  
  94. # class for logging messages - done
  95. class Logger:
  96. def __init__(self, config):
  97. self.log_path = config.log_path
  98.  
  99. def log(self, message):
  100. try:
  101. log_name = datetime.datetime.now().date().__str__()
  102. log_file = open(self.log_path + log_name + '.txt', 'a+')
  103. log_file.write(message + '\n')
  104. log_file.close()
  105. except IOError:
  106. print "<Error> Can't open logs file!"
  107. return
  108.  
  109.  
  110. conf = Configuration()
  111. conf.read()
  112. logger = Logger(conf)
  113. print "<INFO> Settings: {}".format(conf.__dict__)
  114. logger.log("<INFO> Settings: {}".format(conf.__dict__))
  115.  
  116.  
  117. allowed_names = {
  118. "addstore.DBF",
  119. "addstore.DBF",
  120. "addstore.DBF",
  121. "addstore.DBF",
  122. "addstore.DBF",
  123. "addstore.DBF",
  124. "addstore.DBF",
  125. }
  126.  
  127.  
  128. # initial read (if files already exist) - done
  129. lock = portalocker.Lock(conf.data_path + "signal.dbf")
  130. while True:
  131. try:
  132. lock.acquire(fail_when_locked=False)
  133. break
  134. except IOError:
  135. time.sleep(1)
  136. data = Data(conf)
  137. data.read_data('addstore.dbf')
  138. data.send_data()
  139. try:
  140. os.remove(conf.data_path + 'addstore.dbf')
  141. except:
  142. print "<ERROR> No initial file!"
  143. logger.log("<ERROR> No initial file!")
  144. lock.release()
  145.  
  146.  
  147. # class for handling changes in directory - done
  148. class EventsHandler(events.FileSystemEventHandler):
  149. def on_created(self, event):
  150. global logger
  151. global conf
  152. file_name = os.path.basename(event.src_path)
  153. print "<FILE> Found {} in data_directory!".format(file_name)
  154. logger.log("<FILE> Found {} in data_directory!".format(file_name))
  155. if file_name in allowed_names:
  156. lock = portalocker.Lock(conf.data_path + "signal.dbf")
  157. while True:
  158. try:
  159. lock.acquire(fail_when_locked=False)
  160. break
  161. except IOError:
  162. time.sleep(1)
  163. data = Data(conf)
  164. data.read_data(file_name)
  165. data.send_data()
  166. try:
  167. os.remove(conf.data_path + file_name)
  168. except:
  169. print "<ERROR> Can't find {}!".format(file_name)
  170. logger.log("<ERROR> Can't find {}!".format(file_name))
  171. lock.release()
  172.  
  173.  
  174. eventsHandler = EventsHandler()
  175. observer = observers.Observer()
  176. observer.schedule(eventsHandler, conf.data_path, recursive=False)
  177. observer.start()
  178.  
  179. try:
  180. while True:
  181. time.sleep(1)
  182. except KeyboardInterrupt:
  183. observer.stop()
  184. observer.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement