Skip to content

Instantly share code, notes, and snippets.

@D3f0
Created December 16, 2016 19:00
Show Gist options
  • Save D3f0/edd70a6066863ee74674ac5ede838a20 to your computer and use it in GitHub Desktop.
Save D3f0/edd70a6066863ee74674ac5ede838a20 to your computer and use it in GitHub Desktop.
Access directly to Heroku app DBs from your shell
# This snippet requires dj_database_url (https://github.com/kennethreitz/dj-database-url)
class HerokuDatabaseWrapper(dict):
def get_config_for_app(self, name):
from subprocess import check_output
d = {}
output = check_output('heroku config -a'.split() + [name, ])
for line in output.split('\n'):
if ':' not in line:
continue
key, val = map(lambda s: s.strip(), line.split(':', 1))
d[key] = val
return d
def get_config(self, name):
import dj_database_url
db_url = self.get_config_for_app(name)['DATABASE_URL']
return dj_database_url.parse(db_url)
def __getitem__(self, name):
if name not in self:
self[name] = self.get_config(name)
return dict.__getitem__(self, name)
# Define databases like this in your settings.py
DATABASES = HerokuDatabaseWrapper({
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'project', # Or path to database file if using sqlite3.
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment