xmaria.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # update: 2021-7-2-9
  2. """
  3. pymysql==0.9.3
  4. peewee==3.13.1 # db orm
  5. """
  6. from peewee import MySQLDatabase as PeeweeEngine # todo UserWarning: Unable to determine MySQL version
  7. # from playhouse.mysql_ext import MySQLConnectorDatabase as PeeweeEngine # todo MySQL connector not installed!
  8. from playhouse.reflection import generate_models
  9. class Client(PeeweeEngine):
  10. def __init__(self, host='test-stack-mariadb', port=3306, database='vms', username='root', password='root'):
  11. """
  12. 内部访问:
  13. host: test-stack-mariadb
  14. port: 3306
  15. 远程访问:
  16. host: 118.190.217.96、192.168.20.162
  17. port: 17706
  18. """
  19. super().__init__(database, user=username, password=password, host=host, port=port)
  20. tables = generate_models(self)
  21. globals().update(tables)
  22. self.tables = globals()
  23. # --- vuls ---
  24. # self.vuls = dict()
  25. # table = self.tables['vul_detail']
  26. # for item in table.select():
  27. # self.vuls[item.cve_id] = item.__data__
  28. # def get_vul_by_cve_id(self, cve_id):
  29. # return self.vuls.get(cve_id, {})
  30. def get_all(self, table_name):
  31. """
  32. 获取全部数据
  33. """
  34. table = self.tables[table_name]
  35. return table.select()
  36. def get_one(self, table_name, unique_dict):
  37. """
  38. 单条获取
  39. """
  40. table = self.tables[table_name]
  41. wheres = list()
  42. for k, v in unique_dict.items():
  43. data = getattr(table, k) == v
  44. wheres.append(data)
  45. for item in table.select().where(*wheres):
  46. return item.__data__
  47. def execute_sql(self, sql):
  48. """
  49. 执行sql
  50. """
  51. try:
  52. result = db.execute_sql(sql)
  53. print(result.__class__.__name__)
  54. return result
  55. except Exception as exception:
  56. print(exception.__class__.__name__)
  57. return None
  58. if __name__ == '__main__':
  59. # --- init ---
  60. # db = Client()
  61. # db = Client(host='192.168.30.49', port=7033)
  62. db = Client(host='127.0.0.1', port=3306, database='ar', username='root', password='20221212!')
  63. # --- test ---
  64. sql = f'''select sum(timestampdiff(second, createtime, updatetime)) from ar.ar_phone_call where status = 1'''
  65. result = db.execute_sql(sql)
  66. for row in result:
  67. print(' --- --- ---- ---')
  68. print(row)
  69. print(row.__class__.__name__)
  70. print(row[0])
  71. db.close()
  72. # --- test ---
  73. # items = db.get_all('vul_detail')
  74. # for item in items:
  75. # print(item.cve_id)
  76. # # print(item.vul_name)
  77. # --- test ---
  78. # out = db.get_one('vul_detail', {'cve_id': 'CVE-2007-1858'})
  79. # print(type(out.get('cvss_point')))
  80. # print(out.get('cvss_point'))