将未来状态存储在应用程序对象上

Store future state on application object

将未来的状态直接存储在应用对象上可以吗?下面的例子

import asyncio

async def background():
    await asyncio.sleep(1)
    print('Doing something useful in the background')
    await asyncio.sleep(1)


@aiohttp_jinja2.template('loading.html')
async def loading(request):
    app = request.app
    task = getattr(app, 'task_obj', None)
    if task is None:
        task = asyncio.ensure_future(background())
        callback = partial(done_refresh, app)
        task.add_done_callback(callback)
        app.task_obj = task


def done_refresh(app, future):
    if hasattr(app, 'task_obj'):
        # Nice! Task is done
        del app.refreshing

    exc = future.exception()
    if exc is not None:
        # Task has some exception
        print('Failed to update: %s', exc)

通常,我会在 Redis 中存储一些标记,如 in_progress,然后从我想要的任何函数中检查该值,但那样我会丢失 Task 对象本身,并且将无法访问有用的数据,如异常信息。 处理此类情况的常用方法是什么?

您的方法非常有意义,除了任务应该存储在 aiohttp 应用程序上下文中,而不是设置为属性(app['task_obj'] = ... 而不是 app.task_obj = ...

另见 https://docs.aiohttp.org/en/stable/web_advanced.html#data-sharing-aka-no-singletons-please