-
Notifications
You must be signed in to change notification settings - Fork 2k
/
redis.py
58 lines (41 loc) · 1.27 KB
/
redis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# encoding: utf-8
'''
Redis utilities.
.. versionadded:: 2.7
'''
from __future__ import absolute_import
import logging
from redis import ConnectionPool, Redis
from ckan.common import config
log = logging.getLogger(__name__)
# Redis connection pool. Do not use this directly, use ``connect_to_redis``
# instead.
_connection_pool = None
def connect_to_redis() -> Redis:
'''
(Lazily) connect to Redis.
The connection is set up but not actually established. The latter
happens automatically once the connection is used.
:returns: A lazy Redis connection.
:rtype: ``redis.Redis``
.. seealso:: :py:func:`is_redis_available`
'''
global _connection_pool
if _connection_pool is None:
url = config.get('ckan.redis.url')
log.debug(u'Using Redis at {}'.format(url))
_connection_pool = ConnectionPool.from_url(url)
return Redis(connection_pool=_connection_pool)
def is_redis_available() -> bool:
'''
Check whether Redis is available.
:returns: The availability of Redis.
:rtype: bool
.. seealso:: :py:func:`connect_to_redis`
'''
redis_conn = connect_to_redis()
try:
return redis_conn.ping() is True
except Exception:
log.exception(u'Redis is not available')
return False