Python 3.x 在应用程序对象上存储未来状态

Python 3.x 在应用程序对象上存储未来状态,python-3.x,python-3.6,python-asyncio,aiohttp,Python 3.x,Python 3.6,Python Asyncio,Aiohttp,直接在应用程序对象上存储未来状态可以吗?下面的例子 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): a

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

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\u obj']=…
而不是
app.task\u obj=…


另请参见

这个问题表明,在应用程序上下文中存储变量是可以的,但是否有任何警告?谢谢,就这样。像往常一样,一切都在文档中。但设置属性和设置项方法之间真的有什么区别吗?设置属性在aiohttp 4.0中是被禁止的。现在,它在调试模式下发出警告。