dj-database-urlに渡すデフォルトの接続文字列
dj-database-urlを使うとdb接続文字列を環境変数DATABASE_URLから取得させることができます。
https://github.com/kennethreitz/dj-database-url
herokuにdjangoアプリを動かすときとかに使ってます。
設定は以下のように書きます。
環境変数DATABASE_URLがない場合はdefaultとして渡した文字列をパースして接続文字列を取得します。
DATABASES = {'default': dj_database_url.config(default='postgres://...')}
dj_database_url.parseを使うと、環境変数は参照せずに渡した文字列をパースして接続文字列を取得します。
DATABASES = {'default': dj_database_url.parse('postgres://...')}
さて接続文字列ですが、sqliteを使う場合渡す文字列は以下のような感じで書いてます。
import os PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) DATABASES = {'default': dj_database_url.parse('sqlite:///%s' % os.path.join(PROJECT_ROOT, 'development.db') )}
以下の設定と同義になります。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'development.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
mysqlの場合は以下のような感じ
DATABASES = {'default': dj_database_url.parse('mysql://testuser:testuserpassword@localhost:3306/devdb'') )}
以下の設定と同義になります
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'devdb',
'USER': 'testuser',
'PASSWORD': 'testuserpassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
注意点として、パスワードに#が含まれている場合は、接続文字列を正しくパースできないので使えません。