import redis
class MyRedis(object):
    def __init__(self,ip,password,port=6379,db=6):
         #构造函数
        try:        #进行异常处理
            self.r = redis.Redis(host=ip,port=port,password=password,db=db)
        except Exception as e:    
            print('Redis连接失败,错误信息%s'%e)

    def str_get(self,k):
        res = self.r.get(k)
        if res:
            return res.decode()
        return None

    def close(self):   #私有方法
        print('close')

    def str_set(self,k,v,time=None):
        res=self.r.set(k,v,time)
        print('string数据插入成功')

    def str_delete(self,k):  #stt类型的删除key
        tag=self.r.exists(k)  #判断这个K是否存在5
        if tag:
            self.r.delete(k)
            print('数据删除成功')
        else:
            print('这个K不存在')

    def hash_get(self,name,k):   #hash类型获取单个key
        res=self.r.hget(name,k)
        if res:
            return res.decode()
        return None

    def hash_set(self,name,k,v):  #hash类型set
        self.r.hset(name,k,v)
        print('hash数据插入成功')

    def hash_getall(self,name):  #hash类型获取key里面的所有数据
        data={}
        res=self.r.hgetall(name)   #获取的数据类型是字典类型,要单个元素用decode()
        if res:
            for k,v in res.items():
                k=k.decode()
                v=v.decode()
                data[k]=v
            return data
        return None

    def hash_del(self,name,k):   #删除某个hash里面小key
        res=self.r.hdel(name,k)
        if res:
            print('小key删除成功')
            return 1
        else:
            print('删除失败,该K不存在')
            return 0

    def clean_redis(self):  #清理redis,删除所有的key
        self.r.flushdb() #清空redis
        print('清空redis成功')
        return 0



my = MyRedis('118.24.3.xx','HK139bcxx')
my.str_set('tanxxxx','wowowo')
my.hash_set('tanxxxxx_hash','tanrrrr','uiuiuiuii')
# my.hash_set('tanxxx_hash','tanrrrr','ioioioioio')
# print('tanttt.....',my.str_get('tanzhen'))
# print('tanttt_hash_2.....',my.hash_get('tanttt_hash','tantttt'))
# my.clean_redis()
print('hash_getall:',my.hash_getall('tantttt_hash'))