Skip to content

Commit 1a4327c

Browse files
committed
Add a strict boolean parameter to FlaskRedis initializer
The parameter allows easily choosing between using redis.StrictRedis or redis.Redis as the client. Closes #15
1 parent 175ee42 commit 1a4327c

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

flask_redis.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
import warnings
2-
from redis import Redis as _Redis
2+
try:
3+
import redis
4+
except ImportError:
5+
# We can allow custom provider only usage without redis-py being installed
6+
redis = None
37

48
__all__ = ('Redis', 'FlaskRedis')
59
__version__ = '0.0.6'
610

711

812
class FlaskRedis(object):
9-
def __init__(self, app=None, config_prefix='REDIS'):
13+
def __init__(self, app=None, strict=False, config_prefix='REDIS'):
1014
self._provider_class = None
1115
self._redis_client = None
1216
self.config_prefix = config_prefix
1317

1418
if app is not None:
15-
self.init_app(app)
19+
self.init_app(app, strict)
1620

1721
@classmethod
1822
def from_custom_provider(cls, provider, app=None, **kwargs):
@@ -27,9 +31,11 @@ def from_custom_provider(cls, provider, app=None, **kwargs):
2731
instance.init_app(app)
2832
return instance
2933

30-
def init_app(self, app):
34+
def init_app(self, app, strict=False):
3135
if self._provider_class is None:
32-
self._provider_class = _Redis
36+
self._provider_class = (
37+
redis.StrictRedis if strict else redis.Redis
38+
)
3339

3440
redis_url = app.config.get(
3541
'{0}_URL'.format(self.config_prefix), 'redis://localhost:6379/0'

test_flask_redis.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,19 @@ def test_custom_prefix(app):
4444
assert redis_b.connection_pool.connection_kwargs['db'] == 2
4545

4646

47+
def test_strict_parameter(app):
48+
'''Test that initializing with the strict parameter set to True will use
49+
StrictRedis, and that False will keep using the old Redis class.'''
50+
51+
redis = FlaskRedis(app, strict=True)
52+
assert redis._redis_client is not None
53+
assert type(redis._redis_client).__name__ == 'StrictRedis'
54+
55+
redis = FlaskRedis(app, strict=False)
56+
assert redis._redis_client is not None
57+
assert type(redis._redis_client).__name__ == 'Redis'
58+
59+
4760
def test_custom_provider(app):
4861
'''Test that FlaskRedis can be instructed to use a different Redis client,
4962
like StrictRedis'''

0 commit comments

Comments
 (0)