dj-database-url/dj_database_url.py

74 lines
1.6 KiB
Python
Raw Normal View History

2012-04-30 17:37:05 +00:00
# -*- coding: utf-8 -*-
import os
2012-06-19 15:53:51 +00:00
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
2012-04-30 17:37:05 +00:00
# Register database schemes in URLs.
urlparse.uses_netloc.append('postgres')
2012-06-19 15:21:06 +00:00
urlparse.uses_netloc.append('postgresql')
2012-06-05 02:37:58 +00:00
urlparse.uses_netloc.append('postgis')
2012-04-30 17:37:05 +00:00
urlparse.uses_netloc.append('mysql')
2012-06-19 15:21:06 +00:00
urlparse.uses_netloc.append('mysql2')
2012-05-01 16:23:09 +00:00
urlparse.uses_netloc.append('sqlite')
2012-04-30 17:37:05 +00:00
2012-04-30 18:33:12 +00:00
DEFAULT_ENV = 'DATABASE_URL'
2012-04-30 17:37:05 +00:00
2012-06-19 14:57:33 +00:00
SCHEMES = {
'postgres': 'django.db.backends.postgresql_psycopg2',
'postgresql': 'django.db.backends.postgresql_psycopg2',
'postgis': 'django.contrib.gis.db.backends.postgis',
'mysql': 'django.db.backends.mysql',
'mysql2': 'django.db.backends.mysql',
'sqlite': 'django.db.backends.sqlite3'
}
2012-05-30 05:23:28 +00:00
def config(env=DEFAULT_ENV, default=None):
2012-04-30 18:55:37 +00:00
"""Returns configured DATABASE dictionary from DATABASE_URL."""
2012-04-30 17:37:05 +00:00
2012-04-30 18:33:12 +00:00
config = {}
2012-04-30 17:37:05 +00:00
s = os.environ.get(env, default)
2012-05-30 05:23:28 +00:00
if s:
2012-05-30 05:51:08 +00:00
config = parse(s)
2012-04-30 18:55:37 +00:00
return config
def parse(url):
"""Parses a database URL."""
config = {}
url = urlparse.urlparse(url)
2012-06-19 15:21:06 +00:00
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
# if we are using sqlite and we have no path, then assume we
# want an in-memory database (this is the behaviour of sqlalchemy)
if url.scheme == 'sqlite' and path == '':
path = ':memory:'
2012-04-30 18:55:37 +00:00
# Update with environment configuration.
config.update({
2012-06-19 15:21:06 +00:00
'NAME': path,
2012-04-30 18:55:37 +00:00
'USER': url.username,
2012-04-30 19:04:06 +00:00
'PASSWORD': url.password,
2012-04-30 18:55:37 +00:00
'HOST': url.hostname,
'PORT': url.port,
})
2012-06-19 14:57:33 +00:00
if url.scheme in SCHEMES:
config['ENGINE'] = SCHEMES[url.scheme]
2012-05-01 16:23:09 +00:00
return config