Save and Retrieve Data Using a Block

I have a situation. I am using a package asyncio

with Python 3.x and store the data in a block with

, something like this:

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
        )

      

I need to get data res

in a block with

, but persistence and data fetching should happen when I exit the block with

. How can I achieve this?

+3


source to share


1 answer


This behavior is only supported in Python 3.5+ using asynchronous context managers ( __aenter__

/ __aexit__

) and async with

, both of which were added in 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())

      



Until 3.5, you need to use the try

/ block finally

with explicit calls to init / cleanup coroutines, unfortunately:

@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()

      

+1


source







All Articles