简体   繁体   English

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

[英]How reconstruct commands from json encoded object

I want to be able to encode and decode a method, arguments pair via json. 我希望能够通过json编码和解码方法,参数对。 Something like this: 像这样:

fn = 'simple_function'
arg = 'blob'

encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)

method, args = decoded
fn = getattr(self, method)
fn(*args)

But it fails because python splits the 'blob' string up into a tuple for every character (strange behaviour). 但是它失败了,因为python将'blob'字符串拆分为每个字符的元组(奇怪的行为)。 I guess it works if the args are an actual list of items. 我猜如果args是项目的实际列表,它会起作用。 It also fails if we want to not send any args, calling a function with no parameters (not enough values to unpack error.) 如果我们不希望发送任何参数,调用没有参数的函数(没有足够的值来解压缩错误),也会失败。

How to construct a very general mechanism for this? 如何为此构建一个非常通用的机制? I'm trying to make a server that can call functions on a client this way, mostly because I don't know how else to do it. 我试图制造一种可以通过这种方式在客户端上调用函数的服务器,主要是因为我不知道该怎么做。

So, looking for a solution which will let me call the functions with no, one or any number of arguments. 因此,正在寻找一种解决方案,该解决方案将使我可以不带任何参数,一个参数或任意数量的参数来调用函数。

The ideal solution might look something like this: 理想的解决方案可能看起来像这样:

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)

And will work with no args, one single string arg which does not get split up in to a list by the *, or a list of any kinds of args. 并且可以不使用任何args,一个不会被*分成一个列表的单个字符串arg或任何类型的args的列表。

Your args is a single object. 您的args是单个对象。 Not a list. 没有清单。 So you need to either 所以你需要

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

OR 要么

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) 

OR 要么

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)

Which "or" really depends on what you want. 哪个“或”实际上取决于您想要什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM