-
-
Save swilcox/1319999 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import redis | |
from django.conf import settings | |
from django.core.signals import request_finished | |
try: | |
from eventlet.corolocal import local | |
except ImportError: | |
from threading import local | |
REDIS_HOST = getattr(settings, 'REDIS_HOST', '127.0.0.1') | |
REDIS_PORT = getattr(settings, 'REDIS_PORT', 6379) | |
REDIS_DB = getattr(settings, 'REDIS_DB', 8) | |
REDIS_LOCAL = local() | |
def get_redis(): | |
try: | |
return REDIS_LOCAL.client | |
except AttributeError: | |
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) | |
REDIS_LOCAL.client = client | |
return client | |
def cleanup(sender, **kwargs): | |
try: | |
client = REDIS_LOCAL.client | |
del REDIS_LOCAL.client | |
except AttributeError: | |
return | |
try: | |
client.disconnect() | |
except (KeyboardInterrupt, SystemExit, MemoryError): | |
raise | |
except: | |
pass | |
request_finished.connect(cleanup) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment