本文整理汇总了Python中memcache.Client.set方法的典型用法代码示例。如果您正苦于以下问题:Python Client.set方法的具体用法?Python Client.set怎么用?Python Client.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类memcache.Client
的用法示例。
在下文中一共展示了Client.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MemcacheStore
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class MemcacheStore(DictProxy):
def __init__(self, host, port):
from memcache import Client
self.mc= Client(['%s:%s' % (host, port)])
def update(self, updates):
for update in updates:
(processId, data)= update
self.mc.set(processId, data)
def get(self, processId, default= None):
data= self.mc.get(processId)
if data == None:
return default
return data
def pop(self, processId):
data= self.mc.get(processId)
self.mc.delete(processId)
return data
if data == None:
return default
def __len__(self):
return int(self.mc.get_stats()[0][1].get('curr_items'))
示例2: save
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def save(self, body, layer, coord, format):
""" Save a cached tile.
"""
mem = Client(self.servers)
key = tile_key(layer, coord, format, self.revision)
mem.set(key, body, layer.cache_lifespan or 0)
示例3: MemcachedCache
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class MemcachedCache(CacheBase):
def __init__(self, config, section):
from memcache import Client
servers = config.get(section, 'memcache-server').split()
self.conn = Client(servers)
def key(self, raw):
if sys.version_info >= (3, ):
return self.prefix(hashlib.md5(bytes(raw, 'utf-8')).hexdigest())
else:
return self.prefix(hashlib.md5(raw).hexdigest()).encode('utf-8')
def check_password(self, user, password):
cached = self.conn.get(self.key('%s-pass' % user))
if cached is None:
return cached
return cached == self.hash(password, cached)
def set_password(self, user, password):
self.conn.set(self.key('%s-pass' % user), self.hash(password, None), self.expire)
def in_groups(self, user, groups):
cached = self.conn.get(self.key('%s-groups' % user))
if cached is None:
return None
return not cached.isdisjoint(groups)
def set_groups(self, user, groups):
self.conn.set(self.key('%s-groups' % user), groups, self.expire)
示例4: __init__
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class FoursquareAPI:
url_base = "https://api.foursquare.com/v2/%s"
payload = {}
mc = False
mcprefix = False
def __init__(self, lifestream):
OAUTH_FILENAME = lifestream.config.get("foursquare", "secrets_file")
CONSUMER_KEY = lifestream.config.get("foursquare", "client_id")
CONSUMER_SECRET = lifestream.config.get("foursquare", "secret")
MEMCACHE_HOST = lifestream.config.get("memcache", "host")
MEMCACHE_PORT = lifestream.config.get("memcache", "port")
self.mcprefix = lifestream.config.get("memcache", "prefix")
servers = ["%s:%s" % (MEMCACHE_HOST, MEMCACHE_PORT)]
self.mc = Client(servers, debug=1)
if not os.path.exists(OAUTH_FILENAME):
logger.error("No OAUTH found at %s" % OAUTH_FILENAME)
raise Exception("You need to run foursquare_oauth.py to generate the oauth key")
oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME)
self.payload = {
'v': "20170801",
'oauth_token' : oauth_token
}
def cache_get(self, url, params):
m = hashlib.sha224()
m.update(url)
m.update(str(params))
key = m.hexdigest()
res = self.mc.get(key)
if(res):
return json.loads(res)
r = requests.get(self.url_base % "users/self/checkins", params=self.payload)
self.mc.set(key, json.dumps(r.json()))
return r.json()
def my_checkins(self):
return self.cache_get(self.url_base % "users/self/checkins", params=self.payload)
def search_near(self, lat, lng, intent="checkin", radius=50, limit=10):
payload = self.payload
payload['ll'] = "%s,%s" % (lat, lng)
payload['intent'] = intent
payload['radius'] = radius
payload['limit'] = limit
return self.cache_get(self.url_base % "venues/search", params=self.payload)
示例5: save
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def save(self, body, layer, coord, format):
""" Save a cached tile.
"""
mem = Client(self.servers)
key = tile_key(layer, coord, format, self.revision, self.key_prefix)
mem.set(key, body, layer.cache_lifespan or 0)
mem.disconnect_all()
示例6: preset
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def preset(sample):
global addresses
conn = Client([gethostname()+':11211'])
if conn.get_stats()[0][1]['curr_items'] == 0:
for k in addresses:
conn.set(addr_prefix+k, 0)
示例7: OODictMongoMemcache
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class OODictMongoMemcache(OODictMongo):
"""Add memcache caching capabilities to a OODictMongo."""
def __init__(self, memcache_host, mongo_uri, mongo_db, mongo_coll,
mongo_id="_id", mongo_client=None, memcache_client=None,
_dict=None):
super(OODictMongoMemcache, self).__init__(
mongo_uri, mongo_db, mongo_coll, mongo_id,
mongo_client, _dict
)
self._memcache_host = memcache_host
## self._memcache_lock = memache_lock
if memcache_client is None:
self._memcache = MemcacheClient(memcache_host)
else:
self._memcache = memcache_client
def _memcache_key(self, mongo_id=None):
return str("%s:%s:%s" % (self._mongo_db, self._mongo_coll,
mongo_id or self._dict.get(self._mongo_id, '')))
def get_from_field(self, key, value, flush=False):
"""Get user by a key:value pair from mongo or memcache."""
# if searching by id key, then we can find it in memcache
if not flush and key == self._mongo_id:
item = self._memcache.get(self._memcache_key(value))
if item:
log.info("Cache hit.")
return self._reinit(item)
log.info("Cache miss.")
# didn't find it in memcache, search in mongo and update cache
super(OODictMongoMemcache, self).get_from_field(key, value)
item = self._dict
if item:
self._memcache.set(self._memcache_key(), item)
return self._reinit(item)
def refresh(self, flush=False):
"""Refresh self data from memcache. If flush is True, then
flush memcache entry and force a refresh from mongo.
"""
self.get_from_field(self._mongo_id, self._dict[self._mongo_id], flush)
def save(self):
"""Save user data to storage."""
self._memcache.set(self._memcache_key(), self._dict)
super(OODictMongoMemcache, self).save()
def delete(self):
"""Delete user from storage."""
self._memcache.delete(self._memcache_key())
super(OODictMongoMemcache, self).delete()
示例8: save
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def save(self, body, layer, coord, format):
""" Save a cached tile.
"""
mem = Client(self.servers)
key = tile_key(layer, coord, format, self.revision, self.key_prefix)
if body is not None:
body = b64encode(body).decode('ascii')
mem.set(key, body, layer.cache_lifespan or 0)
mem.disconnect_all()
示例9: whereyoulive
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def whereyoulive(addr):
conn = Client([gethostname()+':11211'])
if conn.get(addr_prefix+addr) != None:
conn.incr(addr_prefix+addr)
else:
conn.set(addr_prefix+addr, 1)
if not addresses.__contains__(addr):
addresses.append(addr)
示例10: MemcachedManager
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class MemcachedManager():
class Prefix():
Session = 'SESSION'
SysCache = 'ORDER_SYS_CACHE'
def __init__(self):
# if settings.ENVIRONMENT['dev']:
# pass
# else:
self.conn = Client(settings.CACHE['clients'])
def get(self, *arg):
if len(arg) ==0:
return None
arg = [str(i) for i in arg]
key = PRODUCT_PREFIX+ '|'.join(arg)
try:
# if settings.ENVIRONMENT['dev']:
# return _localCache.get(key)
# else:
return self.conn.get(key)
# self.conn.
except:# Client.MemcachedKeyNoneError:
return None
def set(self, value, timeout, *arg):
if len(arg) ==0:
return None
arg = [str(i) for i in arg]
key = PRODUCT_PREFIX+'|'.join(arg)
# if settings.ENVIRONMENT['dev']:
# _localCache[key] = value
# else:
self.conn.set(key, value, timeout)
def delete(self, *arg):
if len(arg) ==0:
return None
arg = [str(i) for i in arg]
key = PRODUCT_PREFIX+'|'.join(arg)
try:
# if settings.ENVIRONMENT['dev']:
# if _localCache.has_key(key):
# _localCache.pop(key)
# else:
self.conn.delete(key)
except: # Client.MemcachedKeyNoneError:
return None
示例11: test_memcached_connection
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def test_memcached_connection(self):
# python-memcached
print('MEMCACHED_PORT_11211_TCP_ADDR')
print(os.environ.get('MEMCACHED_PORT_11211_TCP_ADDR'))
print('MEMCACHED_PORT_11211_TCP_PORT')
print(os.environ.get('MEMCACHED_PORT_11211_TCP_PORT'))
mc = Client([
os.environ.get('MEMCACHED_PORT_11211_TCP_ADDR')
], debug=1)
mc.set('a_string', 'some random string')
newval = mc.get('a_string')
self.assertEqual(newval, 'some random string')
mc.disconnect_all()
示例12: MemcachedZipState
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class MemcachedZipState(object):
"""get or set state of an zip job.
"""
def __init__(self, uid):
self._uid = uid
if ZIPSTATE_MEMCACHEDSERVER not in os.environ:
raise ValueError(
'Expect environment variable "{0}: pointing a memcached '
'server in order to share state '
'information.'.format(ZIPSTATE_MEMCACHEDSERVER)
)
self._client = Client([os.environ[ZIPSTATE_MEMCACHEDSERVER]])
def _combined_key(self, key):
return '{0}-{1}'.format(self._uid, key)
def __getitem__(self, key):
"""get state of zip job
"""
return self._client.get(self._combined_key(key))
def __setitem__(self, key, value):
"""set state of zip job
"""
return self._client.set(self._combined_key(key), value)
示例13: MemCacheWrapper
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class MemCacheWrapper(object):
"""
Memcache client wrapper.
No exception raise and add some useful function.
"""
def __init__(self, servers, logerr=None):
self.cache = MCClient(servers=servers, debug=False)
self.logerr = logerr
def add(self, key, val=1, time=0):
try:
return self.cache.add(key, val, time)
except Exception as e:
_logger.warning("Exception during `add`: %s", e)
return None
def count(self, key, expires=0, delta=1):
try:
result = self.cache.incr(key, delta)
if result is None:
if not self.cache.add(key, delta, expires):
result = self.cache.incr(key, delta)
else:
return delta
return result
except Exception as e:
_logger.warning("Exception during `count`: %s", e)
return None
def get(self, key):
result = None
try:
result = self.cache.get(str(key))
except Exception as e:
_logger.warning("Exception during `get`: %s", e)
return result
def set(self, key, value, expires):
result = False
try:
result = self.cache.set(str(key), value, expires)
except Exception as e:
_logger.warning("Exception during `set`: %s", e)
return result
def delete(self, key):
result = False
try:
result = self.cache.delete(key)
except Exception as e:
_logger.warning("Exception during `del`: %s", e)
return result
示例14: Memcache
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
class Memcache(object):
"""
address=127.0.0.1:11211
# TODO 链接断开后没有自动重连机制
"""
def __init__(self, address):
from memcache import Client
self.conn = Client([address])
def get(self, key):
return self.conn.get(key)
def set(self, key, value, timeout):
self.conn.set(key, value, timeout)
def delete(self, key):
self.conn.delete(key)
示例15: lock
# 需要导入模块: from memcache import Client [as 别名]
# 或者: from memcache.Client import set [as 别名]
def lock(self, layer, coord, format):
""" Acquire a cache lock for this tile.
Returns nothing, but blocks until the lock has been acquired.
"""
mem = Client(self.servers)
key = tile_key(layer, coord, format, self.revision, self.key_prefix)
due = _time() + layer.stale_lock_timeout
try:
while _time() < due:
if mem.add(key + "-lock", "locked.", layer.stale_lock_timeout):
return
_sleep(0.2)
mem.set(key + "-lock", "locked.", layer.stale_lock_timeout)
return
finally:
mem.disconnect_all()