我有麻烦使Python Asyncio NATS.io顺序运行。我有两个课程:Account
和Bridge
帐户拥有应用程序的逻辑,它通过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
对象
答案 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()