Created
December 21, 2010 08:49
-
-
Save chrisglass/749677 to your computer and use it in GitHub Desktop.
This makes Django settings autodiscover local memcaches! :)
This file contains hidden or 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 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