forked from jazzband/dj-database-url
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dj_database_url.py
69 lines (49 loc) · 1.5 KB
/
dj_database_url.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
import os
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
# Register database schemes in URLs.
urlparse.uses_netloc.append('postgres')
urlparse.uses_netloc.append('postgresql')
urlparse.uses_netloc.append('postgis')
urlparse.uses_netloc.append('mongodb')
urlparse.uses_netloc.append('mysql')
urlparse.uses_netloc.append('mysql2')
urlparse.uses_netloc.append('sqlite')
DEFAULT_ENV = 'DATABASE_URL'
SCHEMES = {
'postgres': 'django.db.backends.postgresql_psycopg2',
'postgresql': 'django.db.backends.postgresql_psycopg2',
'postgis': 'django.contrib.gis.db.backends.postgis',
'mongodb': 'django_mongodb_engine',
'mysql': 'django.db.backends.mysql',
'mysql2': 'django.db.backends.mysql',
'sqlite': 'django.db.backends.sqlite3'
}
def config(env=DEFAULT_ENV, default=None):
"""Returns configured DATABASE dictionary from DATABASE_URL."""
config = {}
s = os.environ.get(env, default)
if s:
config = parse(s)
return config
def parse(url):
"""Parses a database URL."""
config = {}
url = urlparse.urlparse(url)
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
# Update with environment configuration.
config.update({
'NAME': path,
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme in SCHEMES:
config['ENGINE'] = SCHEMES[url.scheme]
return config