Cleaned up querystring parsing

Moved `_parse_querystring_for_options()` into its own function
Added test for empty querystring params
This commit is contained in:
Sam Sandberg 2015-05-14 17:52:16 -04:00
parent 5336a0c014
commit 7f6717e434
2 changed files with 20 additions and 12 deletions

View file

@ -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

View file

@ -112,12 +112,8 @@ class DatabaseTestSuite(unittest.TestCase):
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 @@ class DatabaseTestSuite(unittest.TestCase):
'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()