【问题标题】:How to pass `keys_and_args` to redis-py' `eval` function, and on to lua script如何将 `keys_and_args` 传递给 redis-py' `eval` 函数,然后传递给 lua 脚本
【发布时间】:2019-09-22 21:10:48
【问题描述】:

我希望通过 redis 的 eval 函数(即 documented)将一些键和值从 python 传递到 lua 脚本:

eval(script, numkeys, *keys_and_args)

执行Luascript,指定numkeys脚本将接触到的keys_and_args中的键名和参数值。返回脚本的结果。

在实践中,使用register_script 返回的对象。这个函数的存在纯粹是为了 Redis API 补全。

我以this answer 为起点。该脚本增加由 1 指定的排序集中的 all 值的分数。因为我希望指定要更新的值(键名)和每个(参数值)的增量计数,我的脚本看起来像这个:

-- some logging
local loglist = "lualog"
redis.pcall("DEL", loglist)

local function logit(msg)
  redis.pcall("RPUSH", loglist, msg)
end

logit("started")

-- count & log the keys provided
local countofkeys = table.getn(KEYS)
logit(countofkeys)

-- loop through each key and increment
for n = 1, countofkeys do
  redis.call("zincrby", "test_set", ARGV[n], KEYS[n])
end

我可以从命令行运行它:

$ redis-cli --eval script.lua apple orange , 1 1

然后在 Python 中确认值已经递增:

>>> r.zrange('test_set', start = 0, end = -1, withscores=True)
[(b'apple', 1.0), (b'orange', 1.0)]

但是我不知道如何使用eval 运行它:

>>> c.eval(script,1,{'orange':1,'apple':1})
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a byte, string or number first.

>>> c.eval(script,2,'apple orange , 1 1')
redis.exceptions.ResponseError: Number of keys can't be greater than number of args

>>> c.eval(script,1,'apple orange , 1 1')
redis.exceptions.ResponseError: Error running script (call to f_aaecafd58b474f08bafa5d4fefe9db98a58b4084): @user_script:21:
 @user_script: 21: Lua redis() command arguments must be strings or integers 

文档不太清楚keys_and_args 应该是什么样子。同样在命令行numkeys 实际上并不需要事物的外观。有谁知道这应该是什么样子?

额外问题:如何避免将"test_set" 硬编码到 lua 脚本中。

【问题讨论】:

    标签: redis redis-py


    【解决方案1】:

    *keys_and_args 应该是可迭代的(例如列表) - 使用星号作为参数名称的前缀是 Pythonic 的表达方式。

    额外提示:查看 redis-py 脚本助手。

    奖励答案:脚本涉及的任何键名都需要通过KEYS 表提供。你的脚本做错了 - 阅读documentation about EVAL

    在命令行中,看起来实际上并不需要 numkeys

    这仅适用于以这种方式使用的 cli - 逗号 (',') 分隔键名和参数。

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 2013-06-04
      • 2020-11-18
      • 2014-12-07
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      相关资源
      最近更新 更多