【发布时间】:2019-09-22 21:10:48
【问题描述】:
我希望通过 redis 的 eval 函数(即 documented)将一些键和值从 python 传递到 lua 脚本:
eval(script, numkeys, *keys_and_args)执行Lua
script,指定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 脚本中。
【问题讨论】: