2017-02-10 19 views
0

私はtwisted.internet.deferを私のパッケージに広く使用していますが、2日間費やしても解決できない問題が発生しました。以下は私の問題のシナリオです。Python Twisted Defer returnValue dictと互換性がありません

# 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 

私はサービスのリストを返すクライアントに電話しています。 listServices()戻り値の型はtwisted.internet.defer.ReturnValueです。

class myinterface: 
    # has infrastructure 

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

これを実行すると私は理解できない以下のエラーが発生します。誰かが助けてくれますか?それが問題を作成returnValuedictを包むため

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" 

はそれですか?

答えて

1

dictインスタンスでreturnValueを使用しても問題はありません:

$ 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モジュールのdumpまたはdumpsのいずれかの機能です。これは、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_を実行している必要があります。 Twisted自体は、inlineCallbacks-decorated関数から得た値をJSONで直列化しようとしていません。 –

関連する問題