db.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. """
  3. demeter
  4. name:db.py
  5. author:rabin
  6. """
  7. class Influxdb(object):
  8. """
  9. instance = None
  10. def __new__(cls, *args, **kwd):
  11. if Influxdb.instance is None:
  12. Influxdb.instance = object.__new__(cls, *args, **kwd)
  13. return Influxdb.instance
  14. """
  15. def __init__(self, config):
  16. influxdb = __import__('influxdb')
  17. InfluxDBClient = getattr(influxdb, 'InfluxDBClient')
  18. self.connect = InfluxDBClient(config['host'], config['port'], config['username'], config['password'], config['dbname'])
  19. self.create(config['dbname'])
  20. def get(self):
  21. return self.connect
  22. def create(self, name):
  23. database = self.connect.get_list_database()
  24. self.connect.create_database(name)
  25. class Postgresql(object):
  26. """
  27. instance = None
  28. def __new__(cls, *args, **kwd):
  29. if Postgresql.instance is None:
  30. Postgresql.instance = object.__new__(cls, *args, **kwd)
  31. return Postgresql.instance
  32. """
  33. def __init__(self, config):
  34. psycopg2 = __import__('psycopg2')
  35. self.connect = psycopg2.connect(host=config['host'], port=config['port'], user=config['username'], password=config['password'], database=config['dbname'])
  36. def get(self):
  37. return self.connect
  38. def create(self, name):
  39. 'psql -U postgres'
  40. sql = 'CREATE DATABASE '+name+' WITH OWNER = postgres ENCODING = "UTF8"'
  41. return sql
  42. class Mysql(object):
  43. """
  44. instance = None
  45. def __new__(cls, *args, **kwd):
  46. if Mysql.instance is None:
  47. Mysql.instance = object.__new__(cls, *args, **kwd)
  48. return Mysql.instance
  49. """
  50. def __init__(self, config):
  51. pymysql = __import__('pymysql')
  52. self.connect = pymysql.connect(host=config['host'], port=int(config['port']), user=config['username'], password=config['password'], database=config['dbname'], charset=config['charset'])
  53. def get(self):
  54. return self.connect
  55. def create(self, name):
  56. sql = 'CREATE DATABASE IF NOT EXISTS '+name+' DEFAULT CHARSET utf8 COLLATE utf8_general_ci'
  57. return sql
  58. class Sqlite(object):
  59. """
  60. instance = None
  61. def __new__(cls, *args, **kwd):
  62. if Sqlite.instance is None:
  63. Sqlite.instance = object.__new__(cls, *args, **kwd)
  64. return Sqlite.instance
  65. """
  66. def __init__(self, config):
  67. sqlite3 = __import__('sqlite3')
  68. self.connect = sqlite3.connect(config['file'])
  69. def get(self):
  70. return self.connect
  71. def create(self, name):
  72. sql = 'CREATE DATABASE IF NOT EXISTS '+name+' DEFAULT CHARSET utf8 COLLATE utf8_general_ci'
  73. return sql