hard_disk_storage.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import datetime
  2. import math
  3. import re
  4. # import openpyxl
  5. import pymysql
  6. import traceback
  7. import time
  8. # from AES_crypt import decrypt
  9. import configparser
  10. class HardDiskStorage:
  11. def __init__(self, port=3306, charset='utf8'):
  12. self.config = configparser.ConfigParser()
  13. self.config.read("database.conf", encoding="utf-8")
  14. # for section in self.config.sections():
  15. # print(f"[{section}]")
  16. # for key, value in self.config.items(section):
  17. # print(f"{key} = {value}")
  18. self.host = self.config.get("db", "db_host")
  19. self.user = self.config.get("db", "db_user")
  20. self.passwd = self.config.get("db", "db_pass")
  21. self.db = self.config.get("db", "db_name")
  22. self.port = port
  23. self.charset = charset
  24. self.conn = None
  25. if not self._conn():
  26. self._reConn()
  27. def _conn(self):
  28. try:
  29. self.conn = pymysql.connect(host=self.host, user=self.user, password=self.passwd, database=self.db,
  30. port=self.port, autocommit=True)
  31. return True
  32. except Exception as e:
  33. print(f'failed to connect to {self.host}:{self.port}:{self.db} by [{self.user}:{self.passwd}]:{e}')
  34. return False
  35. def _reConn(self, num=28800, stime=3): # 重试连接总次数为1天,这里根据实际情况自己设置,如果服务器宕机1天都没发现就......
  36. _number = 0
  37. _status = True
  38. while _status and _number <= num:
  39. try:
  40. self.conn.ping() # cping 校验连接是否异常
  41. _status = False
  42. except Exception as e:
  43. if self._conn(): # 重新连接,成功退出
  44. _status = False
  45. break
  46. _number += 1
  47. time.sleep(stime) # 连接不成功,休眠3秒钟,继续循环,知道成功或重试次数结束
  48. # def get_point_info(self, point_tuple):
  49. # if point_tuple:
  50. # sql = "SELECT * FROM data_point_tbl where serial_number in %s" % (str(point_tuple))
  51. # else:
  52. # sql = "SELECT * FROM data_point_tbl"
  53. # try:
  54. # self._reConn()
  55. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  56. # self.cursor.execute(sql)
  57. # results = self.cursor.fetchall()
  58. # self.cursor.close()
  59. # return results
  60. # except:
  61. # print(traceback.format_exc())
  62. # return False
  63. # def get_table_data(self, senect_info):
  64. # table_name = "table_" + senect_info['deviceName']
  65. # time_begin = senect_info['timeBegin']
  66. # time_end = senect_info['timeEnd']
  67. # column = senect_info['pointList']
  68. # if len(column) > 0:
  69. # sql = "SELECT times"
  70. # for column_name in column:
  71. # sql = sql + "," + column_name
  72. # sql = sql + " FROM %s WHERE times > '%s' AND times < '%s'" % (table_name, time_begin, time_end)
  73. # else:
  74. # sql = "SELECT * FROM %s WHERE times > '%s' AND times < '%s';" % (table_name, time_begin, time_end)
  75. # try:
  76. # self._reConn()
  77. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  78. # self.cursor.execute(sql)
  79. # results = self.cursor.fetchall()
  80. # self.cursor.close()
  81. # return results
  82. # except:
  83. # print(traceback.format_exc())
  84. # return None
  85. # # 历史查询接口(new)--------------------------------------------\\
  86. # def get_total_count_and_first_id(self, search_info):
  87. # table_name = "table_" + search_info['deviceName']
  88. # time_begin = search_info['timeBegin']
  89. # time_end = search_info['timeEnd']
  90. # sql = "select count(*) from %s where times >= '%s' and times <= '%s';" % (table_name, time_begin, time_end)
  91. # sql_1 = "select id from %s where times >= '%s' limit 1;" % (table_name, time_begin)
  92. # try:
  93. # self._reConn()
  94. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  95. # self.cursor.execute(sql)
  96. # count = self.cursor.fetchall()
  97. # self.cursor.execute(sql_1)
  98. # first_id = self.cursor.fetchall()
  99. # if isinstance(first_id, tuple):
  100. # first_id = list(first_id)
  101. # result = count + first_id
  102. # return result
  103. # except:
  104. # print(traceback.format_exc())
  105. # return None
  106. # def get_item_by_id_offset(self, search_info):
  107. # table_name = "table_" + search_info['deviceName']
  108. # point_list = search_info['pointList']
  109. # id_offset = search_info['idOffset']
  110. # quantity = search_info['quantity']
  111. # sql = "select times, %s from %s where id >= %s limit %s" % (','.join(point_list), table_name, id_offset, quantity)
  112. # try:
  113. # self._reConn()
  114. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  115. # self.cursor.execute(sql)
  116. # results = self.cursor.fetchall()
  117. # self.cursor.close()
  118. # return results
  119. # except:
  120. # print(traceback.format_exc())
  121. # return None
  122. #
  123. # # --------------------------------------------//
  124. # # 数据导出接口------------------------------------------------\\
  125. # def quary_table_data(self, search_info):
  126. # table_name = "table_" + search_info['deviceName']
  127. # time_begin = search_info['timeBegin']
  128. # time_end = search_info['timeEnd']
  129. # point_list = search_info['pointList']
  130. # point_list_1 = str([i[1:] for i in point_list])[1:-1]
  131. #
  132. # sql = "select times, %s from %s where times >= '%s' and times <= '%s';" % (','.join(point_list), table_name, time_begin, time_end)
  133. # sql1 = "select io_point_name from data_point_tbl where serial_number in ( %s );" % point_list_1
  134. #
  135. # try:
  136. # self._reConn()
  137. # self.cursor = self.conn.cursor()
  138. # self.cursor.execute(sql)
  139. # res = self.cursor.fetchall()
  140. # self.cursor.execute(sql1)
  141. # res1 = self.cursor.fetchall()
  142. # title = [item[0] for item in res1]
  143. # title.insert(0, '日期')
  144. # self.cursor.close()
  145. # except:
  146. # print(traceback.format_exc())
  147. # return None
  148. # book = openpyxl.Workbook()
  149. # sheet = book.create_sheet(index=0)
  150. # # 循环将表头写入到sheet页
  151. # for i in range(len(title)):
  152. # if search_info['deviceName'] == 'adcp': # adcp需要重新计算垂直方向表头
  153. # name = re.findall(r"\d+\.?\d*", title[i]) # 提取数字字符
  154. # if name:
  155. # title[i] = re.sub(r"\d+\.?\d*", str(round((int(name[0]) * math.sin(14 * math.pi / 180)), 2)), title[i]) # 14为adcp安装倾斜角度,2保留小数的位数
  156. # sheet.cell(1, i + 1).value = title[i]
  157. # # 写数据
  158. # for row in range(0, len(res)):
  159. # for col in range(0, len(res[row])):
  160. # cell_val = res[row][col]
  161. # if isinstance(cell_val, datetime.datetime):
  162. # times = cell_val.strftime("%Y-%m-%d %H:%M:%S")
  163. # sheet.cell(row + 2, col + 1).value = times
  164. # else:
  165. # sheet.cell(row + 2, col + 1).value = cell_val
  166. # file_path = (table_name + '.xlsx')
  167. # savepath = file_path
  168. # book.save(savepath)
  169. # return savepath
  170. #
  171. # # ------------------------------------------------//
  172. # # 获取insitu指令接口
  173. # def get_in_situ_command(self):
  174. # sql = "select * from shuizhi_insitu_instruct;"
  175. # try:
  176. # self._reConn()
  177. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  178. # self.cursor.execute(sql)
  179. # results = self.cursor.fetchall()
  180. # self.cursor.close()
  181. # return results
  182. # except:
  183. # print(traceback.format_exc())
  184. # return None
  185. # def get_connectors(self):
  186. # sql = "SELECT * FROM station_info_tbl WHERE status = 1"
  187. # try:
  188. # self._reConn()
  189. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  190. # self.cursor.execute(sql)
  191. # results = self.cursor.fetchall()
  192. # self.cursor.close()
  193. # return results
  194. # except:
  195. # print(traceback.format_exc())
  196. # return None
  197. # def create_delete_stale_data_event(self, eventName, table_name, day):
  198. # self.cursor = self.conn.cursor()
  199. # sql = "create event %s on SCHEDULE every 1 day do delete from %s where times<(CURRENT_TIMESTAMP() + INTERVAL -%s DAY);" % (
  200. # eventName, table_name, day)
  201. # self.cursor.execute(sql)
  202. # self.cursor.close()
  203. # def create_many_column_table(self, table_name, list):
  204. # self.cursor = self.conn.cursor()
  205. # for index in range(len(list)):
  206. # dataType = list[index]['storageType']
  207. # columnName = "c" + str(list[index]['serialNumber'])
  208. # sql_c = "CREATE TABLE IF NOT EXISTS %s (times datetime NOT NULL,INDEX (times)) \
  209. # ENGINE=InnoDB DEFAULT CHARSET=utf8;" % (table_name)
  210. # sql_add = "ALTER TABLE %s ADD %s %s " % (table_name, columnName, dataType)
  211. # try:
  212. # self.cursor.execute(sql_c)
  213. # self.cursor.execute(sql_add)
  214. # except:
  215. # print(traceback.format_exc())
  216. # sql_send = "ALTER TABLE %s ADD 'is_send'tinyint NOT NULL DEFAULT '0'" % (table_name)
  217. # self.cursor.execute(sql_send)
  218. # self.cursor.close()
  219. # def insert_column_many(self, table_name, timeNow, dict):
  220. # try:
  221. # self.cursor = self.conn.cursor()
  222. # sql = "INSERT INTO %s (times" % (table_name)
  223. # for key_name in dict.keys():
  224. # sql = sql + "," + key_name
  225. # sql = sql + ") VALUE ('" + str(timeNow) + "'"
  226. # for key_name in dict.keys():
  227. # data = "," + str(dict[key_name])
  228. # sql = sql + data
  229. # sql = sql + ")"
  230. # try:
  231. # self.cursor.execute(sql)
  232. # # 提交到数据库执行
  233. # self.conn.commit()
  234. # except Exception as e:
  235. # # 如果发生错误则回滚
  236. # self.conn.rollback()
  237. # print(e)
  238. # except Exception as e:
  239. # self._reConn()
  240. # print(e)
  241. # else:
  242. # self.cursor.close()
  243. def close(self):
  244. self.conn.close()
  245. # def get_command_info(self, station_name):
  246. # sql = "SELECT command FROM command where station_name = '%s' " % station_name
  247. # try:
  248. # self._reConn()
  249. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  250. # self.cursor.execute(sql)
  251. # results = self.cursor.fetchall()
  252. # self.cursor.close()
  253. # return results
  254. # except:
  255. # print(traceback.format_exc())
  256. # return None
  257. # # lee
  258. # def get_device_name_by_station_name(self, station_name):
  259. # sql = "SELECT DISTINCT device_name FROM data_point_tbl WHERE station_name = '%s' " % station_name
  260. # try:
  261. # self._reConn()
  262. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  263. # self.cursor.execute(sql)
  264. # results = self.cursor.fetchall()
  265. # self.cursor.close()
  266. # return results
  267. # except:
  268. # print(traceback.format_exc())
  269. # return None
  270. # def get_data_point_by_device_name(self, device_name):
  271. # sql = "SELECT * FROM data_point_tbl WHERE device_name = '%s'" % device_name
  272. # try:
  273. # self._reConn()
  274. # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  275. # self.cursor.execute(sql)
  276. # results = self.cursor.fetchall()
  277. # self.cursor.close()
  278. # return results
  279. # except:
  280. # print(traceback.format_exc())
  281. # return None
  282. def execute_sql(self, sql, var):
  283. try:
  284. self._reConn()
  285. self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  286. self.cursor.execute(sql, var)
  287. results = self.cursor.fetchall()
  288. self.cursor.close()
  289. return results
  290. except:
  291. print(traceback.format_exc())
  292. return None
  293. def get_all(self, sql):
  294. try:
  295. self._reConn()
  296. self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  297. self.cursor.execute(sql)
  298. results = self.cursor.fetchall()
  299. self.cursor.close()
  300. return results
  301. except:
  302. print(traceback.format_exc())
  303. return False