diff --git a/dj_database_url.py b/dj_database_url.py index 9c93b5a..2aa7b3c 100644 --- a/dj_database_url.py +++ b/dj_database_url.py @@ -48,6 +48,17 @@ def config(env=DEFAULT_ENV, default=None, engine=None): return config +def _parse_querystring_for_options(path): + if '?' not in path: + return + query_string = path.split('?', 2)[1] + if not query_string: + return + qs = urlparse.parse_qs(query_string) + return {key: values[-1] for key, values in qs.iteritems()} + + + def parse(url, engine=None): """Parses a database URL.""" @@ -66,9 +77,8 @@ def parse(url, engine=None): url = urlparse.urlparse(url) - # Remove query strings. - path = url.path[1:] - path = path.split('?', 2)[0] + # Path (without leading '/'), and with no query string + path = url.path[1:].split('?')[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) @@ -90,10 +100,7 @@ def parse(url, engine=None): }) # Parse the query string into OPTIONS. - qs = urlparse.parse_qs(url.query) - options = {} - for k in qs: - options[k] = qs[k][-1] + options = _parse_querystring_for_options(url.path) if options: config['OPTIONS'] = options diff --git a/test_dj_database_url.py b/test_dj_database_url.py index f8d3f0a..b457008 100644 --- a/test_dj_database_url.py +++ b/test_dj_database_url.py @@ -112,12 +112,8 @@ def test_config_engine_setting(self): assert url['ENGINE'] == engine def test_database_url_with_options(self): - del os.environ['DATABASE_URL'] - a = dj_database_url.config() - assert not a - + # Test full options os.environ['DATABASE_URL'] = 'postgres://uf07k1i6d8ia0v:wegauwhgeuioweg@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn?sslrootcert=rds-combined-ca-bundle.pem&sslmode=verify-full' - url = dj_database_url.config() assert url['ENGINE'] == 'django.db.backends.postgresql_psycopg2' @@ -131,6 +127,11 @@ def test_database_url_with_options(self): 'sslmode': 'verify-full' } + # Test empty options + os.environ['DATABASE_URL'] = 'postgres://uf07k1i6d8ia0v:wegauwhgeuioweg@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn?' + url = dj_database_url.config() + assert 'OPTIONS' not in url + if __name__ == '__main__': unittest.main()