gpt4 book ai didi

python - 在 block 中持久化和获取数据

转载 作者:行者123 更新时间:2023-11-28 18:38:05 25 4
gpt4 key购买 nike

我有一种情况 - 我在 Python 3.x 中使用 asyncio 包,并将数据保存在 with block 中,如下所示:

test_repo = TestRepository()

with (yield from test_repo):
res = yield from test_repo.get_by_lim_off(
page_size=int(length),
offset=start,
customer_name=customer_name,
customer_phone=customer_phone,
return_type=return_type
)

我需要在 with block 中获取 res 数据,但是当我从 with block 退出时应该发生持久性和获取数据。我怎样才能做到这一点?

最佳答案

此行为仅在 Python 3.5+ 中受支持,通过异步上下文管理器(__aenter__/__aexit__)和async with,两者在 PEP 492 中添加:

class TestRepository:
# All your normal methods go here

async def __aenter__(self):
# You can call coroutines here
await self.some_init()

async def __aexit__(self, exc_type, exc, tb):
# You can call coroutines here
await self.do_persistence()
await self.fetch_data()


async def do_work():
test_repo = TestRepository()

async with test_repo:
res = await test_repo.get_by_lim_off(
page_size=int(length),
offset=start,
customer_name=customer_name,
customer_phone=customer_phone,
return_type=return_type
)

asyncio.get_event_loop().run_until_complete(do_work())

在 3.5 之前,您必须使用 try/finally block 显式调用 init/cleanup 协程,不幸的是:

@asyncio.coroutine
def do_work():
test_repo = TestRepository()

yield from test_repo.some_init()
try:
res = yield from test_repo.get_by_lim_off(
page_size=int(length),
offset=start,
customer_name=customer_name,
customer_phone=customer_phone,
return_type=return_type
)
finally:
yield from test_repo.do_persistence()
yield from test_repo.fetch_data()

关于python - 在 block 中持久化和获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com