Python 使用块持久化并获取数据

Python 使用块持久化并获取数据,python,python-3.x,persistence,python-asyncio,Python,Python 3.x,Persistence,Python Asyncio,我遇到了一种情况——我在Python 3.x中使用asyncio包,并使用块将数据持久化,如下所示: 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=custom

我遇到了一种情况——我在Python 3.x中使用
asyncio
包,并使用
块将数据持久化,如下所示:

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
块中获取
res
数据,但是当我退出
with
块时,应该发生持久化和获取数据。如何实现这一点?

只有Python 3.5+通过异步上下文管理器(
\uuuuu aenter\uuuu
/
\uuuu aexit\uuuu
)和
async with
支持此行为,这两个工具都添加到:

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

对不起,我没听懂。什么是
TestRepository
类?你是说你想在
\uuuuuuu退出\uuuuuu
内部进行异步调用?如果是这样的话,.@Andrew Svetlov:TestRepository()是模型层的存储库模式,我只是更改了它的名称。这个类可以很好地管理所有的模型功能,看起来你真的需要PEP 492,就像上面提到的@dano一样
@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()