0

我很难让 Python Asyncio NATS.io 连续运行。我有两个类:AccountAccountBridge 持有应用程序的逻辑,它Bridge通过 NATS.io 与外部服务交流思想。

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对象

4

1 回答 1

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()
于 2017-04-05T09:30:10.457 回答