Skip to content

Instantly share code, notes, and snippets.

@chrisglass
Created December 21, 2010 08:49
Show Gist options
  • Save chrisglass/749677 to your computer and use it in GitHub Desktop.
Save chrisglass/749677 to your computer and use it in GitHub Desktop.
This makes Django settings autodiscover local memcaches! :)
import os
import socket
class IP(object):
def __init__(self):
self.base = None
def get(self, end):
if not self.base:
self.base = self._get_base()
return '%s.%s' % (self.base, end)
def _get_base(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('google.com', 0))
return s.getsockname()[0].rsplit('.', 1)[0]
ip_getter = IP()
def check(ip, port, timeout):
try:
socket.create_connection((ip, port), timeout)
return ip
except socket.error:
return False
def find_local_memcached(timeout=1, startip=1, endip=127, port=11211, cachefile=None):
if cachefile and os.path.exists(cachefile):
f = open(cachefile, 'r')
first = f.read()
f.close()
if check(first, port, timeout):
return first
for end in xrange(startip, endip + 1):
ip = ip_getter.get(end)
if check(ip, port, timeout):
if cachefile:
f = open(cachefile, 'w')
f.write(ip)
f.close()
return ip
return None
cache_file = os.path.join(os.path.expanduser('~'), '.dj_memcached_ip')
ip = find_local_memcached(cachefile=cache_file)
if ip:
print 'found memcached server running at %s' % ip
CACHE_BACKEND = 'memcached://%s:11211/?timeout=300' % ip
else:
print 'no memcached server found'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment