Python:Asyncio NATS.io阻止

时间:2017-04-04 15:11:45

标签: python python-asyncio nats.io

我有麻烦使Python Asyncio NATS.io顺序运行。我有两个课程:AccountBridge 帐户拥有应用程序的逻辑,它通过NATS.io与外部服务通信思想Bridge

Main档案:

loop = asyncio.get_event_loop()
account = Account(loop, options)
asyncio.async(account.start())
loop.run_forever()

Account上课:

class Account:
    bridge = Bridge()

    def connect(self):
        result = self.bridge.connect(self.id)
        return result

Bridge上课:

def connect(self, account_id):
    data = None

    try:
        response = yield from self.nc.timed_request("bank.account.connect",
                     BankRequest(
                          method="connect",
                          data={...}
                    ), 10)
        data = json.loads(response.data.decode())
    except ErrTimeout:
        status = Messages.REQUEST_TIMED_OUT

    return Result(data=data)

我需要从帐户类中的任何位置调用account.connect()并获取连接结果(顺序)。现在我得到了generator对象

1 个答案:

答案 0 :(得分:1)

你的connect()方法可能应该是协程:

class Account:
    bridge = Bridge() # you probably want to put this in `def __init__(self)`!

    @asyncio.coroutine
    def connect(self):
        result = yield from self.bridge.connect(self.id)
        return result

class Bridge:
    @asyncio.coroutine
    def connect(self, account_id):
        data = None

        try:
            response = yield from self.nc.timed_request("bank.account.connect",
                         BankRequest(
                              method="connect",
                              data={...}
                        ), 10)
            data = json.loads(response.data.decode())
        except ErrTimeout:
            status = Messages.REQUEST_TIMED_OUT

        return Result(data=data)

resp = yield from account.connect()