python-从redis数据库中读数据

  • 读string,list,set,sort_set,hash类型的数据
import redis

class DataBase:
    def __init__(self, host, port):
        self.host = host
        self.port = port
    
    def read_string(self, key):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            result = r.get(key)
            return result
        except Exception as exception:
            print(exception)     
            
    def read_list(self, key, n):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            if n > r.llen(key):
                result = r.lrange(0, -1)
            else:
                result = r.lrange(key, 0, n)
                
            return result
        except Exception as exception:
            print(exception) 
    
    def read_set(self, key):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            result = r.smembers(key)
            return result
        except Exception as exception:
            print(exception)
        
    def read_hash(self, key):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            result = r.hgetall(key)
            return result
        except Exception as exception:
            print(exception)
    
    def read_sort_set(self, key, n):
        try:
            r = redis.StrictRedis(host=self.host, port=self.port)
            if n > r.zcard(key):
                result = r.zrange(0, -1)
            else:
                result = r.zrange(0, n)
            return result
        except Exception as exception:
            print(exception)
posted @ 2016-01-27 10:44  奋斗的珞珞  阅读(2920)  评论(0编辑  收藏  举报