簡體   English   中英

如何從json編碼的對象重建命令

[英]How reconstruct commands from json encoded object

我希望能夠通過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'字符串拆分為每個字符的元組(奇怪的行為)。 我猜如果args是項目的實際列表,它會起作用。 如果我們不希望發送任何參數,調用沒有參數的函數(沒有足夠的值來解壓縮錯誤),也會失敗。

如何為此構建一個非常通用的機制? 我試圖制造一種可以通過這種方式在客戶端上調用函數的服務器,主要是因為我不知道該怎么做。

因此,正在尋找一種解決方案,該解決方案將使我可以不帶任何參數,一個參數或任意數量的參數來調用函數。

理想的解決方案可能看起來像這樣:

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)

並且可以不使用任何args,一個不會被*分成一個列表的單個字符串arg或任何類型的args的列表。

您的args是單個對象。 沒有清單。 所以你需要

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)

哪個“或”實際上取決於您想要什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM