• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python memcache.Client类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中memcache.Client的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Client类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: whereyoulive_sum

def whereyoulive_sum():

    global addresses
    
    ret = "<table class=\"normal\">"
    ret += "<th class=\"normal\">" + "Address" + "</th>"
    ret += "<th class=\"normal\">" + "Total/Address" + "</th>"

    conn = Client([gethostname()+':11211'])

    vals = []
    
    for k in addresses:
        ret += "<tr class=\"normal\">"
        ret += "<td class=\"normal\">" + k + "</td>"
        val = conn.get(addr_prefix+k)

        if val == None:
            vals.append(0)
        else:
            vals.append(val)

        ret += "<td class=\"normal\"><span>" + str(vals[-1]) + "</span></td>"
        ret += "</tr>"

    ret += "<tr align=\"center\"><td class=\"normal\">" + "Sum" + "</td>"

    if len(vals) == 0:
        ret += "<td class=\"normal\">" + "0" + "</td></tr>"
    else:
        ret += "<td class=\"normal\">" + str(reduce(lambda i, j : i+j, [i for i in vals])) + "</td></tr>"

    ret += "</table>"

    return ret
开发者ID:Zex,项目名称:Starter,代码行数:35,代码来源:whereyoulive_sum.py


示例2: remove

 def remove(self, layer, coord, format):
     """ Remove a cached tile.
     """
     mem = Client(self.servers)
     key = tile_key(layer, coord, format, self.revision)
     
     mem.delete(key)
开发者ID:Narrator,项目名称:TileStache,代码行数:7,代码来源:Memcache.py


示例3: MemcachedZipState

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)
开发者ID:collective,项目名称:collective.azipfele,代码行数:26,代码来源:state.py


示例4: SocketHandler

class SocketHandler(websocket.WebSocketHandler):
    client_infos = defaultdict()

    def __init__(self, *args, **kwargs):
        super(SocketHandler, self).__init__(*args, **kwargs)
        servers = ['127.0.0.1:11211']
        self._mc = Client(servers)

    def open(self):
        self.client_infos[self] = ClientInfo()

    def on_close(self):
        del self.client_infos[self]

    def on_message(self, message):
        now = datetime.now()
        delta = now - self.client_infos[self].prev_message_time
        # TODO: Restrict access based on delta.

        time = self._mc.get('time')
        if self.client_infos[self].prev_image_time == time:
            self.write_message({'timeout': 50})
        else:
            image = self._mc.get('image')
            image = base64.b64encode(image)
            self.write_message({'image': image, 'timeout': 80})
            self.client_infos[self].prev_image_time = time
        self.client_infos[self].prev_message_time = now

    def check_origin(self, origin):
        return True
开发者ID:vmlaker,项目名称:wabbit,代码行数:31,代码来源:websocket_serve.py


示例5: MemcacheStoreTest

class MemcacheStoreTest(unittest.TestCase, SimpleKVTest):
    def setUp(self):
        self.mc = Client([testconf.get('memcache', 'server')])
        self.mc.flush_all()

        self.store = MemcacheStore(self.mc)

    def tearDown(self):
        self.mc.flush_all()

    def test_memcache_connection(self):
        pass

    # disabled tests (not fully API support for memcache)
    test_has_key = None
    test_has_key_with_delete = None
    test_key_iterator = None
    test_keys = None

    def test_keys_throws_io_error(self):
        with self.assertRaises(IOError):
            self.store.keys()

        with self.assertRaises(IOError):
            self.store.iter_keys()

        with self.assertRaises(IOError):
            iter(self.store)

    def test_contains_throws_io_error_or_succeeds(self):
        try:
            'a' in self.store
        except IOError:
            pass
开发者ID:danilobellini,项目名称:simplekv,代码行数:34,代码来源:test_memcache.py


示例6: save

 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)
开发者ID:aaronr,项目名称:TileStache,代码行数:7,代码来源:Memcache.py


示例7: __init__

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)
开发者ID:aquarion,项目名称:Lifestream,代码行数:59,代码来源:__init__.py


示例8: remove

    def remove(self, layer, coord, format):
        """ Remove a cached tile.
        """
        mem = Client(self.servers)
        key = tile_key(layer, coord, format, self.revision, self.key_prefix)

        mem.delete(key)
        mem.disconnect_all()
开发者ID:kaimw,项目名称:TileStache,代码行数:8,代码来源:Memcache.py


示例9: save

    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()
开发者ID:kaimw,项目名称:TileStache,代码行数:8,代码来源:Memcache.py


示例10: unlock

    def unlock(self, layer, coord, format):
        """ Release a cache lock for this tile.
        """
        mem = Client(self.servers)
        key = tile_key(layer, coord, format, self.revision, self.key_prefix)

        mem.delete(key + "-lock")
        mem.disconnect_all()
开发者ID:kaimw,项目名称:TileStache,代码行数:8,代码来源:Memcache.py


示例11: preset

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)
开发者ID:Zex,项目名称:Starter,代码行数:9,代码来源:whereyoulive_sum.py


示例12: read

    def read(self, layer, coord, format):
        """ Read a cached tile.
        """
        mem = Client(self.servers)
        key = tile_key(layer, coord, format, self.revision, self.key_prefix)

        value = mem.get(key)
        mem.disconnect_all()

        return value
