Skip to content

Instantly share code, notes, and snippets.

@ericflo
Created October 4, 2010 04:02
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ericflo/609238 to your computer and use it in GitHub Desktop.
Save ericflo/609238 to your computer and use it in GitHub Desktop.
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