简体   繁体   中英

How reconstruct commands from json encoded object

I want to be able to encode and decode a method, arguments pair via 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). I guess it works if the args are an actual list of items. 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.

Your args is a single object. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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