开发者ID:kaimw,项目名称:TileStache,代码行数:10,代码来源:Memcache.py


示例13: save

 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()
开发者ID:byrman,项目名称:TileStache,代码行数:11,代码来源:Memcache.py


示例14: read

 def read(self, layer, coord, format):
     """ Read a cached tile.
     """
     mem = Client(self.servers)
     key = tile_key(layer, coord, format, self.revision, self.key_prefix)
     
     value = mem.get(key)
     mem.disconnect_all()
     
     if value is None:
         return None
     
     return b64decode(value.encode('ascii'))
开发者ID:byrman,项目名称:TileStache,代码行数:13,代码来源:Memcache.py


示例15: WrappedClient

class WrappedClient(object):
    def __init__(self, *args):
        self.args = args
        self.mc = Client(*args, cache_cas=True, socket_timeout=10)
        self.del_que = []
        import threading

    def gets(self, key):
        while True:
            result = self.mc.gets(key)
            if isinstance(result, tuple):
                return result[0]
            return result

    def cas(self, key, value):
        retry_count = 0
        try:
            while True:
                result = self.mc.cas(key, value)
                if not isinstance(result, bool):
                    if retry_count <= 10:
                        retry_count += 1
                        wait_time = 0.001 * randint(0, 1 << retry_count)
                        print "add fail, retry for sleep"
                        sleep(wait_time)
                        self.mc = Client(*self.args, cache_cas=True, socket_timeout=10)
                        continue
                # raise ConnectionError
                return result
        except TypeError:
            return False

    def add(self, key, value):
        retry_count = 0
        while True:
            result = self.mc.add(key, value)
            if not isinstance(result, bool):
                if retry_count <= 10:
                    retry_count += 1
                wait_time = 0.001 * randint(0, 1 << retry_count)
                print "add fail, retry for sleep"
                sleep(wait_time)
                print self.args
                self.mc = Client(*self.args, cache_cas=True, socket_timeout=10)
                continue
                # raise ConnectionError
            return result

    # delegation
    def __getattr__(self, attrname):
        return getattr(self.mc, attrname)
开发者ID:kumagi,项目名称:kvtx2,代码行数:51,代码来源:__init__.py


示例16: MemcachedManager

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
开发者ID:yaksea,项目名称:lunchOrder,代码行数:50,代码来源:memcachedManager.py


示例17: __init__

    def __init__(self, urls, controllers, config=None,
                 auth_class=Authentication):
        super(StorageServerApp, self).__init__(urls, controllers, config,
                                               auth_class)
        self.config = config

        # Collecting the host-specific config and building connectors.
        self.storages = {'default': get_storage(config)}
        hostnames = set()
        host_token = 'host:'
        for cfgkey in config:
            if cfgkey.startswith(host_token):
                # Get the hostname from the config key.  This assumes
                # that host-specific keys have two trailing components
                # that specify the setting to override.
                # E.g: "host:localhost.storage.sqluri" => "localhost"
                hostname = cfgkey[len(host_token):].rsplit(".", 2)[0]
                hostnames.add(hostname)
        for hostname in hostnames:
            host_cfg = self._host_specific(hostname, config)
            self.storages[hostname] = get_storage(host_cfg)

        self.check_blacklist = \
                self.config.get('storage.check_blacklisted_nodes', False)
        if self.check_blacklist and Client is not None:
            servers = self.config.get('storage.cache_servers',
                                      '127.0.0.1:11211')
            self.cache = Client(servers.split(','))
        else:
            if self.check_blacklist:
                raise ValueError('The "check_blacklisted_node" option '
                                 'needs a memcached server')
            self.cache = None
开发者ID:rfk,项目名称:moz-server-storage,代码行数:33,代码来源:wsgiapp.py


示例18: __init__

 def __init__(self, config):
   super(MemcachedCacheClient, self).__init__(config["host"], config["port"], config["cache"])
   self.config = config
   if self.cache_name and self.cache_name != "" and self.cache_name != DEFAULT_MEMCACHED_CACHE_NAME:
     print "WARNING: memcached client doesn't support named caches. cache_name config value will be ignored and the cache name configured on the server will be used instead."
   self.memcached_client = Client([self.host + ':' + self.port], debug=0)
   return
开发者ID:infinispan,项目名称:ispncon,代码行数:7,代码来源:client.py


示例19: Store

class Store(object):
  def __init__(self, host='127.0.0.1', port=11211):
    self.client = Client(['%s:%d' % (host, port),],
                         pickler=JSONPickler,
                         unpickler=JSONUnpickler)

  def get(self, key):
    result = self.client.get(key)
    if result:
      result = result.split('\t')
    return result

  def set(self, key, val):
    result = self.client.add(key, val)
    if not result:
      result = self.client.append(key, '\t%s' % val)
    return result
开发者ID:sukhchander,项目名称:log-spy,代码行数:17,代码来源:store.py


示例20: MemcacheStore

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'))
开发者ID:richardjmarini,项目名称:Impetus-old,代码行数:26,代码来源:queue.py



注:本文中的memcache.Client类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python data_helper.MemcachedClientHelper类代码示例发布时间:2022-05-27
下一篇:
Python memcache._Host函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap