Python使用redis pool的一种单例实现方式

yipeiwu_com5年前Python基础

本文实例讲述了Python使用redis pool的一种单例实现方式。分享给大家供大家参考,具体如下:

为适应多个redis实例共享同一个连接池的场景,可以类似于以下单例方式实现:

import redis
class RedisDBConfig:
  HOST = '127.0.0.1'
  PORT = 6379
  DBID = 0
def operator_status(func):
  '''''get operatoration status
  '''
  def gen_status(*args, **kwargs):
    error, result = None, None
    try:
      result = func(*args, **kwargs)
    except Exception as e:
      error = str(e)
    return {'result': result, 'error': error}
  return gen_status
class RedisCache(object):
  def __init__(self):
    if not hasattr(RedisCache, 'pool'):
      RedisCache.create_pool()
    self._connection = redis.Redis(connection_pool = RedisCache.pool)
  @staticmethod
  def create_pool():
    RedisCache.pool = redis.ConnectionPool(
        host = RedisDBConfig.HOST,
        port = RedisDBConfig.PORT,
        db  = RedisDBConfig.DBID)
  @operator_status
  def set_data(self, key, value):
    '''''set data with (key, value)
    '''
    return self._connection.set(key, value)
  @operator_status
  def get_data(self, key):
    '''''get data by key
    '''
    return self._connection.get(key)
  @operator_status
  def del_data(self, key):
    '''''delete cache by key
    '''
    return self._connection.delete(key)
if __name__ == '__main__':
  print RedisCache().set_data('Testkey', "Simple Test")
  print RedisCache().get_data('Testkey')
  print RedisCache().del_data('Testkey')
  print RedisCache().get_data('Testkey')

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Django如何使用第三方服务发送电子邮件

Django如何使用第三方服务发送电子邮件

在 Django 网站中使用 mailgun 的邮件收发服务。 1.在 mailgun 官网上注册个账号(免费,免费账号每个月有10000条收发邮件的服务,对我来说已经完全够用了),注册...

Bottle框架中的装饰器类和描述符应用详解

最近在阅读Python微型Web框架Bottle的源码,发现了Bottle中有一个既是装饰器类又是描述符的有趣实现。刚好这两个点是Python比较的难理解,又混合在一起,让代码有些晦涩难...

Python OS模块实例详解

本文实例讲述了Python OS模块。分享给大家供大家参考,具体如下: os模块 在自动化测试中,经常需要查找操作文件,比如查找配置文件(从而读取配置文件的信息),查找测试报告等等,经常...

Django验证码的生成与使用示例

Django验证码的生成与使用示例

前言 本文主要介绍的是关于Django验证码生成与使用的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 方法如下: 1、基于PIL生成一个带验证码的图片和验证码,生成验证码...

在pytorch 中计算精度、回归率、F1 score等指标的实例

pytorch中训练完网络后,需要对学习的结果进行测试。官网上例程用的方法统统都是正确率,使用的是torch.eq()这个函数。 但是为了更精细的评价结果,我们还需要计算其他各个指标。在...