3.Python操作Redis:字符串(String)

6 篇文章 0 订阅
5 篇文章 0 订阅

Python操作Redis的redis模块对字符串(string)的主要操作函数包括:SET、GET、GETSET、SETEX、SETNX、MSET、MSETNX、INCR(INCRBY,DECR,DECRBY在python中庸同一个函数incr实现)、APPEND。其他的一些方法在Python的redis无法实现redis命令行下的操作效果,诸如SETRANGE、STRLEN等命令无法实现,代码注释内容有所体现。

函数说明

  1. SET: 为指定的键(key)设置值(value), set(self, name, value, **kwargs)。
  2. GET:获取指定键(key)绑定的值(value),get(self, name)。
  3. GETSET: 为指定的键(key)设置新的值(value),并返回旧的值(old Value),getset(self, name, value)
  4. SETEX:为指定的键(key)设置过期以秒(second)计的过期时间,setex(self, name, value, time)
  5. SETNX: 键(key)不存在时,为键(key)指定值(value),setnx(self, name, value)
  6. MSET:一次性设置多个键-值(key-value)对,函数设置的键-值对(即mapping所指内容)数据要以Python字典数据类型传入,mset(self, mapping)
  7. MSETNX:键-值(key-value)对不存在时,设置键-值(key-value)对,msetnx(self, mapping),mapping值参考6。
  8. INCR:自增函数,默认步长为1,通过对步长(amount)大小以及征服的控制实现了INCRBY(amount>=1)、DECR(amount=-1)、DECRBY(amount<=-1)等函数功能,incr(self, name, amount=1)
  9. APPEND: 为指定的字符串追加值,若不存在则直接创建, append(self, key, value)

代码示例

#!/usr/bin/python
import redis
import time

## Connect local redis service
client =redis.Redis(host='127.0.0.1',port=6379)
print "Connection to server successfully!"

client.set("tutorial-name","Redis tutorial")
print "Stored srting in redis: ",
print client.get("tutorial-name") 

# Get Key's children string(unable to achieve command GETRANGE)
key = "key1"
string ="This my test key"
client.set(key,string)
rangeString=client.substr(key,0,5)
print "The child string for key ",key," child vlaue list",rangeString

# Binding a new value to the key, return the old value(GETSET)
oldVal=client.getset("tutorial-name","Redis")
print "Get old value: ",oldVal
print "New value:",client.get("tutorial-name")

# getbit method not exists in the module(GETBIT) 
#client.set("tutorial-name","Redis tutorial")
#print client.getbit("tutorial-name",2)

# setex(self, name, value, time) command SETEX
# Set the value of key ``name`` to ``value`` 
# that expires in ``time`` seconds 
# ttl(self) command TTL
client.setex('mykey','mysql',10)
time.sleep(2)
timeLeft=client.ttl('mykey')
print "Get left live time",timeLeft
print "Get the value",client.get('mykey')

#setnx Set the value of key ``name`` to ``value`` if key doesn't exist. (SETNX)
client.setnx('mykey','PostgreSQL')
client.setnx('mykey1','MongoDB')
print "Get existed key's new value",client.get('mykey')
print "Get new built value",client.get('mykey1')

# no SETRANGE
# no STRLEN
# mset, Sets each key in the ``mapping`` dict to its corresponding value
client.mset({'key1':'Redis','key2':'MySQl'})
print "Get key1 mapping value",client.get('key1')
print "Get key2 mapping value",client.get('key2')


# msetnx: Sets each key in the ``mapping`` dict to its corresponding value if
#         none of the keys are already set
client.msetnx({'mykeyI':'Redis','mykeyII':'MySQl'})
print "Get mykeyI mapping value",client.get('mykeyI')
print "Get mykeyII mapping value",client.get('mykeyII')

# no PSETEX 
# incr method achieved both INCR and INCRBY command line in redis
# incr, iIncrements the value of ``key`` by ``amount``.
# If no key exists, the value will be initialized as ``amount``
# if not set the increment number, the default is 1. 
# We can set amount an negative value get DECR/DECRBY method.
client.set('page_num',20)
client.incr('page_num',-2)
print "The increased value",client.get('page_num')

# append(self,key,value), 
#       Appends the string ``value`` to the value at ``key``. If ``key``
#       doesn't already exist, create it with a value of ``value``.
#       Returns the new length of the value at ``key``.
client.append('mykey',' DB2')
print "Get appended string",client.get('mykey')

hashVal = client.hgetall('profile')
print hashVal
#Empty db
client.flushdb()

参考资料
1、Redis 字符串(String)
2、Python redis文档(python交互模式下命令>>>help redis

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用redis-py库来实现Redis数据迁移。以下是一个简单的示例代码,演示如何从一个Redis实例复制数据到另一个Redis实例。 首先,确保你已经安装了redis-py库。可以使用以下命令来安装: ``` pip install redis ``` 然后,使用以下代码实现数据迁移: ```python import redis def migrate_data(source_host, source_port, source_password, destination_host, destination_port, destination_password): # 连接源Redis source_redis = redis.Redis(host=source_host, port=source_port, password=source_password) # 连接目标Redis destination_redis = redis.Redis(host=destination_host, port=destination_port, password=destination_password) # 获取所有键 keys = source_redis.keys() # 迁移数据 for key in keys: key_type = source_redis.type(key) if key_type == b'string': value = source_redis.get(key) destination_redis.set(key, value) elif key_type == b'list': values = source_redis.lrange(key, 0, -1) for value in values: destination_redis.rpush(key, value) elif key_type == b'set': values = source_redis.smembers(key) for value in values: destination_redis.sadd(key, value) elif key_type == b'zset': values = source_redis.zrange(key, 0, -1, withscores=True) for value, score in values: destination_redis.zadd(key, {value: score}) elif key_type == b'hash': items = source_redis.hgetall(key) for field, value in items.items(): destination_redis.hset(key, field, value) print("数据迁移完成!") # 示例用法 migrate_data('source_host', 6379, 'source_password', 'destination_host', 6379, 'destination_password') ``` 请确保替换示例中的源Redis和目标Redis的主机、端口和密码信息。这段代码会将源Redis中的所有键和对应的值迁移到目标Redis中。 请注意,该示例代码只迁移了常见的Redis数据类型(字符串、列表、集合、有序集合和哈希)。如果你使用了其他数据类型,你需要相应地进行修改。 希望对你有所帮助!如有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值