我正在尝试编写一个异步方法来在hive上运行查询(使用pyhive)。现在,pyhive确实支持异步查询,我不知道如何等待查询完成而不会阻塞。
我可以通过反复检查来等待查询结束,但这基本上与阻止操作相同。
def runQuery():
cursor = hive.connect('localhost').cursor()
cursor.execute('select * from mytable', async_ = True)
status = cursor.poll().operationState
while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
status = cursor.poll().operationState
return cursor.fetchall()
所以我使用异步,但是后来我不知道如何等待。我尝试了以下代码,但抛出了TypeError: object int can't be used in 'await' expression
async def runQueryAsync():
cursor = hive.connect('localhost').cursor()
cursor.execute('select * from mytable', async_ = True)
#THIS DOESN'T WORK
await cursor.poll().operationState not in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE)
return cursor.fetchall()
有任何解决方法吗?基本上,我想要一种方法,而不是说await methodCall,我说await直到此条件为真
PS:为明确起见,cursor.execute('select * from mytable', async_ = True)
在返回协程/未来的python意义上不是异步的。它只是启动查询并立即返回,因此您必须检查状态以了解查询是否完成。因此await cursor.execute('select * from mytable', async_ = True)
无法正常工作。
答案 0 :(得分:1)
您必须积极等待:
async def runQueryAsync():
cursor = hive.connect('localhost').cursor()
await cursor.execute('select * from mytable', async_ = True)
while cursor.poll().operationState not in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
await asyncio.sleep(1) # try each 1 second
return cursor.fetchall()
我不确定是否可以await cursor.execute('select * from mytable', async_ = True)
,但是如果不仅仅使用cursor.execute('select * from mytable', async_ = True)
,那么在那里使用它是很有意义的。如果它在执行过程中与await
一起使用,则可能不需要使用while
循环,因为它应在执行完成后继续执行:
async def runQueryAsync():
cursor = hive.connect('localhost').cursor()
await cursor.execute('select * from mytable', async_ = True)
return cursor.fetchall()