使用块保持和获取数据

时间:2015-05-25 18:13:57

标签: python python-3.x persistence python-asyncio

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

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
        )

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

1 个答案:

答案 0 :(得分:1)

此行为仅在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块来显式调用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()