createdb.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. import time
  3. import MySQLdb
  4. import psycopg2
  5. import _mysql_exceptions
  6. from wsgi import *
  7. def create_dbs():
  8. deadline = time.time() + 60
  9. while time.time() < deadline:
  10. try:
  11. print("create_dbs: let's go.")
  12. django_settings = __import__(os.environ['DJANGO_SETTINGS_MODULE'], fromlist='DATABASES')
  13. print("create_dbs: got settings.")
  14. databases = django_settings.DATABASES
  15. for name, db in databases.iteritems():
  16. host = db['HOST']
  17. user = db['USER']
  18. password = db['PASSWORD']
  19. port = db['PORT']
  20. db_name = db['NAME']
  21. db_type = db['ENGINE']
  22. # see if it is mysql
  23. if db_type.endswith('mysql'):
  24. print 'creating database %s on %s' % (db_name, host)
  25. db = MySQLdb.connect(user=user,
  26. passwd=password,
  27. host=host,
  28. port=port)
  29. cur = db.cursor()
  30. print("Check if database is already there.")
  31. cur.execute("""SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
  32. WHERE SCHEMA_NAME = %s""", (db_name,))
  33. results = cur.fetchone()
  34. if not results:
  35. print("Database %s doesn't exist, lets create it." % db_name)
  36. sql = """CREATE DATABASE IF NOT EXISTS %s """ % (db_name,)
  37. print("> %s" % sql)
  38. cur.execute(sql)
  39. print(".....")
  40. else:
  41. print("database already exists, moving on to next step.")
  42. exit(0)
  43. # see if it is postgresql
  44. elif db_type.endswith('postgresql_psycopg2'):
  45. print 'creating database %s on %s' % (db_name, host)
  46. con = psycopg2.connect(host=host, user=user, password=password, port=port, database='postgres')
  47. con.set_isolation_level(0)
  48. cur = con.cursor()
  49. try:
  50. cur.execute('CREATE DATABASE %s' % db_name)
  51. except psycopg2.ProgrammingError as detail:
  52. print detail
  53. print 'moving right along...'
  54. exit(0)
  55. else:
  56. print("ERROR: {0} is not supported by this script, you will need to create your database by hand.".format(db_type))
  57. exit(1)
  58. except psycopg2.OperationalError:
  59. print "Could not connect to database. Waiting a little bit."
  60. time.sleep(10)
  61. except _mysql_exceptions.OperationalError:
  62. print "Could not connect to database. Waiting a little bit."
  63. time.sleep(10)
  64. print 'Could not connect to database after 1 minutes. Something is wrong.'
  65. exit(1)
  66. if __name__ == '__main__':
  67. import sys
  68. print("create_dbs start")
  69. create_dbs()
  70. print("create_dbs all done")