我正在使用异步工作流程,其中包含同步代码。如何检查同步函数是否阻塞,以确保执行期间没有任何中断。
async def download_upload_xmls_async(message,count,id,conn1,cursor1,conn2,cursor2):
# SOME CODE
xml = await req(urlX, headers)
print('Got message')
write(message_count, id, conn1, cursor1)
print('Wrote progress')
send_message("Send" + xml, id, conn2, cursor2)
print('Sent message')
write_locally(data)
await message.ack()
在上面的代码中,如何检查函数 write 和 send_message 是否是非阻塞的?他们与数据库一起工作,我无法访问该数据库来检查一切是否按预期工作。我还可以假设,如果函数 write_locally 正常工作,我以前的函数也可以正常工作吗?
函数 write 和 send_message 执行几乎相同的操作 - 它们使用传递给它们的连接和游标获取数据并在 PostgreSQL 数据库上执行查询。函数 write_locally 写入 csv 文件。
def send_message(message, id, con, cur, **nargs):
params = {
#some params
}
union_params= {**params, **nargs}
data = json.dumps(union_params, ensure_ascii=False)
cur.execute(
#Query
)
con.commit()
我还必须补充一点,连接和光标是使用 aiopg 创建的,因此它们的所有方法都是协程。
最佳答案
如果连接和游标具有协程方法,则编写的 send_message
不会阻塞事件循环。
但是,它不会做任何事情,因为它无法等待它调用的协程。它需要使用 async def
进行定义,并且需要 await
对 cur.execute(...)
和 cur 的调用.commit()
。 download_upload_xmls_async
同样无法等待 send_message
。正确的代码应该如下所示:
async def download_upload_xmls_async(message, count, id, conn1, cursor1, conn2, cursor2):
... some code here ...
# note the await
await send_message("Send" + xml, id, conn2, cursor2)
# write_locally doesn't need to be a coroutine because
# it (presumably) doesn't block
write_locally(data)
await message.ack()
# note "async def"
async def send_message(message, id, con, cur, **nargs):
params = {
#some params
}
union_params= {**params, **nargs}
data = json.dumps(union_params, ensure_ascii=False)
# note the await
await cur.execute(
#Query
)
await con.commit()
关于python - 如何检查函数是否阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494909/