mysql.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # -*- coding: utf-8 -*-
  2. from six.moves import configparser
  3. def parse_mysql_cnf(dbinfo):
  4. """
  5. Attempt to parse mysql database config file for connection settings.
  6. Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs
  7. so we have to emulate the behaviour
  8. Settings that are missing will return ''
  9. returns (user, password, database_name, database_host, database_port)
  10. """
  11. read_default_file = dbinfo.get('OPTIONS', {}).get('read_default_file')
  12. if read_default_file:
  13. config = configparser.RawConfigParser({
  14. 'user': '',
  15. 'password': '',
  16. 'database': '',
  17. 'host': '',
  18. 'port': '',
  19. 'socket': '',
  20. })
  21. import os
  22. config.read(os.path.expanduser(read_default_file))
  23. try:
  24. user = config.get('client', 'user')
  25. password = config.get('client', 'password')
  26. database_name = config.get('client', 'database')
  27. database_host = config.get('client', 'host')
  28. database_port = config.get('client', 'port')
  29. socket = config.get('client', 'socket')
  30. if database_host == 'localhost' and socket:
  31. # mysql actually uses a socket if host is localhost
  32. database_host = socket
  33. return user, password, database_name, database_host, database_port
  34. except configparser.NoSectionError:
  35. pass
  36. return '', '', '', '', ''