侧边栏壁纸
博主头像
nivnek博主等级

道阻且长,行则将至

  • 累计撰写 21 篇文章
  • 累计创建 27 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Use Python import zset data to Redis cluster

kenvin
2022-11-14 / 0 评论 / 0 点赞 / 186 阅读 / 3066 字

Prerequisites

python modules:

  • redis-py-cluster

Excute follow command to install module:

pip install redis-py-cluster 

Code example

import.py:

#!/usr/bin/en python3
from rediscluster import RedisCluster
import sys
import json
def redis_cluster():
    redis_nodes = [
                   {'host':'node-0.redis.xx.us','port':6379},
                   {'host':'node-1.redis.xx.us','port':6379},
                   {'host':'node-2.redis.xx.us','port':6379},
                   {'host':'node-3.redis.xx.us','port':6379},
                   {'host':'node-4.redis.xx.us','port':6379},
                   {'host':'node-5.redis.xx.us','port': 6379}
                  ]
    try:
        client = RedisCluster(startup_nodes=redis_nodes,password='{your redis password}')
    except Exception as e:
        print(e)
        sys.exit(1)
    with open('/tmp/data.json', 'r') as f:
         data = json.load(f)
    for item in data['value']:
        member=item[0]
        score=item[1]
        print(member,score)
        mapping = {member:score,}
        client.zadd(data['key'],mapping) 
redis_cluster()

Usually You can add data from the command line zadd(key,member,score), but you can’t add data like that.

client.zadd(key,member,score)

If written in python code like above, an exception will be thrown as follow
AttributeError: ‘str’ object has no attribute ‘items’

Traceback (most recent call last):
  File "/tmp/import.py", line 36, in <module>
    redis_cluster()
  File "/tmp/import.py", line 31, in redis_cluster
    redisconn.zadd(data['key'],member,score)
  File "/apps/py3/lib64/python3.6/site-packages/redis/client.py", line 2685, in zadd
    for pair in iteritems(mapping):
  File "/apps/py3/lib64/python3.6/site-packages/redis/_compat.py", line 159, in iteritems
    return iter(x.items())
AttributeError: 'str' object has no attribute 'items'

The reason is that python’s implementation doesn’t provide a method to pass arguments like this, but instead does it in a different form, using struct dict to pass arguments.

0

评论区