sqlconfigparser.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from astconfigparser import MultiOrderedConfigParser
  2. try:
  3. import pymysql as MySQLdb
  4. MySQLdb.install_as_MySQLdb()
  5. except ImportError:
  6. # MySQLdb is compatible with Python 2 only. Try it as a
  7. # fallback if pymysql is unavailable.
  8. import MySQLdb
  9. import traceback
  10. class SqlConfigParser(MultiOrderedConfigParser):
  11. _tablename = "sippeers"
  12. def __init__(self,tablename="sippeers"):
  13. self._tablename=tablename
  14. MultiOrderedConfigParser.__init__(self)
  15. def connect(self, user, password, host, port, database):
  16. self.cnx = MySQLdb.connect(user=user,passwd=password,host=host,port=int(port),db=database)
  17. def read(self, filename, sect=None):
  18. MultiOrderedConfigParser.read(self, filename, sect)
  19. # cursor = self.cnx.cursor(dictionary=True)
  20. cursor = self.cnx.cursor(cursorclass=MySQLdb.cursors.DictCursor)
  21. cursor.execute("SELECT * from `" + MySQLdb.escape_string(self._tablename) + "`")
  22. rows = cursor.fetchall()
  23. for row in rows:
  24. sect = self.add_section(row['name'])
  25. for key in row:
  26. if (row[key] != None):
  27. for elem in str(row[key]).split(";"):
  28. sect[key] = elem
  29. #sect[key] = str(row[key]).split(";")
  30. def write_dicts(self, config_file, mdicts):
  31. """Write the contents of the mdicts to the specified config file"""
  32. for section, sect_list in mdicts.iteritems():
  33. # every section contains a list of dictionaries
  34. for sect in sect_list:
  35. sql = "INSERT INTO "
  36. if (sect.get('type')[0] == "endpoint"):
  37. sql += "ps_endpoints "
  38. elif (sect.get('type')[0] == "aor" and section != "sbc"):
  39. sql += "ps_aors "
  40. elif (sect.get('type')[0] == "identify"):
  41. sql += "ps_endpoint_id_ips"
  42. else:
  43. continue
  44. sql += " SET `id` = " + "\"" + MySQLdb.escape_string(section) + "\""
  45. for key, val_list in sect.iteritems():
  46. if key == "type":
  47. continue
  48. # every value is also a list
  49. key_val = " `" + key + "`"
  50. key_val += " = " + "\"" + MySQLdb.escape_string(";".join(val_list)) + "\""
  51. sql += ","
  52. sql += key_val
  53. config_file.write("%s;\n" % (sql))
  54. def write(self, config_file):
  55. """Write configuration information out to a file"""
  56. try:
  57. self.write_dicts(config_file, self._sections)
  58. except:
  59. print("Could not open file " + config_file + " for writing")
  60. traceback.print_exc()