Skip to content

Commit

Permalink
Cleaned up querystring parsing
Browse files Browse the repository at this point in the history
Moved `_parse_querystring_for_options()` into its own function
Added test for empty querystring params
  • Loading branch information
loisaidasam committed May 14, 2015
1 parent 5336a0c commit 7f6717e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
21 changes: 14 additions & 7 deletions dj_database_url.py
Expand Up @@ -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."""

Expand All @@ -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)
Expand All @@ -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

Expand Down
11 changes: 6 additions & 5 deletions test_dj_database_url.py
Expand Up @@ -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'
Expand All @@ -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()

0 comments on commit 7f6717e

Please sign in to comment.