dj-database-url/dj_database_url.py

50 lines
1 KiB
Python
Raw Normal View History

2012-04-30 17:37:05 +00:00
# -*- coding: utf-8 -*-
import os
import urlparse
# Register database schemes in URLs.
urlparse.uses_netloc.append('postgres')
urlparse.uses_netloc.append('mysql')
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-04-30 18:33:12 +00:00
def config(env=DEFAULT_ENV):
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
2012-04-30 18:33:12 +00:00
if env in os.environ:
2012-04-30 18:55:37 +00:00
config = parse(os.environ[env])
return config
def parse(url):
"""Parses a database URL."""
config = {}
url = urlparse.urlparse(url)
# Update with environment configuration.
config.update({
'NAME': url.path[1:],
'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,
})
if url.scheme == 'postgres':
config['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
if url.scheme == 'mysql':
config['ENGINE'] = 'django.db.backends.mysql'
2012-04-30 17:37:05 +00:00
2012-05-01 16:23:09 +00:00
if url.scheme == 'sqlite':
config['ENGINE'] = 'django.db.backends.sqlite3'
return config