import redis
# 创建 Redis 连接
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置键值对
r.set('foo', 'bar')
# 获取键对应的值
value = r.get('foo')
print(f"The value of 'foo' is: {value.decode()}")
# 删除键
r.delete('foo')
# 检查键是否存在
exists = r.exists('foo')
print(f"Does 'foo' exist? {exists}")
# 使用哈希类型存储数据
r.hset('user:1000', mapping={
'name': 'Alice',
'age': 30,
'city': 'Beijing'
})
# 获取哈希中的所有字段和值
user_info = r.hgetall('user:1000')
for key, value in user_info.items():
print(f"{key.decode()}: {value.decode()}")
# 列表操作,向列表中添加元素
r.lpush('mylist', 'item1', 'item2')
# 获取列表中的所有元素
items = r.lrange('mylist', 0, -1)
print(f"Items in 'mylist': {[item.decode() for item in items]}")
redis.Redis
创建一个连接到本地 Redis 服务器的客户端。set
和 get
方法来设置和获取键值对。注意 get
返回的是字节类型,需要解码为字符串。delete
方法删除指定的键。exists
方法检查某个键是否存在。hset
和 hgetall
方法来操作哈希类型的数据结构。lpush
和 lrange
方法来操作列表类型的数据结构。上一篇:python append
下一篇:python download
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站