diff options
author | Kenneth Reitz <me@kennethreitz.com> | 2012-05-18 15:02:24 -0700 |
---|---|---|
committer | Kenneth Reitz <me@kennethreitz.com> | 2012-05-18 15:02:24 -0700 |
commit | e57bbd1278631f89395102652193b53f9826d5cd (patch) | |
tree | d6749c35e48cce0b4c5b1188e9201e0380d9e07e | |
parent | 2eb518a7c53702168f5e987c1741512ac5e9b4d7 (diff) | |
download | redis-py-e57bbd1278631f89395102652193b53f9826d5cd.tar.gz |
redis.from_url
-rw-r--r-- | redis/__init__.py | 4 | ||||
-rw-r--r-- | redis/utils.py | 27 |
2 files changed, 30 insertions, 1 deletions
diff --git a/redis/__init__.py b/redis/__init__.py index 3b47484..c4b87a5 100644 --- a/redis/__init__.py +++ b/redis/__init__.py @@ -1,5 +1,6 @@ # legacy imports from redis.client import Redis, ConnectionPool +from redis.utils import from_url from redis.exceptions import ( AuthenticationError, ConnectionError, @@ -11,10 +12,11 @@ from redis.exceptions import ( ) + __version__ = '2.2.4' __all__ = [ 'Redis', 'ConnectionPool', 'RedisError', 'ConnectionError', 'ResponseError', 'AuthenticationError', - 'InvalidResponse', 'DataError', 'PubSubError', + 'InvalidResponse', 'DataError', 'PubSubError', 'from_url' ] diff --git a/redis/utils.py b/redis/utils.py new file mode 100644 index 0000000..4f116a7 --- /dev/null +++ b/redis/utils.py @@ -0,0 +1,27 @@ +from urlparse import urlparse + +from .client import Redis + +DEFAULT_DATABASE_ID = 0 + +def from_url(url, db=None): + """Returns an active Redis client generated from the given database URL. + + Will attempt to extract the database id from the path url fragment, if + none is provided. + """ + + url = urlparse(url) + + # Attempt to resolve database id. + if db is None: + try: + db = int(url.path.replace('/')) + except (AttributeError, ValueError): + db = DEFAULT_DATABASE_ID + + return Redis( + host=url.hostname, + port=url.port, + db=db, + password=url.password)
\ No newline at end of file |