Python3 / Redis:redis.exceptions.ResponseError:未知命令“ JSON.SET”

时间:2020-09-25 15:35:01

标签: redis python-3.6

我正在尝试从this RedisLabs page运行示例程序。 我选择了选项A-来设置免费的Redis云服务器。 (好像是手动安装,则必须将JSON添加为插件。) 我能够连接并使用其他“设置”命令,但在JSON上出现错误:

  File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\client.py", line 901, in execute_command
    return self.parse_response(conn, command_name, **options)
  File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\client.py", line 915, in parse_response
    response = connection.read_response()
  File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\connection.py", line 756, in read_response
    raise response
redis.exceptions.ResponseError: unknown command 'JSON.SET'

我的Python测试程序(发布前放在示例端点中的除外):

    import redis
    import json
    import pprint
    
    host_info = "redis.us-east-1-1.ec2.cloud.redislabs.com"
    redisObj = redis.Redis(host=host_info, port=18274, password='xxx')
    
print ("Normal call to Redis")
redisObj.set('foo', 'bar')
value = redisObj.get('foo')
print(value)


capitals = {
     "Lebanon": "Beirut",
     "Norway": "Oslo",
     "France": "Paris"
 }
print ("capitals - before call to Redis")
pprint.pprint(capitals)


print("JSON call to Redis")
redisObj.execute_command('JSON.SET', 'doc', '.', json.dumps(capitals))
print("Data Saved, now fetch data back from redis")
reply = json.loads(redisObj.execute_command('JSON.GET', 'doc'))
print("reply from Redis get")
pprint.pprint(reply)

这是我创建数据库的网站的屏幕快照。我没有看到启用JSON或添加任何模块的任何选项。

enter image description here

1 个答案:

答案 0 :(得分:1)

不确定这在我创建 REDIS 数据库时是否可用,但现在可用。在 redislabs.com 上创建时,您可以打开模块,然后从列表中选择一个。

enter image description here

然后使用这个库:“rejson” from https://pypi.org/project/rejson/ 来获取方法“jsonset”方法,使用这样的代码:

rj = Client(host=config_dict['REDIS_CONFIG_HOST'], port=config_dict['REDIS_CONFIG_PORT'],                      password=config_dict['REDIS_CONFIG_PASSWORD'], decode_responses=True)

out_doc = {} 
out_doc['firstname'] = "John"
out_doc['lastname'] = "Doe"
rj.jsonset('config', Path.rootPath(), out_doc)
get_doc = rj.jsonget('config', Path.rootPath())
pprint.pprint(get_doc)