redis 使用 lua 的时候,怎么导入外部库
def get_cookie(hkey: str) -> str | None:
from core.redis.models import client
# Use Lua scripting to get a random field from the hash set
lua_script = """
local os = require("os")
math.randomseed(os.time())
local fields = redis.call('HKEYS', KEYS[1])
if #fields == 0 then
return nil
end
local random_index = math.random(1, #fields)
local field = fields[random_index]
return random_index
"""
return client.eval(lua_script, 1, hkey)
我要导入 os 重置时间种子
运行会报错
result = context.run(func, *args)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pon/code/work/pon/vt/account_console/api.py", line 75, in get_cookie_by_parser_name
return {"cookie": get_cookie(hkey)}
^^^^^^^^^^^^^^^^
File "/home/pon/code/work/pon/vt/account_console/api.py", line 45, in get_cookie
return client.eval(lua_script, 1, hkey)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pon/.local/share/virtualenvs/account_console-Tc5w3Cdm/lib/python3.11/site-packages/redis/client.py", line 3131, in eval
return self.execute_command('EVAL', script, numkeys, *keys_and_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pon/.local/share/virtualenvs/account_console-Tc5w3Cdm/lib/python3.11/site-packages/redis/client.py", line 901, in execute_command
return self.parse_response(conn, command_name, **options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pon/.local/share/virtualenvs/account_console-Tc5w3Cdm/lib/python3.11/site-packages/redis/client.py", line 915, in parse_response
response = connection.read_response()
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pon/.local/share/virtualenvs/account_console-Tc5w3Cdm/lib/python3.11/site-packages/redis/connection.py", line 756, in read_response
raise response
redis.exceptions.ResponseError: user_script:2: Script attempted to access nonexistent global variable 'require' script: 1243ed7643e4b791767acb3602ad454e6b9098a3, on @user_script:2.