Skip to content

Commit df9e043

Browse files
committed
web.database now accepts a URL, $DATABASE_URL (fixes webpy#171)
1 parent 35dc18c commit df9e043

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

web/db.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"database", 'DB',
1212
]
1313

14-
import time
14+
import time, os
1515
try:
1616
import datetime
1717
except ImportError:
@@ -1131,13 +1131,33 @@ def _process_insert_query(self, query, tablename, seqname):
11311131
else:
11321132
return query + "; SELECT %s.currval FROM dual" % seqname
11331133

1134+
def dburl2dict(url):
1135+
"""
1136+
Takes a URL to a database and parses it into an equivalent dictionary.
1137+
1138+
>>> dburl2dict('postgres://james:day@serverfarm.example.net:5432/mygreatdb')
1139+
{'user': 'james', 'host': 'serverfarm.example.net', 'db': 'mygreatdb', 'pw': 'day', 'dbn': 'postgres'}
1140+
1141+
"""
1142+
dbn, rest = url.split('://', 1)
1143+
user, rest = rest.split(':', 1)
1144+
pw, rest = rest.split('@', 1)
1145+
host, rest = rest.split(':', 1)
1146+
port, rest = rest.split('/', 1)
1147+
db = rest
1148+
return dict(dbn=dbn, user=user, pw=pw, db=db, host=host)
1149+
11341150
_databases = {}
11351151
def database(dburl=None, **params):
11361152
"""Creates appropriate database using params.
11371153
11381154
Pooling will be enabled if DBUtils module is available.
11391155
Pooling can be disabled by passing pooling=False in params.
11401156
"""
1157+
if not dburl and not params:
1158+
dburl = os.environ['DATABASE_URL']
1159+
if dburl:
1160+
params = dburl2dict(dburl)
11411161
dbn = params.pop('dbn')
11421162
if dbn in _databases:
11431163
return _databases[dbn](**params)

0 commit comments

Comments
 (0)