def home(): """ Home """ try: basic_connection = BasicConnection() basic_connection.connect() except Exception as e: response_object = { "status": "failed", "data": { "connection": "failed", "details": str(e) } } else: response_object = { "status": "success", "data": { "connection": "ok", } } return jsonify(response_object)
def check_connect(host, port, password=None): from redis import Connection try: conn = Connection(host=host, port=port, password=password) conn.connect() return True except: return False
def check_connect(host,port, password=None): from redis import Connection try: conn = Connection(host=host, port=port, password=password) conn.connect() return True except: return False
def status_process(db: Connection, number: str) -> bool: if db.exists(number): data = db.hmget(number, 'status', 'updated_at') if data[0] == STATUS.get(1) and (datetime.fromtimestamp(float( data[1])) + timedelta(hours=6)) > datetime.utcnow(): return STATUS.get(4) elif data[0] == STATUS.get(2): return STATUS.get(2)
def read_msg(): ret = '' conn = Connection(host=gethostname(), port=6379) conn.send_command('keys', msg_prefix + '*') keys = conn.read_response() vals = [] if len(keys) != 0: conn.send_command('mget', *keys) vals = conn.read_response() ret += "<h2>" + "Message log" + "</h2>" for k, v in zip(keys, vals): ret += "<span>" + k.replace(msg_prefix, '').replace( '--', ' ') + "</span>" ret += "<pre readonly=\"true\">" + v + "</pre>" conn.disconnect() ret += "<br>" return ret
def read_msg(): ret = '' conn = Connection(host=gethostname(),port=6379) conn.send_command('keys', msg_prefix+'*') keys = conn.read_response() vals = [] if len(keys) != 0: conn.send_command('mget', *keys) vals = conn.read_response() ret += "<h2>" + "Message log" + "</h2>" for k, v in zip(keys, vals): ret += "<span>" + k.replace(msg_prefix, '').replace('--', ' ') + "</span>" ret += "<pre readonly=\"true\">" + v + "</pre>" conn.disconnect() ret += "<br>" return ret
def __create_connection_pool__(self) -> BlockingConnectionPool: connection_class = Connection( host=os.environ.get('REDIS_HOST'), port=os.environ.get('REDIS_PORT', 6379), db=self.config.get('REDIS_DB', 0), username=self.config.get('REDIS_USERNAME', None), password=os.environ.get('REDIS_PASSWORD', None), socket_timeout=BaseConfig.REDIS_SOCKET_TIMEOUT, socket_connect_timeout=BaseConfig.REDIS_SOCKET_CONNECT_TIMEOUT, socket_keepalive=BaseConfig.REDIS_SOCKET_KEEP_ALIVE, health_check_interval=BaseConfig.REDIS_HEALTH_CHECK_INTERVAL, client_name=BaseConfig.REDIS_CLIENT_NAME, encoding='utf-8', decode_responses=True) pool = BlockingConnectionPool( timeout=BaseConfig.REDIS_CONNECTION_TIMEOUT, max_connections=BaseConfig.REDIS_MAX_CONNECTION) pool.connection_class = connection_class return pool
def redis_container(): session = docker.from_env() redis = session.containers.run('redis:latest', ports={'6379/tcp': 6379}, detach=True) try: conn = Connection() for i in range(60): try: conn.connect() conn.disconnect() break except ConnectionError: pass if i == 59: raise RuntimeError('Failed to connect to Redis.') sleep(.5) yield redis finally: redis.remove(force=True, v=True)
def __init__(self): """ 初始仅需要初始化一个Redis.Connection,无需连接,只需要打包数据接口即可 """ self.packer = Connection() self.__reset()
class RedisBatch(Redis): """ 自实现Redis批量插入库 """ def __init__(self): """ 初始仅需要初始化一个Redis.Connection,无需连接,只需要打包数据接口即可 """ self.packer = Connection() self.__reset() def __reset(self): """ 重置数据 """ self.bufferList = [] self.buffer = [] self.bufLen = 0 self.countCommands = 0 def dumpDB(self, redis): """ 把缓存下来的Redis协议一次批量入库,若存在缓存 """ tmpBuf = self.bufferList tmpCount = self.countCommands self.__reset() if tmpBuf: pool = redis.connection_pool connection = pool.get_connection('') try: connection.send_packed_command(tmpBuf) for i in xrange(tmpCount): redis.parse_response(connection, '') except (ConnectionError, TimeoutError) as e: connection.disconnect() if not connection.retry_on_timeout and isinstance(e, TimeoutError): raise connection.send_packed_command(tmpBuf) for i in xrange(tmpCount): redis.parse_response(connection, '') finally: pool.release(connection) #subprocess.Popen('cat %s | ./redis-cli -pipe -n 15 -a '%(IP, BASE_PORT, code, NAME), shell=True) def execute_command(self, *args, **options): """ 执行命令处理重载,这里不需要 @param p1: @type p1: @return: @rtype: """ for chunk in self.packer.pack_command(*args): self.buffer.append(chunk) self.bufLen += len(chunk) if self.bufLen > 6000: self.bufferList.append(SYM_EMPTY.join(self.buffer)) self.bufLen = 0 self.buffer = [] self.countCommands += 1
def insert_msg(cust, tm, msg): conn = Connection(host=gethostname(),port=6379) conn.send_command('set', msg_prefix+cust+'--'+tm, msg) conn.disconnect()
def insert_msg(cust, tm, msg): conn = Connection(host=gethostname(), port=6379) conn.send_command('set', msg_prefix + cust + '--' + tm, msg) conn.disconnect()
from redis import StrictRedis, ConnectionPool, Connection redis = StrictRedis(host='localhost', port=6379, db=0, password='******') # 或者 conn = Connection(host='localhost', port=6379, db=0, password='******') pool = ConnectionPool(conn) redis = StrictRedis(connection_pool=pool) # 或则 ''' redis://[:password]@host:port/db rediss://[:password]@host:port/db unix://[:password]@/path/to/socket.sock?db=db ''' url = 'redis://:foobared@localhost:6379/0' pool = ConnectionPool.from_url(url) redis = StrictRedis(connection_pool=pool) redis.set('name', 'Bob') print(redis.get('name')) """键操作""" # 判断是否存在 redis.exists('name') # 删除 # redis.delete('name') # 获取键的类型 redis.type('name') # 正则匹配 redis.keys('n*') # 随机一个键 redis.randomkey() # 重命名