如何从 json 编码对象重建命令



我希望能够通过json对方法,参数对进行编码和解码。像这样:

fn = 'simple_function'
arg = 'blob'
encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)
method, args = decoded
fn = getattr(self, method)
fn(*args)

但它失败了,因为python将"blob"字符串拆分为每个字符的元组(奇怪的行为)。我想如果参数是实际的项目列表,它会起作用。如果我们不想发送任何参数,调用一个没有参数的函数(没有足够的值来解压缩错误),它也失败了。

如何为此构建一个非常通用的机制?我正在尝试制作一个可以以这种方式在客户端上调用函数的服务器,主要是因为我不知道该怎么做。

因此,寻找一种解决方案,让我调用没有、一个或任意数量的参数的函数。

理想的解决方案可能如下所示:

def create_call(*args):
    cmd = json.dumps(args)
def load_call(cmd):
    method, optional_args = json.loads(*cmd)
    fn = getattr(object, method)
    fn(*optional_args)

并且将适用于没有参数,一个不会被 * 拆分为列表的单个字符串 arg,或任何类型的参数列表。

你的参数是一个对象。不是列表。所以你需要要么

fn = 'simple_function'
arg = 'blob'
encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)
method, args = decoded
fn = getattr(self, method)
fn(args) #don't try to expand the args

fn = 'simple_function'
arg = 'blob'
encoded = json.dumps([fn, [arg]]) #make sure to make a list of the arguments
decoded = json.loads(encoded)
method, args = decoded
fn = getattr(self, method)
fn(*args) 

fn = 'simple_function'
arg = 'blob'
encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)
method, args = decoded[0], decoded[1:] #cut them up into a single function name and list of args
fn = getattr(self, method)
fn(*args)

哪个"或"实际上取决于你想要什么。

最新更新