Skip to content

Instantly share code, notes, and snippets.

@afeld
Last active March 27, 2017 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afeld/79d82d70a7cee21b92b43165b4c79c54 to your computer and use it in GitHub Desktop.
Save afeld/79d82d70a7cee21b92b43165b4c79c54 to your computer and use it in GitHub Desktop.
get MySQL database connection information from environment variables in Python

While this code is for MySQLdb, it would be similar for most other Python database APIs. The corresponding environment variables, which are all optional:

  • DB_HOST
  • DB_PASSWD
  • DB_PORT
  • DB_USER
  • DB_UNIX_SOCKET

More information about these variables.

import MySQLdb
def get_db_kwargs(env):
db_kwargs = {}
for key in ['host', 'user', 'passwd', 'port', 'unix_socket']:
env_var = "DB_{}".format(key.upper())
if env_var in env:
db_kwargs[key] = env[env_var]
return db_kwargs
db_kwargs = get_db_kwargs(os.environ)
db = MySQLdb.connect(**db_kwargs)
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment