Import Redis
# 1, set get Setex Delete all operate on values that are string types
R = Redis. Redis (host='x.x.x.x'123456', db = 1)# r.set (' am_session ', ' 20122222222 ') #set数据, add a piece of data # Print (R.get (' am_session '). Decode ()) #get数据, the data that Redis takes out is bytes type, so it is converted to a string using the Decode method. # # r.delete (' cm_session ') # R.setex (' am_ssss ', ' Chenmeng ', ten) #新建一条数据, you can specify the expiration time of the key, in seconds
#
# # 2, hash type set, get Data way: A session, like a dictionary, different keys corresponding to different values
1 # R.hset (' cmsessions ', ' cm ', ' 1 ') 2 # R.hset (' cmsessions ', ' cm1 ', ' a ') 3 # R.hset ( ' Cmsessions ', ' cm2 ', ' 123 ') 4 # Span style= "COLOR: #008000" > # print (R.hget (' cmsessions ', ' cm2 '). Decode ()) #获取hash类型某个key的数据 5 # # Redis_data = R.hgetall (' Cmsessions ') # Get all data of hash type, return dictionary, but inside are binary: {b ' cm ': B ' 1 ', B ' cm2 ': B ' 123 ', B ' cm1 ': B ' "} 6 # #
# # #解析hash类型中的二进制数据, change to normal string
x
1 # R.hset (' cmsessions ', ' cm ', ' 1 ') 2 # R.hset (' cmsessions ', ' cm1 ', ' a ') 3 # R.hset ( ' Cmsessions ', ' cm2 ', ' 123 ') 4 # Span style= "COLOR: #008000" > # print (R.hget (' cmsessions ', ' cm2 '). Decode ()) #获取hash类型某个key的数据 5 # # Redis_data = R.hgetall (' Cmsessions ') # Get all data of hash type, return dictionary, but inside are binary: {b ' cm ': B ' 1 ', B ' cm2 ': B ' 123 ', B ' cm1 ': B ' "} 6 # #
#
# #hash类型没有过期时间
#
#
# 3. If you need to add a session to a folder, with a colon, multiple levels of folders with multiple colons
# r.set (' cm:am_session ', ' 20122222222 ')
#
#
# # 4. Get all the keys
# Print (R.keys ()) #获取所有的key
# Print (R.keys (' cm* ')) #获取所有以cm开头的key
# Print (R.type (' cmsessions ')) #获取所有kye的类型, hash type is: B ' hash ', the normal return type is B ' string '
#5. All keys in DB2 migrated to DB8
#a Build two Redis links
#b get all the keys, return the byte type starting with B, all judging types, B ' string '
#c determine the type of key, string hash
1 #Src_redis = Redis. Redis (host= ' x.x.x.x ', port = 6379,password = ' 123456 ', db = 4)2 #Target_redis = Redis. Redis (host= ' x.x.x.x ', port = 6379,password = ' 123456 ', db = 3)3 #For key in Src_redis.keys (): #[b ' Session3 ', b ' wy:wy1:wy2 ', b ' Session_wy ', B ' Wangyan ']4 #if Src_redis.type (key) = = B ' String ':5 #v = src_redis.get (key)6 #Target_redis.set (key,v)7 #Else: #hash类型处理8 #all_hash_data = Src_redis.hgetall ()9 #For k,v in All_hash_data.item ():Ten #Target_redis.hset (key,k,v)
"Python" Learning note 5-Working with Redis database Redis