2017-02-10 34 views
0

我在包中廣泛使用twisted.internet.defer,我遇到了一個問題,我花了2天后無法解決。以下是我的問題場景。Python扭曲的延遲returnValue與字典不兼容

# all imports done and correct 
class infrastructure: # line 1 

    @inlineCallbacks 
    def dict_service(self): 
    client = MyClient() 
    services = yield client.listServices() # line 5 
    ret = (dict(service.name, [cont.container_id for cont in service.instances]) for service in dockerServices) 
    returnValue(ret) # line 7 

我打電話給我的客戶,它返回我的服務列表。返回類型爲twisted.internet.defer.ReturnValue

class myinterface: 
    # has infrastructure 

    def init: 
    data = dict(
     container_services=self._infrastructure.dict_service(), 
     ) 

當執行這個我得到以下錯誤,我無法理解。有人可以請幫忙。

raise TypeError(repr(o) + \" is not JSON serializable\")\nexceptions.TypeError: <DeferredWithContext at 0x4bfbb48 current result: <twisted.python.failure.Failure <type 'exceptions.NameError'>>> is not JSON serializable\n" 

是不是因爲那個包裹dictreturnValue創設問題?

回答

1

有使用returnValuedict實例沒有問題:你報

$ python -m twisted.conch.stdio 
>>> from __future__ import print_function 
>>> from twisted.internet.defer import inlineCallbacks, returnValue 
>>> @inlineCallbacks 
... def f(): 
...  d = yield {"foo": "bar"} # Yield *something* or it's not a generator 
...  returnValue(d) 
... 
>>> f().addCallback(print) 
{'foo': 'bar'} 
<Deferred at 0x7f84c51847a0 current result: None> 

錯誤:

raise TypeError(repr(o) + \" is not JSON serializable\")\nexceptions.TypeError: <DeferredWithContext at 0x4bfbb48 current result: <twisted.python.failure.Failure <type 'exceptions.NameError'>>> is not JSON serializable\n" 

使它看起來好像你有一些代碼,觸發NameError。這似乎在遞延回調發生(或以其他方式使得其方式爲遞延)和被包裹在一個Failure

<twisted.python.failure.Failure <type 'exceptions.NameError'>> 

這使得:

raise TypeError(repr(o) + \" is not JSON serializable\")\nexceptions.TypeError: <DeferredWithContext at 0x4bfbb48 current result: ...> is not JSON serializable\n" 

我不知道DeferredWithContext是什麼。我猜這是Deferred的一個子類,有一些額外的行爲。如果你能鏈接到提供這個功能的庫(這對我來說似乎是一個壞主意,但我想了解更多),那將會很好。

如果真是這樣,那麼誤差在談論具有DeferredWithContext例如上述Failure作爲它的結果:

<DeferredWithContext at 0x4bfbb48 current result: ...> 

這使得:

raise TypeError(repr(o) + \" is not JSON serializable\")\nexceptions.TypeError: ... is not JSON serializable\n" 

這似乎是來自json模塊,可以是dumpdumps函數。這是聲稱不是JSON序列化的東西被傳入。DeferredWithContext幾乎肯定不是JSON可序列化的,所以這就解釋了這個問題。

這將導致類似:

json.dumps(function_that_returns_deferred()) 

應改爲:

function_that_returns_deferred().addCallback(json.dumps) 
+0

檢查和將更新它。 – chaosguru

+0

我沒有明確任何json.dumps。但總的堆棧跟蹤看起來像這樣。 – chaosguru

+0

你的程序中的某些東西必須用JSON來做_something_。扭曲本身當然不是試圖讓JSON序列化你從inlineCallbacks-decorated函數中產生的任何值。 –